@serifpersia/dango 3.4.2 → 3.4.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/client/dist/assets/{AnimeCard-CIwTZI3D.js → AnimeCard-4CEz8Buu.js} +1 -1
- package/client/dist/assets/AnimeInfo-DyX9qTwg.js +1 -0
- package/client/dist/assets/AnimeInfoPage-Dvp_c8vK.js +2 -0
- package/client/dist/assets/Asmr-qg3lMAJn.js +2 -0
- package/client/dist/assets/{AsmrResetProgressModal-BDpA07Fa.js → AsmrResetProgressModal-BpPlg_Vv.js} +1 -1
- package/client/dist/assets/AvSyncCalibrator-C2wu1ydI.css +1 -0
- package/client/dist/assets/AvSyncCalibrator-FJllOgOH.js +10 -0
- package/client/dist/assets/Home-A7gCeEST.js +1 -0
- package/client/dist/assets/Insights-G9IXepHJ.js +1 -0
- package/client/dist/assets/{LibraryListPage-DWbcek1i.js → LibraryListPage-Bh2qCJPh.js} +1 -1
- package/client/dist/assets/{ListeningList-CcuxBzy1.js → ListeningList-Czv4cTRl.js} +1 -1
- package/client/dist/assets/{Manga-DpLaW39C.js → Manga-qdAAS1z7.js} +1 -1
- package/client/dist/assets/MangaInfoPage-1rTgZzf2.js +1 -0
- package/client/dist/assets/MangaReadPage-CeyxPG6w.js +1 -0
- package/client/dist/assets/{MangaResetProgressModal-CYguBG2f.js → MangaResetProgressModal-C_ppotmh.js} +1 -1
- package/client/dist/assets/Mature-Bkhxnr3K.js +1 -0
- package/client/dist/assets/{MediaCard-p29DqyKX.js → MediaCard-BQZsutEo.js} +1 -1
- package/client/dist/assets/Music-C0rGzSbi.js +1 -0
- package/client/dist/assets/{OptionListMenu-C1pvpu8X.js → OptionListMenu-CyfpCBEy.js} +1 -1
- package/client/dist/assets/Player-yhiTlpYU.js +56 -0
- package/client/dist/assets/PlayerSettings-icy4SfQa.js +1 -0
- package/client/dist/assets/{QueueOptionsButton-CWdoe1_I.js → QueueOptionsButton-5eloKF5J.js} +1 -1
- package/client/dist/assets/{QueueRail-BBpn9CII.js → QueueRail-DaMjlKL4.js} +1 -1
- package/client/dist/assets/Radio-FxGqCxR4.js +1 -0
- package/client/dist/assets/{ReadingList-D4xQ9tlw.js → ReadingList-CCm3IAbt.js} +1 -1
- package/client/dist/assets/{ResetProgressModal-JFlbXy7W.js → ResetProgressModal-CeI4V3Y5.js} +1 -1
- package/client/dist/assets/{Search-D-ocogP-.js → Search-qpILaAiQ.js} +1 -1
- package/client/dist/assets/Settings-Bw9M3NGz.js +21 -0
- package/client/dist/assets/{SkeletonGrid-N67HqYXx.js → SkeletonGrid-0dY_xMq3.js} +1 -1
- package/client/dist/assets/{Trackers-C_SPMGKx.js → Trackers-Zy5GOs0P.js} +2 -2
- package/client/dist/assets/Tv-Bx7tGS57.css +1 -0
- package/client/dist/assets/Tv-DREwc7BX.js +4 -0
- package/client/dist/assets/TvInfo-CHIsVzZ0.js +1 -0
- package/client/dist/assets/{TvPopup-DEB6Ufq4.js → TvPopup-D_tVTyZ2.js} +1 -1
- package/client/dist/assets/{TvSearch-grOUL0Bc.js → TvSearch-BVxedBW-.js} +1 -1
- package/client/dist/assets/{TvWatchlist-CBI21Vge.js → TvWatchlist-BEIwq9R9.js} +1 -1
- package/client/dist/assets/{Watchlist-5cDHUoC8.js → Watchlist-CSngjqlz.js} +1 -1
- package/client/dist/assets/{hls-DySVERd_.js → hls-D48GVTkk.js} +1 -1
- package/client/dist/assets/index-CVB5dYhT.js +178 -0
- package/client/dist/assets/{useAnimeInfoData-BMwVSGhZ.js → useAnimeInfoData-DxdOg_B7.js} +1 -1
- package/client/dist/assets/useAsmr-ClckxnPe.js +1 -0
- package/client/dist/assets/{useAsmrPopup-CY-6b88q.js → useAsmrPopup-Bbgxefy_.js} +1 -1
- package/client/dist/assets/useMangaLibrary-B3_BUKVk.js +1 -0
- package/client/dist/assets/{useMangaPopup-_pNXvRYJ.js → useMangaPopup-Celk4lzf.js} +1 -1
- package/client/dist/assets/{useProviders-CKSedfqb.js → useProviders-pwxPZPHh.js} +1 -1
- package/client/dist/assets/useTv-D9sQrDop.js +1 -0
- package/client/dist/assets/useTvLibrary-UsQpgBTB.js +1 -0
- package/client/dist/index.html +1 -1
- package/package.json +3 -3
- package/server/dist/app-hono.js +15 -37
- package/server/dist/db/drizzle.js +2 -18
- package/server/dist/db.js +3 -2
- package/server/dist/hono/tv.js +9 -5
- package/server/dist/hono/watchlist.js +10 -108
- package/server/dist/lib/migration.js +0 -5
- package/server/dist/providers/remote-loader.js +40 -1
- package/server/dist/providers/remote-types.js +9 -2
- package/server/dist/server.js +50 -182
- package/server/dist/sync.js +173 -704
- package/server/dist/trpc/routers/auth.js +2 -71
- package/server/dist/trpc/routers/continue-watching.js +0 -2
- package/server/dist/trpc/routers/data.js +0 -1
- package/server/dist/trpc/routers/discord.js +8 -0
- package/server/dist/trpc/routers/progress.js +95 -1
- package/server/dist/trpc/routers/queue.js +0 -2
- package/server/dist/trpc/routers/watchlist.js +0 -7
- package/server/dist/trpc/validation.js +64 -0
- package/server/package.json +2 -2
- package/client/dist/assets/AnimeInfo-DlfvDaR8.js +0 -1
- package/client/dist/assets/AnimeInfoPage-B3EPwtzx.js +0 -2
- package/client/dist/assets/Asmr-DCirAWM6.js +0 -2
- package/client/dist/assets/AvSyncCalibrator-BPa6KaGC.css +0 -1
- package/client/dist/assets/AvSyncCalibrator-BroSW86T.js +0 -10
- package/client/dist/assets/Home-DEjYtHbs.js +0 -1
- package/client/dist/assets/Insights-B3b6u8RW.js +0 -1
- package/client/dist/assets/MangaInfoPage-B7FPC4a_.js +0 -1
- package/client/dist/assets/MangaReadPage-Dx0qAAFe.js +0 -1
- package/client/dist/assets/Mature-AScDPmWW.js +0 -1
- package/client/dist/assets/Music-DFInMskb.js +0 -1
- package/client/dist/assets/Player-D-8zY3cx.js +0 -56
- package/client/dist/assets/PlayerSettings-CfJjs_0Q.js +0 -1
- package/client/dist/assets/Radio-DCgO5hAS.js +0 -1
- package/client/dist/assets/Settings-BsFbgkdy.js +0 -21
- package/client/dist/assets/Tv-D7s0Kqqx.js +0 -4
- package/client/dist/assets/Tv-ZEA45gXK.css +0 -1
- package/client/dist/assets/TvInfo-CrmCSFDF.js +0 -1
- package/client/dist/assets/index-HZNJp28e.js +0 -178
- package/client/dist/assets/useAsmr-BLc7FwPm.js +0 -1
- package/client/dist/assets/useMangaLibrary-XFRTq5Qg.js +0 -1
- package/client/dist/assets/useMatureConsent-Cra09TA0.js +0 -1
- package/client/dist/assets/useTv-Dizj6G4R.js +0 -1
- package/client/dist/assets/useTvLibrary-twjHQ89n.js +0 -1
|
@@ -1,56 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/PlayerSettings-CfJjs_0Q.js","assets/vendor-core-DfaOB3Rn.js","assets/vendor-icons-DrybRNxP.js","assets/OptionListMenu-C1pvpu8X.js","assets/AvSyncCalibrator-BroSW86T.js","assets/index-HZNJp28e.js","assets/vendor-query-BBT5_sHx.js","assets/index-Cc1Up_NI.css","assets/useProviders-CKSedfqb.js","assets/AvSyncCalibrator-BPa6KaGC.css","assets/PlayerSettings-Bj6SsmQ2.css"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{g as Wt,h as x,u as r,P as Or,z as Wr,d as Q,A as v,q as O,y as Vr,T as ut,o as Ur,a as qr,c as Qr,_ as zr,S as kt}from"./vendor-core-DfaOB3Rn.js";import{_ as fr,S as Nt,g as Gr,t as Le,z as Ke,O as Kr,k as Hr,l as jr,m as Yr,n as Xr,d as Jr,u as Zr,M as Be,B as st,P as en,f as tn}from"./index-HZNJp28e.js";import{u as hr,b as ur,a as jt}from"./vendor-query-BBT5_sHx.js";import{C as rn,S as nn,U as sn,a as on,p as Yt,s as an,l as ln,u as cn,b as un,i as dn,c as pn,d as dr,f as pr,e as mn,g as fn,h as hn,r as vn,j as Ge,E as gn,k as bn,m as u,n as yn,A as Sn,P as En,o as wn,q as kn}from"./AvSyncCalibrator-BroSW86T.js";import{I as q}from"./vendor-icons-DrybRNxP.js";import{l as Tn}from"./hls-DySVERd_.js";import{u as Cn}from"./useMatureConsent-Cra09TA0.js";import{u as Rn}from"./useIsMobile-Dvx1uJ82.js";import{s as ot,Q as Mn}from"./QueueRail-BBpn9CII.js";import{u as vr,f as _n}from"./useProviders-CKSedfqb.js";import{u as Nn,Q as Pn}from"./QueueOptionsButton-CWdoe1_I.js";import{A as xn}from"./AnimeMetaDetails-BogOi_bM.js";import{S as An}from"./SynopsisText-B3Sa5pRv.js";import"./vendor-ui-3qrARCPr.js";const Bn={soft:"Softsub",hard:"Hardsub",mixed:"Mixed"},Ln={direct:"Direct",embed:"Embed",cookie:"Needs cookie"},In=["direct","cookie","embed"],Dn="_controlsOverlay_1b7ea_1",$n="_hidden_1b7ea_21",Fn="_topControls_1b7ea_27",On="_backBtn_1b7ea_47",Wn="_videoTitleInfo_1b7ea_67",Vn="_animeTitle_1b7ea_73",Un="_episodeNumber_1b7ea_81",qn="_bottomControls_1b7ea_89",Qn="_progressBarContainer_1b7ea_108",zn="_progressBar_1b7ea_108",Gn="_thumb_1b7ea_127",Kn="_scrubbing_1b7ea_142",Hn="_watchedBar_1b7ea_146",jn="_bufferedBar_1b7ea_147",Yn="_timeBubble_1b7ea_185",Xn="_skipSegment_1b7ea_219",Jn="_op_1b7ea_229",Zn="_ed_1b7ea_232",es="_recap_1b7ea_235",ts="_bottomControlsRow_1b7ea_239",rs="_leftControls_1b7ea_247",ns="_rightControls_1b7ea_248",ss="_controlBtn_1b7ea_255",os="_theaterBtn_1b7ea_296",as="_nextEpisodeBtn_1b7ea_300",is="_active_1b7ea_317",ls="_timeDisplay_1b7ea_321",cs="_skipControls_1b7ea_329",us="_skipBtn_1b7ea_335",ds="_volumeContainer_1b7ea_376",ps="_volumeSlider_1b7ea_382",ms="_playerPageLayout_1b7ea_440",fs="_videoPlayerWrapper_1b7ea_444",hs="_playerInfoContainer_1b7ea_449",vs="_visible_1b7ea_566",gs="_shortcuts_1b7ea_584",w={controlsOverlay:Dn,hidden:$n,topControls:Fn,backBtn:On,videoTitleInfo:Wn,animeTitle:Vn,episodeNumber:Un,bottomControls:qn,progressBarContainer:Qn,progressBar:zn,thumb:Gn,scrubbing:Kn,watchedBar:Hn,bufferedBar:jn,timeBubble:Yn,skipSegment:Xn,op:Jn,ed:Zn,recap:es,bottomControlsRow:ts,leftControls:rs,rightControls:ns,controlBtn:ss,theaterBtn:os,nextEpisodeBtn:as,active:is,timeDisplay:ls,skipControls:cs,skipBtn:us,volumeContainer:ds,volumeSlider:ps,playerPageLayout:ms,videoPlayerWrapper:fs,playerInfoContainer:hs,visible:vs,shortcuts:gs},bs=Wr(()=>fr(()=>import("./PlayerSettings-CfJjs_0Q.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10]))),ys=({player:n,isAutoplayEnabled:g,onAutoplayChange:k,showNextEpisodeButton:j,onNextEpisode:b,videoSources:R,selectedSource:E,selectedLink:L,onSourceChange:B,loadingVideo:z,skipIntervals:ke,animeTitle:e,episodeNumber:f,isTheaterMode:Te,onTheaterModeToggle:N,anime4kEnabled:ae,onAnime4kToggle:Fe,anime4kSupported:W,anime4kProfile:A,onAnime4kProfileChange:$,anime4kInitializing:Oe,anime4kError:He,videoDelayEnabled:a,onVideoDelayToggle:p,videoDelayMs:M,onVideoDelayChange:pe,onCalibrateAvSync:We,fallbackChoice:je,onFallbackChoiceChange:be,children:Ye,overlays:ee,isInteractingExtra:Ce=!1,className:ce,hideChrome:d=!1})=>{const{state:o,refs:l,actions:h}=n,{showSettings:D}=o,{setShowSettings:Y,setShowVolumeSlider:G}=h,V=Wt.useRef(null),ie=Wt.useRef(null);x(()=>{const m=P=>{V.current&&!V.current.contains(P.target)&&ie.current&&!ie.current.contains(P.target)&&D&&Y(!1)};return D&&document.addEventListener("mousedown",m),()=>{document.removeEventListener("mousedown",m)}},[D,Y]);const ye=Wt.useRef(null),at=m=>{l.videoRef.current&&(l.videoRef.current.volume=m,l.videoRef.current.muted=m===0,localStorage.setItem("playerVolume",m.toString()))},Xe=m=>{!l.videoRef.current||isNaN(o.duration)||o.duration===0||(l.videoRef.current.currentTime=m*o.duration,h.sendProgressUpdate(!1,!0))},bt=()=>{l.videoRef.current&&(h.setIsScrubbing(!0),h.wasPlayingBeforeScrub.current=!l.videoRef.current.paused,l.videoRef.current.pause())},K=m=>{!l.videoRef.current||!o.duration||(l.videoRef.current.currentTime=m*o.duration)},it=()=>{h.setIsScrubbing(!1),h.wasPlayingBeforeScrub.current&&l.videoRef.current?.play()},dt=m=>{if(!l.videoRef.current)return;h.setActiveSubtitleTrack(m);try{if(m===null||m==="off")localStorage.setItem("playerSubtitlesEnabled","false");else{localStorage.setItem("playerSubtitlesEnabled","true");const T=o.availableSubtitles.find(Ue=>Ue.label===m||Ue.lang===m);T?localStorage.setItem("playerLastSubtitle",an(T)):localStorage.setItem("playerLastSubtitle",m)}}catch{}let P=!1;Array.from(l.videoRef.current.textTracks).forEach(T=>{const Ie=m!==null&&m!=="off"&&(T.language===m||T.label===m)&&!P;T.mode=Ie?"showing":"hidden",Ie&&(P=!0)})},te=o.activeSubtitleTrack!==null&&o.activeSubtitleTrack!=="off",ue=()=>{if(!l.videoRef.current)return;if(te){dt("off");return}if(o.availableSubtitles.length===0)return;let m=null;try{m=localStorage.getItem("playerLastSubtitle")}catch{}const P=Yt(o.availableSubtitles,{lastKey:m,enabled:!0});if(P<0)return;const T=o.availableSubtitles[P];dt(T.label||T.lang)},Re=()=>o.isMuted||o.volume===0?r(q,{name:"volume-mute"}):o.volume<.5?r(q,{name:"volume-down"}):r(q,{name:"volume-up"}),yt=r("div",{className:`${w.controlsOverlay} ${!o.showControls&&!D&&!o.isScrubbing?w.hidden:""} `,"data-speed-boost-ignore":"true",style:{pointerEvents:"none",background:"none"},children:r("div",{className:w.topControls,onClick:m=>m.stopPropagation(),children:[r("button",{className:w.backBtn,onClick:m=>{m.stopPropagation(),window.history.back()},title:"Back","aria-label":"Back",children:r(q,{name:"chevron-left"})}),r("div",{className:w.videoTitleInfo,children:[r("span",{className:w.animeTitle,children:e}),f&&r("span",{className:w.episodeNumber,children:["Episode ",f]})]})]})}),F=!z&&!o.isBuffering&&o.duration>0?r(rn,{isPlaying:o.isPlaying,onTogglePlay:h.togglePlay,onSkipBack:()=>h.seek(-10),onSkipForward:()=>h.seek(10)}):null,Ve=r("div",{className:`${w.controlsOverlay} ${!o.showControls&&!D&&!o.isScrubbing?w.hidden:""} `,"data-speed-boost-ignore":"true",style:{pointerEvents:"none",background:"none",justifyContent:"flex-end"},children:r("div",{className:w.bottomControls,"data-speed-boost-ignore":"true",onClick:m=>m.stopPropagation(),children:[r(nn,{classes:{container:w.progressBarContainer,scrubbing:w.scrubbing,timeBubble:w.timeBubble,bar:w.progressBar,buffered:w.bufferedBar,watched:w.watchedBar,thumb:w.thumb},videoRef:l.videoRef,duration:o.duration,formatTime:h.formatTime,isScrubbing:o.isScrubbing,onSeek:Xe,onScrubStart:bt,onScrubMove:K,onScrubEnd:it,timeLabelRef:ye,children:[o.duration>0&&n.state.currentSkipInterval&&r("div",{className:`${w.skipSegment} ${w[n.state.currentSkipInterval.skip_type]} `,style:{left:`${n.state.currentSkipInterval.start_time/o.duration*100}% `,width:`${(n.state.currentSkipInterval.end_time-n.state.currentSkipInterval.start_time)/o.duration*100}% `}}),ke.map(m=>{const P=m.start_time/o.duration*100,T=(m.end_time-m.start_time)/o.duration*100;return r("div",{className:`${w.skipSegment} ${w[m.skip_type]} `,style:{left:`${P}% `,width:`${T}% `},title:m.skip_type.toUpperCase()},m.skip_id)})]}),r("div",{className:w.bottomControlsRow,children:[r("div",{className:w.leftControls,children:[r("button",{className:w.controlBtn,onClick:h.togglePlay,"aria-label":o.isPlaying?"Pause":"Play",children:o.isPlaying?r(q,{name:"pause"}):r(q,{name:"play"})}),r(sn,{muted:o.isMuted,volume:o.volume,volumeIcon:Re(),buttonClassName:w.controlBtn,onToggleMute:h.toggleMute,onVolumeChange:at,onExpandedChange:m=>G(m)}),r("span",{className:w.timeDisplay,ref:ye,children:[h.formatTime(0)," / ",h.formatTime(o.duration)]}),o.currentSkipInterval&&!o.isAutoSkipEnabled&&r("button",{className:w.controlBtn,onClick:()=>{l.videoRef.current&&o.currentSkipInterval&&(l.videoRef.current.currentTime=o.currentSkipInterval.end_time,h.setCurrentSkipInterval(null))},children:["Skip ",o.currentSkipInterval.skip_type==="op"?"Opening":"Ending"]})]}),r("div",{className:w.rightControls,children:[r("div",{className:w.skipControls,children:j&&r("button",{className:w.nextEpisodeBtn,onClick:b,title:"Play next episode",children:"Next EP"})}),r("button",{className:`${w.controlBtn} ${te?w.active:""}`,onClick:ue,title:te?"Disable Subtitles":"Enable Subtitles","aria-label":"Toggle Subtitles",children:r(q,{name:"closed-captioning",size:22})}),r("button",{ref:ie,className:`${w.controlBtn} ${D?w.active:""} `,onClick:()=>Y(!D),"aria-label":"Settings",children:r(q,{name:"cog"})}),r("button",{className:`${w.controlBtn} ${w.theaterBtn} ${Te?w.active:""} `,onClick:m=>{m.stopPropagation(),N()},title:Te?"Exit Theater Mode":"Theater Mode","aria-label":Te?"Exit Theater Mode":"Theater Mode",children:r(q,{name:"tv"})}),r("button",{className:w.controlBtn,onClick:h.toggleFullscreen,"aria-label":o.isFullscreen?"Exit Fullscreen":"Fullscreen",children:o.isFullscreen?r(q,{name:"compress"}):r(q,{name:"expand"})})]})]})]})}),pt=r(Or,{fallback:null,children:r(bs,{ref:V,isOpen:D,onClose:()=>Y(!1),videoSources:R,currentSource:E,currentLink:L,onSourceChange:B,subtitles:o.availableSubtitles,activeSubtitleTrack:o.activeSubtitleTrack,onSubtitleChange:dt,subtitleSettings:{fontSize:o.subtitleFontSize,position:o.subtitlePosition,bgOpacity:o.subtitleBgOpacity,bgColor:o.subtitleBgColor,textColor:o.subtitleTextColor,edge:o.subtitleEdge,bold:o.subtitleBold},onSubtitleSettingsChange:(m,P)=>{const T=(Ue,Ie)=>{try{localStorage.setItem(Ue,String(Ie))}catch{}};switch(m){case"fontSize":h.setSubtitleFontSize(P),T("subtitleFontSize",P);break;case"position":h.setSubtitlePosition(P),T("subtitlePosition",P);break;case"bgOpacity":h.setSubtitleBgOpacity(P),T("subtitleBgOpacity",P);break;case"bgColor":h.setSubtitleBgColor(P),T("subtitleBgColor",P);break;case"textColor":h.setSubtitleTextColor(P),T("subtitleTextColor",P);break;case"edge":h.setSubtitleEdge(P),T("subtitleEdge",P);break;case"bold":h.setSubtitleBold(P),T("subtitleBold",P);break}},useNativeControls:o.useNativeControls,onNativeControlsToggle:h.setUseNativeControls,anime4kEnabled:ae,onAnime4kToggle:Fe,anime4kSupported:W,anime4kProfile:A,onAnime4kProfileChange:$,anime4kInitializing:Oe,anime4kError:He,videoDelayEnabled:a,onVideoDelayToggle:p,videoDelayMs:M,onVideoDelayChange:pe,onCalibrateAvSync:We,isAutoSkipEnabled:o.isAutoSkipEnabled,onAutoSkipChange:m=>{h.setIsAutoSkipEnabled(m);try{localStorage.setItem("autoSkipEnabled",m.toString())}catch{}},isAutoplayEnabled:g,onAutoplayChange:k,fallbackChoice:je,onFallbackChoiceChange:be})}),lt=D?r("div",{"data-speed-boost-ignore":"true",onClick:m=>m.stopPropagation(),children:pt}):null;return r(on,{player:n,topBar:yt,centerControls:F,bottomBar:!z&&!o.isBuffering&&o.duration>0?Ve:null,settingsPanel:lt,overlays:ee,isInteracting:Ce,className:ce,chromeDisabled:d,children:Ye})},Ss=({count:n=3})=>r("section",{className:ot.section,children:[r("div",{className:ot.header,children:r("button",{className:ot.headerToggle,disabled:!0,children:[r("span",{className:ot.title,children:r(Nt,{width:"60px",height:"1.2rem",variant:"text"})}),r(q,{name:"chevron-down",style:{opacity:.3}})]})}),r("div",{className:ot.list,children:Array.from({length:n}).map((g,k)=>r("div",{className:ot.item,style:{pointerEvents:"none"},children:[r("div",{className:ot.dragHandle,style:{opacity:.2},children:r(Nt,{width:"16px",height:"16px",variant:"rectangular"})}),r("div",{className:ot.thumbnail,style:{overflow:"hidden",background:"transparent"},children:r(Nt,{width:"100%",height:"100%",variant:"rectangular"})}),r("div",{className:ot.meta,children:[r(Nt,{width:"80%",height:"1.2rem",variant:"text",className:"mb-2"}),r(Nt,{width:"40%",height:"0.8rem",variant:"rectangular",style:{borderRadius:"var(--radius-sm)"}})]})]},k))})]}),Es="_sourceSelectionContainer_c5tub_76",ws="_providerSelectContainer_c5tub_89",ks="_providerSelect_c5tub_89",Ts="_sourceSelect_c5tub_76",Cs="_sourceButtons_c5tub_145",Rs="_sourceButton_c5tub_145",Ms="_active_c5tub_170",gt={sourceSelectionContainer:Es,providerSelectContainer:ws,providerSelect:ks,sourceSelect:Ts,sourceButtons:Cs,sourceButton:Rs,active:Ms},_s=({selectedProvider:n,onProviderChange:g,isAdult:k,options:j})=>{const b=j&&j.length>0?j:[],R=k===void 0?b:b.filter(E=>E.mature===k);return r("div",{className:gt.providerSelectContainer,children:[r("h4",{children:"Provider"}),r("select",{className:gt.providerSelect,value:n,onChange:E=>g(E.target.value),children:In.map(E=>{const L=R.filter(B=>(B.tier??"direct")===E);return L.length===0?null:r("optgroup",{label:Ln[E],children:L.map(B=>r("option",{value:B.value,children:B.sub?`${B.label} (${Bn[B.sub]})`:B.label},B.value))},E)})})]})},Ns=({videoSources:n,selectedSource:g,selectedLink:k,onSourceChange:j,onLinkChange:b})=>{const R=Array.isArray(n)?n:[];if(R.length===0)return null;const E=g?.type==="iframe"&&(g.links?.length??0)>1;return r("div",{className:gt.sourceSelectionContainer,children:[r("h4",{children:"Source"}),r("div",{className:gt.sourceButtons,children:R.map((L,B)=>r("button",{className:`${gt.sourceButton} ${g?.sourceName===L.sourceName?gt.active:""} `,onClick:()=>j(L),children:L.sourceName},`${L.sourceName}-${B}`))}),E&&r("select",{className:gt.sourceSelect,"aria-label":"Fallback embed quality",value:k?.link??g.links[0]?.link??"",onChange:L=>{const B=g.links.find(z=>z.link===L.target.value);B&&b(B)},children:g.links.map(L=>r("option",{value:L.link,children:L.resolutionStr},L.link))})]})},Ps=Wt.memo(Ns,(n,g)=>n.selectedSource?.sourceName===g.selectedSource?.sourceName&&n.selectedLink?.link===g.selectedLink?.link&&n.videoSources===g.videoSources),xs={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}},As={low:"ModeB",balanced:"ModeA",high:"ModeAA",denoise:"ModeC"},Bs=5,Ls=15e3,Is=`
|
|
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 Ds({videoRef:n,canvasRef:g,profile:k="balanced",delayMs:j=0}){const[b,R]=Q(!1),[E,L]=Q(()=>{try{return localStorage.getItem("anime4kEnabled")==="true"}catch{return!1}}),[B,z]=Q(!1),[ke,e]=Q(null),[f,Te]=Q(0),N=v(0),ae=v(null),Fe=v(null),W=v(null),A=v(null),$=v(null),Oe=v(null),He=v(null),a=v(null),p=v(null),M=v(!1),pe=v(-1),We=v(0),je=v(j);je.current=j;const be=v([]),Ye=v(!1),ee=v(!1),Ce=v(!1),ce=v(null),d=v(-1),o=v(-1),l=v(!1),h=v(0);x(()=>{async function G(){if(typeof navigator>"u"||!navigator.gpu){R(!1);return}try{const V=await navigator.gpu.requestAdapter();R(!!V)}catch{R(!1)}}G()},[]),x(()=>{if(!E||!b)return;let G=!1;const V=++N.current,ie=K=>{if(K)try{K.close()}catch{}},ye=()=>{for(const K of be.current)ie(K.bitmap);be.current=[]},at=K=>Math.max(8,Math.min(40,Math.ceil(K/16.7)+4));function Xe(){p.current!==null&&(cancelAnimationFrame(p.current),p.current=null)}async function bt(){let K=n.current;const it=g.current;if(!K||!it||N.current!==V)return;const dt=performance.now()+Ls;for(;(!K||K.videoWidth===0)&&performance.now()<dt;){if(await new Promise(T=>requestAnimationFrame(T)),G||N.current!==V)return;K=n.current}if(!K||K.videoWidth===0){!G&&N.current===V&&(e("Timed out waiting for video metadata"),z(!1),L(!1));return}const te=K.videoWidth,ue=K.videoHeight,Re=Math.max(te,ue),yt=window.innerWidth,F=window.innerHeight,Ve=Math.max(yt,F),pt=Re<Ve?Ve/Re:1,lt=xs[k],m=Re<=480?lt.sd:Re<=720?lt.hd:Re<=1080?lt.fhd:1,P=Math.min(m,pt);it.width=Math.round(te*P),it.height=Math.round(ue*P),z(!0),e(null),We.current=0,pe.current=-1,d.current=-1,o.current=-1,l.current=!1,h.current=0,ye(),M.current=!1;try{let T=function(){G||N.current!==V||(Xe(),p.current=requestAnimationFrame(()=>{mt()}))};const{ModeA:Ue,ModeB:Ie,ModeC:Tt,ModeAA:Jt}=await fr(async()=>{const{ModeA:I,ModeB:re,ModeC:$e,ModeAA:ne}=await import("./index-BOKlZEHq.js").then(me=>me.i);return{ModeA:I,ModeB:re,ModeC:$e,ModeAA:ne}},[]);if(!navigator.gpu)throw new Error("WebGPU not available");const Pt=await navigator.gpu.requestAdapter();if(!Pt)throw new Error("No GPU adapter found");const _=await Pt.requestDevice();if(!_)throw new Error("Failed to get GPU device");const De=it.getContext("webgpu");if(!De)throw new Error("Failed to get WebGPU context");const Je=navigator.gpu.getPreferredCanvasFormat();De.configure({device:_,format:Je,alphaMode:"premultiplied"});const Se=_.createTexture({size:[te,ue],format:"rgba16float",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT}),Ct=As[k],qe=Math.round(te*P),Qe=Math.round(ue*P),Ze=(()=>{switch(Ct){case"ModeB":return new Ie({device:_,inputTexture:Se,nativeDimensions:{width:te,height:ue},targetDimensions:{width:qe,height:Qe}});case"ModeC":return new Tt({device:_,inputTexture:Se,nativeDimensions:{width:te,height:ue},targetDimensions:{width:qe,height:Qe}});case"ModeAA":return new Jt({device:_,inputTexture:Se,nativeDimensions:{width:te,height:ue},targetDimensions:{width:qe,height:Qe}});default:return new Ue({device:_,inputTexture:Se,nativeDimensions:{width:te,height:ue},targetDimensions:{width:qe,height:Qe}})}})(),ze=Ze.getOutputTexture(),Me=_.createSampler({magFilter:"linear",minFilter:"linear"}),et=_.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
|
-
`}),St=_.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}]}),_e=_.createRenderPipeline({layout:_.createPipelineLayout({bindGroupLayouts:[St]}),vertex:{module:et,entryPoint:"vs"},fragment:{module:et,entryPoint:"fs",targets:[{format:Je}]},primitive:{topology:"triangle-list"}}),xt=_.createBindGroup({layout:St,entries:[{binding:0,resource:ze.createView()},{binding:1,resource:Me}]});try{const I=_.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,externalTexture:{}},{binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}]}),re=_.createShaderModule({code:Is}),$e=_.createRenderPipeline({layout:_.createPipelineLayout({bindGroupLayouts:[I]}),vertex:{module:re,entryPoint:"vs"},fragment:{module:re,entryPoint:"fs",targets:[{format:"rgba16float"}]},primitive:{topology:"triangle-list"}});ce.current={pipeline:$e,layout:I,inputView:Se.createView()}}catch{ce.current=null}if(N.current!==V){Se.destroy(),_.destroy();return}ae.current=_,Fe.current=De,W.current=Ze,A.current=Se,$.current=ze,Oe.current=_e,He.current=Me,a.current=St,ee.current=!1,Ce.current=!1;async function Rt(){const I=ce.current;if(!I||ee.current)return!1;const re=n.current;if(!re)return!1;const $e=!Ce.current;$e&&_.pushErrorScope("validation");try{const ne=_.importExternalTexture({source:re}),me=_.createBindGroup({layout:I.layout,entries:[{binding:0,resource:ne},{binding:1,resource:Me}]}),Ee=_.createCommandEncoder(),Ne=Ee.beginRenderPass({colorAttachments:[{view:I.inputView,loadOp:"load",storeOp:"store"}]});Ne.setPipeline(I.pipeline),Ne.setBindGroup(0,me),Ne.draw(6),Ne.end(),_.queue.submit([Ee.finish()])}catch{return ee.current=!0,ce.current=null,!1}if($e){const ne=await _.popErrorScope().catch(()=>null);if(ne)return console.warn("[anime4k] blit probe failed:",ne.message),ee.current=!0,ce.current=null,!1;Ce.current=!0}return!0}z(!1);async function mt(){if(G||N.current!==V)return;const I=n.current;if(!I||I.videoWidth===0){T();return}if(I!==K||I.videoWidth!==te||I.videoHeight!==ue){Te(me=>me+1);return}if(I.paused||I.ended||document.hidden||I.readyState<HTMLMediaElement.HAVE_CURRENT_DATA){T();return}const re=I.getVideoPlaybackQuality().totalVideoFrames;if(re===o.current){T();return}if(M.current){T();return}const $e=I.currentTime;(I.seeking||d.current>=0&&Math.abs($e-d.current)>.5)&&(ye(),l.current=!1,h.current=0,o.current=-1),d.current=$e;const ne=Math.max(0,je.current||0);ne>h.current&&(l.current=!1),M.current=!0;try{const me=performance.now();let Ee=null,Ne=!1;if(ne<=0){be.current.length>0&&ye(),l.current=!1,h.current=0;let Pe=!1;if(!Ye.current)try{_.queue.copyExternalImageToTexture({source:I},{texture:Se},[te,ue]),o.current=re,Pe=!0}catch(y){if(y instanceof TypeError)Ye.current=!0;else throw y}if(!Pe&&!ee.current&&ce.current&&await Rt()&&(o.current=re,Pe=!0),!Pe){const y=await createImageBitmap(I);o.current=re,_.queue.copyExternalImageToTexture({source:y},{texture:Se},[te,ue]),ie(y)}}else{const Pe=await createImageBitmap(I);o.current=re;const y=be.current;y.push({bitmap:Pe,capture:me});const Vt=at(ne);for(;y.length>Vt;)ie(y.shift()?.bitmap);let rt=-1;for(let fe=y.length-1;fe>=0;fe--)if(me-y[fe].capture>=ne){rt=fe;break}if(rt!==-1){for(let At=0;At<rt;At++)ie(y.shift()?.bitmap);const fe=y.shift();fe?(Ee=fe.bitmap,l.current=!0,h.current=ne):(Ee=Pe,Ne=!0)}else if(!l.current)Ee=Pe,Ne=!0;else{const fe=y.shift();Ee=fe?fe.bitmap:Pe,fe||(Ne=!0)}if(!Ee){M.current=!1,T();return}_.queue.copyExternalImageToTexture({source:Ee},{texture:Se},[te,ue]),Ne||ie(Ee)}const ve=_.createCommandEncoder();await Ze.pass(ve);const tt=ve.beginRenderPass({colorAttachments:[{view:De.getCurrentTexture().createView(),clearValue:{r:0,g:0,b:0,a:1},loadOp:"clear",storeOp:"store"}]});tt.setPipeline(_e),tt.setBindGroup(0,xt),tt.draw(6),tt.end(),_.queue.submit([ve.finish()]),pe.current=re,We.current=0,_.queue.onSubmittedWorkDone().then(()=>{N.current===V&&(M.current=!1)})}catch(me){if(M.current=!1,We.current+=1,We.current>=Bs&&!G&&N.current===V){console.error(me),e(me instanceof Error?me.message:"Render error"),L(!1);return}}T()}T()}catch(T){!G&&N.current===V&&(e(T instanceof Error?T.message:"Failed to initialize upscaler"),z(!1),L(!1))}}return bt(),()=>{G=!0,N.current+=1,Xe(),ye(),A.current&&(A.current.destroy(),A.current=null),$.current&&($.current.destroy(),$.current=null),ae.current&&(ae.current.destroy(),ae.current=null),W.current=null,Oe.current=null,He.current=null,a.current=null,ce.current=null,Fe.current=null,M.current=!1}},[E,b,n,g,k,f]);const D=O(G=>{L(G);try{localStorage.setItem("anime4kEnabled",String(G))}catch{}},[]),Y=O(()=>{L(G=>{const V=!G;try{localStorage.setItem("anime4kEnabled",String(V))}catch{}return V})},[]);return{isWebGPUSupported:b,isEnabled:E,isInitializing:B,error:ke,toggle:Y,setEnabled:D}}const $s=()=>localStorage.getItem("preferredMode")==="dub"?"dub":"sub",Fs=()=>{const n=localStorage.getItem("preferredProvider");return n&&/^[a-z0-9-]+$/i.test(n)?n:"megaplay"},gr=()=>({showMeta:{},episodes:[],watchedEpisodes:[],watchlistStatus:null,showCombinedDetails:!1,currentMode:$s(),inWatchlist:!1,videoSources:[],selectedSource:null,selectedLink:null,forceNativePlayer:localStorage.getItem("forceNativePlayer")==="true",isAutoplayEnabled:ln(),showResumeModal:!0,resumeTime:0,resumeDuration:0,skipIntervals:[],selectedProvider:Fs(),loadingShowData:!0,loadingVideo:!1,loadingDetails:!1,error:null,detailsError:null,showCookieModal:!1,cookieProvider:null});gr();function Os(n,g){switch(g.type){case"SET_STATE":return{...n,...g.payload};case"SET_MODE":return{...n,currentMode:g.payload,videoSources:[],selectedSource:null,selectedLink:null};case"SET_PROVIDER":return{...n,selectedProvider:g.payload};case"SET_OVERRIDE_SOURCE":return{...n,selectedSource:g.payload?.source??null,selectedLink:g.payload?.link??null};default:return n}}async function mr(n,g,k,j,b=!1){if(!n||!g)throw new Error("Missing params");try{const[R,E,L,B]=await Promise.all([Le.data.video.query({showId:n,episodeNumber:g,mode:k.currentMode,provider:k.selectedProvider}).catch(()=>null),Le.progress.getEpisode.query({showId:n,episodeNumber:g}).catch(()=>null),Le.settings.getByKey.query({key:"preferredSource"}).catch(()=>null),Le.data.skipTimes.query({showId:n,episodeNumber:g}).catch(()=>[])]),z=L?.value,ke=R?.filter(A=>{const $=A.sourceName.toLowerCase();return k.currentMode==="dub"?$.includes("eng")||$.includes("dub"):$.includes("jpn")||$.includes("sub")||!$.includes("eng")&&!$.includes("dub")})??[],e=ke.length>0?ke:R??[];let f=e.length>0?e[0]:null;if(z){const A=e.find($=>$.sourceName===z);A&&(f=A)}const Te=f&&f.links.length>0?f.links.sort((A,$)=>(parseInt($.resolutionStr)||0)-(parseInt(A.resolutionStr)||0))[0]:null,N=E?.currentTime||0,ae=E?.duration||0,W=(Array.isArray(B)?B:B?.results||[]).map(A=>({skip_id:A.skip_id||"",skip_type:A.skip_type||"",start_time:A.interval?.start_time??A.start_time??0,end_time:A.interval?.end_time??A.end_time??0})).filter(A=>A.end_time>0);return(!R||R.length===0)&&(b||Ke.error(`No video sources found for ${k.selectedProvider}`)),{videoSources:R,selectedSource:f,selectedLink:Te,resumeTime:N,resumeDuration:ae,showResumeModal:N>5&&f?.type!=="iframe",skipIntervals:W,fetchedEpisodeNumber:g}}catch(R){const E=R;if(E.message==="AUTH_REQUIRED")return j({type:"SET_STATE",payload:{showCookieModal:!0,cookieProvider:E.provider}}),{videoSources:[],selectedSource:null,selectedLink:null,resumeTime:0,resumeDuration:0,showResumeModal:!1,skipIntervals:[],fetchedEpisodeNumber:g};throw R}}const Ws=(n,g,k,j)=>{const[b,R]=Vr(Os,k,d=>({...gr(),showMeta:d?.name?{name:d.name,thumbnail:d.thumbnail,nativeName:d.nativeName,englishName:d.englishName,names:{romaji:d.name||d.englishName,english:d.englishName||d.name,native:d.nativeName}}:{}})),E=hr(),L=Gr(),B=v(null),z=v(null),{options:ke}=vr(),e=ut(()=>ke.filter(d=>(d.kind??"anime")==="anime"),[ke]),f=g||b.initialEpisode,Te=v(f);x(()=>{Te.current!==f&&(Te.current=f,R({type:"SET_STATE",payload:{selectedSource:null,selectedLink:null}}))},[f,R]),x(()=>{n&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(n)&&b.selectedProvider!=="animepahe"&&B.current!==n&&(B.current=n,R({type:"SET_PROVIDER",payload:"animepahe"}))},[n,b.selectedProvider]);const{data:N,isLoading:ae,error:Fe}=Nn(n),{data:W}=ur({queryKey:["player-data",n,b.currentMode,b.selectedProvider],queryFn:async()=>{if(!n)throw new Error("No showId");const d=async()=>{try{const Y=await Le.data.episodes.query({showId:n,mode:b.currentMode,provider:b.selectedProvider}).catch(()=>null);if(Y?.episodes?.length)return Y}catch{}return null},[o,l,h]=await Promise.all([d(),Le.watchlist.check.query({showId:n}).catch(()=>({inWatchlist:!1,status:null})),Le.progress.getWatchedEpisodes.query({showId:n}).catch(()=>[])]),D=o?.episodes?o.episodes.sort((Y,G)=>parseFloat(Y)-parseFloat(G)):[];return{description:o?.description||"",episodes:D,inWatchlist:l.inWatchlist,watchlistStatus:l.status??null,watchedEpisodes:h}},enabled:!!n});x(()=>{!g&&W?.episodes&&W.episodes.length>0&&!g&&R({type:"SET_STATE",payload:{initialEpisode:W.episodes[0]}})},[W,g]),x(()=>{if(N?.isAdult===void 0)return;const o=new Set(e.filter(l=>l.mature).map(l=>l.value)).has(b.selectedProvider);if(z.current!==n){if(N.isAdult&&!o){const l=e.find(h=>h.mature);if(!l)return;z.current=n,R({type:"SET_PROVIDER",payload:l.value}),localStorage.setItem("preferredProvider",l.value)}if(!N.isAdult&&o){const l=e.find(h=>!h.mature);if(!l)return;z.current=n,R({type:"SET_PROVIDER",payload:l.value}),localStorage.setItem("preferredProvider",l.value)}}},[N?.isAdult,b.selectedProvider,n,e]),x(()=>{if(!n||!/^dango-mt-\d+$/.test(n)||z.current===`temp:${n}`)return;const d=N?.provider;d&&(z.current=`temp:${n}`,d!==b.selectedProvider&&R({type:"SET_PROVIDER",payload:d}))},[n,N,b.selectedProvider]);const{data:A,isLoading:$,error:Oe}=ur({queryKey:["video-sources",n,f,b.selectedProvider,b.currentMode],queryFn:()=>mr(n,f,b,R),enabled:!!n&&!!f&&!(b.showMeta?.isAdult===!0&&!j?.hasMatureConsent)}),He=!1,{mutateAsync:a}=jt({mutationFn:async({wasIn:d,showMeta:o})=>{if(!n)throw new Error("Missing showId");if(d)await Le.watchlist.remove.mutate({id:n});else{const l=o.name||o.names?.romaji;if(!l)throw new Error("Missing show name");await Le.watchlist.add.mutate({id:n,name:l,thumbnail:o.thumbnail,nativeName:o.names?.native,englishName:o.names?.english,type:o.type,isAdult:o.isAdult})}return!d},onSuccess:d=>{Ke.success(d?"Added to watchlist":"Removed from watchlist"),E.invalidateQueries({queryKey:["player-data",n]}),E.invalidateQueries({queryKey:["show-data",n]}),E.invalidateQueries({queryKey:["watchlist"]})},onError:d=>Ke.error(d instanceof Error?d.message:"Failed to update watchlist")}),p=O(async()=>{!n||!N||await a({wasIn:!!W?.inWatchlist,showMeta:N})},[n,N,W?.inWatchlist,a]),M=O(async d=>{try{await Le.settings.set.mutate({key:"preferredSource",value:d})}catch(o){console.error(o)}},[]),{mutateAsync:pe,isPending:We}=jt({mutationFn:async({status:d})=>{if(!n)throw new Error("Missing showId");return await Le.watchlist.setStatus.mutate({id:n,status:d}),d},onSuccess:d=>{R({type:"SET_STATE",payload:{inWatchlist:!0,watchlistStatus:d}}),Ke.success(`Moved to ${d}`),E.invalidateQueries({queryKey:["show-data",n]}),E.invalidateQueries({queryKey:["watchlist"]}),E.invalidateQueries({queryKey:["allContinueWatching"]})},onError:()=>Ke.error("Failed to update watchlist status")}),je=O(async()=>{await pe({status:"Completed"})},[pe]),{mutateAsync:be}=jt({mutationFn:async({episodeNumber:d,duration:o,showMeta:l,episodes:h})=>{await _n("/api/update-progress",{method:"POST",body:JSON.stringify({showId:n,episodeNumber:d,currentTime:o,duration:o,showName:l.name,showThumbnail:l.thumbnail,nativeName:l.names?.native,englishName:l.names?.english,genres:l.genres?.map(D=>D.name),popularityScore:Kr(l.score??l.stats?.averageScore),type:l.type,status:l.status,episodeCount:h.length,isAdult:l.isAdult}),keepalive:!0})},onSuccess:(d,o)=>{Ke.success(`Episode ${o.episodeNumber} marked as watched`),E.invalidateQueries({queryKey:["player-data",n]}),E.invalidateQueries({queryKey:["show-meta",n]}),E.invalidateQueries({queryKey:["video-sources",n,o.episodeNumber]}),E.invalidateQueries({queryKey:["allContinueWatching"]}),E.invalidateQueries({queryKey:["thisWeekSchedule"]}),E.invalidateQueries(L.continueWatching.pathFilter())},onError:()=>Ke.error("Failed to mark episode as watched")}),Ye=O(async(d,o)=>{!n||!N||await be({episodeNumber:d,duration:o,showMeta:N,episodes:W?.episodes||[]})},[n,N,W?.episodes,be]),ee=O(async()=>{R({type:"SET_STATE",payload:{showCombinedDetails:!b.showCombinedDetails}})},[b.showCombinedDetails]),Ce=ut(()=>{const d=Fe||Oe,o=d?d.message:null,l=o==="AUTH_REQUIRED"?null:o,h=A&&A.fetchedEpisodeNumber===f?A:null,D=!!A&&!h;return{...b,currentEpisode:f,showMeta:{...b.showMeta||{},...N||{}},episodes:W?.episodes||[],watchedEpisodes:W?.watchedEpisodes||[],inWatchlist:!!W?.inWatchlist,watchlistStatus:W?.watchlistStatus??b.watchlistStatus??null,videoSources:h?.videoSources||[],selectedSource:b.selectedSource||h?.selectedSource||null,selectedLink:b.selectedLink||h?.selectedLink||null,resumeTime:h?.resumeTime||0,resumeDuration:h?.resumeDuration||0,showResumeModal:b.showResumeModal&&(h?.showResumeModal??!1),skipIntervals:h?.skipIntervals||[],loadingShowData:ae,loadingVideo:$||D,loadingDetails:He,error:l,fetchedEpisodeNumber:h?.fetchedEpisodeNumber}},[b,N,W,A,ae,$,He,Fe,Oe,f]),ce=O((d,o)=>{const l=o||n;if(!l||!d||l===n&&d===f)return;const D=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(l)&&b.selectedProvider!=="animepahe"?"animepahe":b.selectedProvider,Y=["video-sources",l,d,D,b.currentMode];E.getQueryState(Y)?.status!=="success"&&E.prefetchQuery({queryKey:Y,queryFn:()=>mr(l,d,{selectedProvider:D,currentMode:b.currentMode},R,!0),staleTime:300*1e3,gcTime:1800*1e3})},[n,f,E,b,R]);return{state:Ce,dispatch:R,toggleWatchlist:p,moveToCompleted:je,setPreferredSource:M,handleToggleDetails:ee,markEpisodeWatched:Ye,prefetchEpisodeSources:ce,isMarkingWatched:be.isPending,isUpdatingWatchlistStatus:We}},Xt="fallbackChoice";function Vs(){try{const n=localStorage.getItem(Xt);return n==="iframe"||n==="retry"?n:null}catch{return null}}function Us(n){try{n===null?localStorage.removeItem(Xt):localStorage.setItem(Xt,n)}catch{}}const io=()=>{const{id:n,episodeNumber:g}=Ur(),k=qr(),j=hr(),b=Qr(),{hasConsent:R,grant:E}=Cn(),{options:L}=vr(),B=ut(()=>L.filter(t=>(t.kind??"anime")==="anime"),[L]),z=ut(()=>B.map(t=>t.value),[B]),ke=ut(()=>new Set(B.filter(t=>t.mature).map(t=>t.value)),[B]),{state:e,dispatch:f,toggleWatchlist:Te,moveToCompleted:N,setPreferredSource:ae,handleToggleDetails:Fe,markEpisodeWatched:W,prefetchEpisodeSources:A,isMarkingWatched:$,isUpdatingWatchlistStatus:Oe}=Ws(n,g,b.state||null,{hasMatureConsent:R});x(()=>{if(n&&e.showMeta?.id&&e.showMeta.id!==n){const t=g?`/watch/${e.showMeta.id}/${g}${window.location.search}`:`/watch/${e.showMeta.id}${window.location.search}`;k(t,{replace:!0})}},[n,e.showMeta?.id,g,k]);const He=ut(()=>{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]),a=cn({skipIntervals:e.skipIntervals,showId:n,episodeNumber:e.currentEpisode?.toString(),episodeCount:e.episodes.length||void 0,sourceType:e.selectedSource?.type,showMeta:He}),{refs:p,actions:M}=a,pe=v(null),We=Rn(),je=v(null),be=v(null),Ye=v(null),ee=v(0),Ce=v(e.resumeTime),ce=v(e.showResumeModal),[d,o]=Q(()=>{try{const t=localStorage.getItem("anime4kProfile");return["low","balanced","high","denoise"].includes(t)?t:"balanced"}catch{return"balanced"}}),[l,h]=Q(()=>{try{const t=Number(localStorage.getItem("playerVideoDelayMs"));if(Number.isFinite(t)&&t>=0&&t<=500)return Math.round(t)}catch{}return 180}),[D,Y]=Q(()=>{try{return localStorage.getItem("playerVideoDelayEnabled")==="true"}catch{return!1}}),[G,V]=Q(!1),[ie,ye]=Q(!1),at=v(null),Xe=v(null),bt=(t,s)=>{try{localStorage.setItem("playerVideoDelayMs",String(t)),localStorage.setItem("playerVideoDelayEnabled",String(s))}catch{}},K=t=>{const s=Math.max(0,Math.min(500,Math.round(t)));h(s);try{localStorage.setItem("playerVideoDelayMs",String(s))}catch{}},it=()=>{at.current={enabled:D,ms:l},Y(!0);try{localStorage.setItem("playerVideoDelayEnabled","true")}catch{}M.setShowSettings(!1),V(!0)},dt=()=>{const t=at.current;at.current=null,t&&(h(t.ms),Y(t.enabled),bt(t.ms,t.enabled)),ye(!1),V(!1)},te=()=>{at.current=null,Y(!0),bt(l,!0),ye(!1),V(!1)},ue=()=>{if(ie){ye(!1);return}const t=p.videoRef.current;t&&!isNaN(t.currentTime)&&(Xe.current=t.currentTime),ye(!0)},Re=D?l:0,yt=v(null),F=Ds({videoRef:p.videoRef,canvasRef:be,profile:d,delayMs:Re}),Ve=F.isEnabled&&F.isWebGPUSupported,pt=`${n??""}:${e.currentEpisode??""}`,lt=v(null),m=v(!1),P=v(!1),T=v(F.setEnabled);T.current=F.setEnabled,x(()=>{const t=lt.current;lt.current=pt,!(t===null||t===pt)&&(!F.isEnabled||!F.isWebGPUSupported||(m.current=!0,P.current=!1,T.current(!1)))},[pt,F.isEnabled,F.isWebGPUSupported]),x(()=>{if(!m.current)return;if(F.isEnabled){P.current&&(m.current=!1);return}if(P.current=!0,e.loadingVideo||!e.selectedLink)return;if(e.selectedSource?.type==="iframe"){m.current=!1,T.current(!0);return}const t=p.videoRef.current;if(!t)return;let s,i=!1;const c=()=>{i||(i=!0,m.current=!1,T.current(!0))};if(t.readyState>=2)return s=window.setTimeout(c,500),()=>window.clearTimeout(s);const C=()=>{window.setTimeout(c,500)};return t.addEventListener("canplay",C,{once:!0}),t.addEventListener("playing",C,{once:!0}),s=window.setTimeout(c,5e3),()=>{window.clearTimeout(s),t.removeEventListener("canplay",C),t.removeEventListener("playing",C)}},[F.isEnabled,e.loadingVideo,e.selectedLink,e.selectedSource?.type,p.videoRef]),un({videoRef:p.videoRef,canvasRef:yt,delayMs:Re,enabled:D&&!Ve});const Ue=D&&!Ve,Ie=Ve||Ue;x(()=>{Ce.current=e.resumeTime,ce.current=e.showResumeModal},[e.resumeTime,e.showResumeModal]);const[Tt,Jt]=Q(null),[Pt,_]=Q(!1),[De,Je]=Q(!1),[Se,Ct]=Q(!1),qe=v(!1),[Qe,Ze]=Q(null),ze=v(!1),Me=v([]),et=v(!1),[St,_e]=Q(null),[xt,Rt]=Q(!1),[mt,I]=Q(!1),[re,$e]=Q(()=>Vs()??"ask"),ne=O(t=>{$e(t),Us(t==="ask"?null:t)},[]),me=v(re);me.current=re;const Ee=v(e.videoSources);Ee.current=e.videoSources;const Ne=v(()=>{}),[ve,tt]=Q(null),Pe=v(g);x(()=>{Pe.current!==g&&(Pe.current=g,tt(null),Ze(null),qe.current=!1,ye(!1),V(!1))},[g]),x(()=>{ze.current=!1,Me.current=[],et.current=!1,_e(null),Rt(!1)},[n,e.currentEpisode]),x(()=>{De||(qe.current=!1)},[De]);const{data:y=[],isLoading:Vt}=Hr(),rt=jr(),fe=v(rt);fe.current=rt;const At=Yr(),br=Xr(),[ge,Ut]=Q(()=>{try{return localStorage.getItem("playerTheaterMode")==="true"}catch{return!1}});x(()=>{try{ge?document.body.classList.add("theater-mode"):document.body.classList.remove("theater-mode")}catch(t){console.error(t)}return()=>{try{document.body.classList.remove("theater-mode")}catch(t){console.error(t)}}},[ge]),zr(()=>{if(a.state.isFullscreen||ge)return;const t=p.playerContainerRef.current,s=je.current;if(!t||!s)return;const i=()=>{const C=t.getBoundingClientRect().height;s.style.height=`${C}px`};i();const c=new ResizeObserver(i);return c.observe(t),()=>c.disconnect()},[a.state.isFullscreen,ge,p.playerContainerRef]);const ft=ut(()=>e.episodes.findIndex(t=>t===e.currentEpisode),[e.episodes,e.currentEpisode]),qt=ft>0?e.episodes[ft-1]:null,xe=ft>=0&&ft<e.episodes.length-1?e.episodes[ft+1]:null,Qt=ft>-1&&ft<e.episodes.length-1,yr=e.episodes.length>0&&!!e.currentEpisode&&e.episodes[e.episodes.length-1]===e.currentEpisode,Sr=String(e.showMeta.status||"").trim().toLowerCase(),Er=["finished","completed","complete","ended"].some(t=>Sr.includes(t)),zt=dn(e.resumeTime,e.resumeDuration)||De,ct=yr&&Er&&zt,Zt=e.showResumeModal&&(ct||!zt),Bt=zt&&!ct&&y.length===0&&!ve&&(e.showResumeModal||De),ht=Zt||Bt;pn(a,!!e.selectedLink&&!ge&&!ht),x(()=>{const t=p.videoRef.current;if(!t)return;let s=!1;for(pe.current&&(pe.current.destroy(),pe.current=null),(e.loadingVideo||e.selectedSource)&&(t.pause(),t.removeAttribute("src"),t.load());t.firstChild;)t.removeChild(t.firstChild);if(ie)return t.src="/av-sync-test.mp4",t.play().catch(()=>{M.setShowControls(!0)}),()=>{s=!0};if(!e.selectedSource||!e.selectedLink)return;if(e.selectedSource.type==="iframe"){ee.current=0;return}Xe.current!=null?(ee.current=Xe.current,Xe.current=null):Ce.current>5&&!ce.current?ee.current=Ce.current:ce.current&&(ee.current=0);let i=e.selectedLink.link;if(i.startsWith("/api/proxy")||(i=`/api/proxy?url=${encodeURIComponent(i)}`,e.selectedLink.headers?.Referer&&(i+=`&referer=${encodeURIComponent(e.selectedLink.headers.Referer)}`)),e.selectedSource.subtitles){const de=localStorage.getItem("playerSubtitlesEnabled")!=="false";let we=null;try{we=localStorage.getItem("playerLastSubtitle")}catch{}const X=Yt(e.selectedSource.subtitles,{lastKey:we,enabled:de}),Ae=X>=0?e.selectedSource.subtitles[X]:null;e.selectedSource.subtitles.forEach(he=>{const J=document.createElement("track");J.kind="subtitles",J.label=he.label,J.srclang=he.lang;const S=he.src??he.url;if(S){let Z=`/api/subtitle-proxy?url=${encodeURIComponent(S)}`;const oe=e.selectedLink?.headers?.Referer,Et=S.includes("anilight.live")?"https://anilight.live/":"",Ot=oe||Et;Ot&&(Z+=`&referer=${encodeURIComponent(Ot)}`),J.src=Z}Ae&&he.label===Ae.label&&he.lang===Ae.lang&&(J.default=!0),t.appendChild(J)}),de||M.setActiveSubtitleTrack("off"),M.setAvailableSubtitles(e.selectedSource.subtitles)}const c=ee.current;ee.current=0;const C=()=>{c>0&&(t.currentTime=c)};t.addEventListener("loadedmetadata",C,{once:!0});const le=!(ce.current&&Ce.current>5),H=()=>{le&&t.play().catch(()=>{M.setShowControls(!0)})};e.selectedLink.hls?(async()=>{const de=await Tn();if(s)return;if(!de||!de.isSupported()){t.src=i,H();return}const we=document.body.classList.contains("low-end"),X=new de({maxBufferLength:we?15:30,maxMaxBufferLength:we?30:60,maxBufferSize:we?25*1e3*1e3:60*1e3*1e3,startLevel:-1,enableWorker:!0});pe.current=X,X.on(de.Events.ERROR,(J,S)=>{S.fatal&&!ze.current&&Ne.current()});const Ae=(e.selectedSource?.subtitles?.length??0)>0,he=()=>{try{Ae&&typeof X.subtitleTrack=="number"&&X.subtitleTrack!==-1&&(X.subtitleTrack=-1)}catch{}};X.on(de.Events.SUBTITLE_TRACK_SWITCH,(J,S)=>{S?.id!==-1&&he()}),he(),X.loadSource(i),X.attachMedia(t),X.once(de.Events.MANIFEST_PARSED,()=>{s||H()})})():(t.src=i,H());const U=localStorage.getItem("playerVolume"),se=localStorage.getItem("playerMuted");return U!==null&&(t.volume=parseFloat(U)),se!==null&&(t.muted=se==="true"),()=>{s=!0,t.removeEventListener("loadedmetadata",C),pe.current&&(pe.current.destroy(),pe.current=null)}},[e.selectedSource,e.selectedLink,p.videoRef,M,e.loadingVideo,ie]);const Lt=O(t=>{if(ze.current)return;ze.current=!0;const s=t.links[0];ae(t.sourceName),f({type:"SET_STATE",payload:{selectedSource:t,selectedLink:s}}),_e(null)},[f,ae]),It=O(()=>{const s=Ee.current.find(i=>i.type==="iframe");return s?.links?.length?s:null},[]),Dt=O(async()=>{const t=e.showMeta?.isAdult,s=z.filter(i=>{if(Me.current.includes(i))return!1;const c=ke.has(i);return t===void 0?!0:c===t});Rt(!0);try{for(const i of s){Me.current.push(i);let c=null;try{c=await Le.data.video.query({showId:n,episodeNumber:e.currentEpisode,mode:e.currentMode,provider:i})}catch{continue}const C=(c??[]).filter(U=>{const se=U.sourceName.toLowerCase();return e.currentMode==="dub"?se.includes("eng")||se.includes("dub"):se.includes("jpn")||se.includes("sub")||!se.includes("eng")&&!se.includes("dub")});if((C.length>0?C:c??[]).find(U=>U.type!=="iframe"&&U.links?.length)){Me.current=[e.selectedProvider],et.current=!1,f({type:"SET_STATE",payload:{selectedProvider:i,videoSources:[],selectedSource:null,selectedLink:null,loadingVideo:!0}}),localStorage.setItem("preferredProvider",i),_e(null),Ke.success(`Switched to ${i} (direct stream)`);return}}_e({retryFailed:!0}),Ke.error("No working direct stream found on other providers")}finally{Rt(!1)}},[n,e.currentEpisode,e.currentMode,e.showMeta?.isAdult,e.selectedProvider,f,z,ke]),er=O(()=>{if(ze.current||et.current||e.selectedSource?.type!=="player")return;const t=It();if(!t)return;Me.current.includes(e.selectedProvider)||Me.current.push(e.selectedProvider);const s=me.current;if(s==="iframe"){Lt(t);return}if(s==="retry"){Dt();return}M.setShowControls(!0),_e({retryFailed:!1})},[e.selectedSource,e.selectedProvider,It,Lt,Dt,M]);Ne.current=er;const wr=O(()=>{et.current=!0,_e(null),I(!1)},[]),kr=O(()=>{mt&&ne("iframe");const t=It();t?Lt(t):_e(null)},[mt,ne,It,Lt]),Tr=O(()=>{mt&&ne("retry"),Dt()},[mt,ne,Dt]),Mt=(t,s,i)=>t.showId===s||!!i&&t.showId===i,$t=O(()=>{M.onEnded();const t=y.find(i=>Mt(i,n,e.showMeta?.id)&&i.episodeNumber===e.currentEpisode);if(y.length>0){const i=y.findIndex(C=>Mt(C,n,e.showMeta?.id)&&C.episodeNumber===e.currentEpisode),c=i>=0?y[i+1]||null:y[0];tt({nextItem:c,playedItem:t||null}),Ze(2)}else t&&fe.current.mutate({showId:t.showId,episodeNumber:t.episodeNumber});let s=!1;if(e.isAutoplayEnabled&&y.length===0){const i=e.episodes.findIndex(c=>c===e.currentEpisode);if(i>-1&&i<e.episodes.length-1){const c=e.episodes[i+1];j.invalidateQueries({queryKey:["allContinueWatching"]}),k(`/watch/${n}/${c}`),s=!0}}if(!s&&y.length===0&&!ve&&!qe.current){const i=e.episodes.length>0&&!!e.currentEpisode&&e.episodes[e.episodes.length-1]===e.currentEpisode,c=String(e.showMeta.status||"").trim().toLowerCase(),C=["finished","completed","complete","ended"].some(le=>c.includes(le));i&&C&&f({type:"SET_STATE",payload:{showResumeModal:!0}})}},[M,k,y,n,e.showMeta?.id,e.showMeta?.status,e.currentEpisode,e.episodes,e.isAutoplayEnabled,ve,f,j]),Gt=O(()=>{if(y.length===0)return;M.onEnded();const t=y.find(c=>Mt(c,n,e.showMeta?.id)&&c.episodeNumber===e.currentEpisode),s=y.findIndex(c=>Mt(c,n,e.showMeta?.id)&&c.episodeNumber===e.currentEpisode),i=s>=0?y[s+1]||null:y[0];t&&rt.mutate({showId:t.showId,episodeNumber:t.episodeNumber}),i?k(`/watch/${i.showId}/${i.episodeNumber}`):t&&f({type:"SET_STATE",payload:{showResumeModal:!0}})},[M,k,y,rt,n,e.showMeta?.id,e.currentEpisode,f]),_t=O(()=>{xe&&(j.invalidateQueries({queryKey:["allContinueWatching"]}),Je(!1),k(`/watch/${n}/${xe}`)),f({type:"SET_STATE",payload:{showResumeModal:!1}})},[xe,k,n,f,j]),tr=O(()=>{y.length>0?Gt():xe?_t():Ke.error("No next episode available")},[y.length,Gt,_t,xe]),Cr=()=>{qt&&k(`/watch/${n}/${qt}`)};x(()=>{const t=p.videoRef.current;if(!t)return;const s=()=>{ie||$t()};return t.addEventListener("ended",s),()=>{t&&t.removeEventListener("ended",s)}},[$t,p.videoRef,ie]),x(()=>{const t=s=>{s.origin===window.location.origin&&e.selectedSource?.type==="iframe"&&s.data?.type==="ANI_WEB_MEDIA_ENDED"&&$t()};return window.addEventListener("message",t),()=>window.removeEventListener("message",t)},[$t,e.selectedSource?.type]),x(()=>{if(!ve||Qe===null)return;if(Qe<=0){const{nextItem:s,playedItem:i}=ve;tt(null),Ze(null),i&&fe.current.mutate({showId:i.showId,episodeNumber:i.episodeNumber}),s?k(`/watch/${s.showId}/${s.episodeNumber}`):i&&f({type:"SET_STATE",payload:{showResumeModal:!0}});return}const t=window.setTimeout(()=>{Ze(s=>s===null?null:s-1)},1e3);return()=>window.clearTimeout(t)},[ve,Qe,k,f]),x(()=>{ht&&a.state.isFullscreen&&a.actions.toggleFullscreen()},[ht,a.state.isFullscreen,a.actions]),x(()=>{ht&&p.videoRef.current&&p.videoRef.current.pause()},[ht,p.videoRef]);const{titlePreference:Ft}=Jr(),{lowEndMode:Rr}=Zr(),vt=ut(()=>{if(!e.showMeta||e.loadingShowData)return"Loading...";const{name:t,names:s}=e.showMeta;return Ft==="name"?t||"Loading...":Ft==="nativeName"?s?.native||t||"Loading...":Ft==="englishName"?s?.english||t||"Loading...":t||"Loading..."},[e.showMeta,Ft,e.loadingShowData]);x(()=>{vt&&vt!=="Loading..."&&e.currentEpisode&&(document.title=`► ${vt} Episode ${e.currentEpisode} - dango`)},[vt,e.currentEpisode]),x(()=>{const t=s=>{if(!s.target.closest('input, textarea, button, select, a, [role="button"], [contenteditable="true"]')&&(["arrowup","arrowdown","arrowleft","arrowright"].includes(s.key.toLowerCase())&&(M.setShowControls(!0),a.actions.inactivityTimer.current&&clearTimeout(a.actions.inactivityTimer.current),a.actions.inactivityTimer.current=window.setTimeout(()=>{M.setShowControls(!1)},1e3)),s.key.toLowerCase()==="n"&&tr(),s.key.toLowerCase()==="t")){const c=!ge;Ut(c),localStorage.setItem("playerTheaterMode",c.toString())}};return document.addEventListener("keydown",t),()=>{document.removeEventListener("keydown",t)}},[M,a.actions.inactivityTimer,tr,ge]);const{setAvailableSubtitles:rr,setActiveSubtitleTrack:Kt}=M;x(()=>{const t=p.videoRef.current;if(!t)return;const s=()=>{const i=Array.from(t.textTracks).map(c=>({label:c.label,lang:c.language,src:void 0,mode:c.mode}));rr(i)};return t.textTracks.addEventListener("addtrack",s),t.textTracks.addEventListener("removetrack",s),s(),()=>{t&&(t.textTracks.removeEventListener("addtrack",s),t.textTracks.removeEventListener("removetrack",s))}},[p.videoRef,rr]),x(()=>{if(a.state.activeSubtitleTrack===null&&a.state.availableSubtitles.length>0&&localStorage.getItem("playerSubtitlesEnabled")!=="false"){let t=null;try{t=localStorage.getItem("playerLastSubtitle")}catch{}const s=Yt(a.state.availableSubtitles,{lastKey:t,enabled:!0});if(s<0){Kt("off");return}const i=a.state.availableSubtitles[s];Kt(i.lang||i.label)}},[a.state.activeSubtitleTrack,a.state.availableSubtitles,Kt]),x(()=>{const t=p.videoRef.current;if(!t||a.state.availableSubtitles.length===0)return;const s=a.state.activeSubtitleTrack;if(!(localStorage.getItem("playerSubtitlesEnabled")!=="false")||s==="off"||s===null){Array.from(t.textTracks).forEach(C=>{C.mode="hidden"});return}let c=!1;if(Array.from(t.textTracks).forEach(C=>{const H=(C.language===s||C.label===s)&&!c;C.mode=H?"showing":"hidden",H&&(c=!0)}),!c&&t.textTracks.length>0){const C=Array.from(t.textTracks).find(le=>le.language==="en"||le.label==="English")||t.textTracks[0];C&&(C.mode="showing")}},[a.state.activeSubtitleTrack,a.state.availableSubtitles,p.videoRef]);const[nr,Mr]=Q(0);x(()=>{const t=p.videoRef.current;if(!t)return;const s=()=>Mr(t.clientHeight||0);s();const i=new ResizeObserver(s);return i.observe(t),()=>i.disconnect()},[p.videoRef,e.selectedSource,e.selectedLink]),x(()=>{const t="dynamic-subtitle-styles";let s=document.getElementById(t);s||(s=document.createElement("style"),s.id=t,document.head.appendChild(s));const i={fontSize:a.state.subtitleFontSize,position:a.state.subtitlePosition,bgOpacity:a.state.subtitleBgOpacity,bgColor:a.state.subtitleBgColor,textColor:a.state.subtitleTextColor,edge:a.state.subtitleEdge,bold:a.state.subtitleBold};s.textContent=dr(i);const c=p.videoRef.current;if(!c)return;const C=pr(a.state.subtitleFontSize,nr||c.clientHeight||720);s.textContent=dr({...i,fontSize:C});const le=()=>{const S=Number(a.state.subtitlePosition),Z=isNaN(S)?0:Math.max(0,Math.min(100,S));return Math.max(0,Math.min(100,100-Z))},H=(S,Z)=>{try{const oe=S;oe.snapToLines=!1,oe.line=Z}catch{}},U=()=>{const S=C*16,Z=c.videoHeight||c.clientHeight||720,oe=c.videoWidth||c.clientWidth||1280;return{step:S*1.3/Z*100,chars:Math.max(20,Math.floor(oe/(S*.55)))}},se=S=>{const Z=le(),oe=Array.from(S.activeCues??[]);if(oe.length<=1){oe.forEach(wt=>H(wt,Z));return}const{step:Et,chars:Ot}=U();let lr=Z;for(let wt=oe.length-1;wt>=0;wt--){const Dr=String(oe[wt].text??"").replace(/<[^>]*>/g,"").split(`
|
|
55
|
-
`).reduce(($r,Fr)=>$r+Math.max(1,Math.ceil(Fr.length/Ot)),0),cr=lr-Dr*Et;H(oe[wt],Math.max(0,cr)),lr=cr-Et*.4}},de=S=>{if(!S.cues)return;const Z=le();Array.from(S.cues).forEach(oe=>H(oe,Z)),S.mode==="showing"&&se(S)},we=()=>{Array.from(c.textTracks).forEach(de)};we();const X=S=>{const Z=S.target;Z.mode==="showing"&&se(Z)};Array.from(c.textTracks).forEach(S=>{S.addEventListener("cuechange",X)});const Ae=()=>{Array.from(c.textTracks).forEach(S=>{S.removeEventListener("cuechange",X),S.addEventListener("cuechange",X)}),we()};c.textTracks.addEventListener("addtrack",Ae),c.textTracks.addEventListener("removetrack",Ae);const he=Array.from(c.querySelectorAll("track")),J=()=>{we()};return he.forEach(S=>{S.addEventListener("load",J)}),()=>{Array.from(c.textTracks).forEach(S=>{S.removeEventListener("cuechange",X)}),c.textTracks.removeEventListener("addtrack",Ae),c.textTracks.removeEventListener("removetrack",Ae),he.forEach(S=>{S.removeEventListener("load",J)})}},[a.state.subtitleFontSize,a.state.subtitlePosition,a.state.subtitleBgOpacity,a.state.subtitleBgColor,a.state.subtitleTextColor,a.state.subtitleEdge,a.state.subtitleBold,a.state.activeSubtitleTrack,a.state.availableSubtitles,e.selectedSource,e.selectedLink,p.videoRef,nr]),x(()=>{if(!Ie)return;const t=p.videoRef.current,s=Ye.current;if(!t||!s)return;const i=localStorage.getItem("playerSubtitlesEnabled")!=="false",c=a.state.activeSubtitleTrack;function C(){if(s.innerHTML="",!i||c==="off"||c===null)return;const U=Array.from(t.textTracks).find(J=>J.language===c||J.label===c);if(!U||U.mode!=="showing")return;const se=Re/1e3;let de;if(se>0&&U.cues){const J=t.currentTime-se;de=Array.from(U.cues).filter(S=>S.startTime<=J&&J<=S.endTime)}else de=Array.from(U.activeCues??[]);if(de.length===0)return;const we={fontSize:pr(a.state.subtitleFontSize,t.clientHeight||0),position:a.state.subtitlePosition,bgOpacity:a.state.subtitleBgOpacity,bgColor:a.state.subtitleBgColor,textColor:a.state.subtitleTextColor,edge:a.state.subtitleEdge,bold:a.state.subtitleBold},X=mn(we),Ae=fn(t,we.position),he=Array.from(de);he.forEach((J,S)=>{const Z=String(J.text??"");if(!hn(Z).trim())return;const oe=document.createElement("div"),Et=(he.length-1-S)*1.7;oe.style.cssText=`${X}
|
|
56
|
-
bottom: calc(${Ae}px + ${Et}em);`,oe.innerHTML=vn(Z),s.appendChild(oe)})}const le=()=>C(),H=()=>C();return Array.from(t.textTracks).forEach(U=>{U.addEventListener("cuechange",le)}),t.addEventListener("timeupdate",H),C(),()=>{Array.from(t.textTracks).forEach(U=>{U.removeEventListener("cuechange",le)}),t.removeEventListener("timeupdate",H),s.innerHTML=""}},[F.isEnabled,F.isWebGPUSupported,a.state.subtitleFontSize,a.state.subtitlePosition,a.state.subtitleBgOpacity,a.state.subtitleBgColor,a.state.subtitleTextColor,a.state.subtitleEdge,a.state.subtitleBold,a.state.activeSubtitleTrack,p.videoRef,Ie,Re]),x(()=>{try{localStorage.setItem("anime4kProfile",d)}catch{}},[d]);const _r=()=>{p.videoRef.current&&(p.videoRef.current.currentTime=e.resumeTime,p.videoRef.current.play()),f({type:"SET_STATE",payload:{showResumeModal:!1}})},Nr=()=>{p.videoRef.current&&(p.videoRef.current.currentTime=0,p.videoRef.current.play()),f({type:"SET_STATE",payload:{showResumeModal:!1}})},sr=O(()=>{ct&&(qe.current=!0),Bt&&Je(!1),f({type:"SET_STATE",payload:{showResumeModal:!1}})},[f,ct,Bt]),Pr=O(()=>{if(Je(!1),p.videoRef.current)try{p.videoRef.current.currentTime=0,p.videoRef.current.play().catch(()=>{})}catch{}f({type:"SET_STATE",payload:{showResumeModal:!1}})},[f,p]),xr=O(async()=>{try{await N(),f({type:"SET_STATE",payload:{showResumeModal:!1}}),k("/")}catch{}},[N,f,k]),or=(t,s)=>r("div",{className:t,children:[r("button",{className:`${u.episodeNavBtn} ${u.secondary}`,onClick:Cr,disabled:!qt,type:"button",children:[r(q,{name:"chevron-left",size:12}),"Prev EP"]}),r("button",{className:`${u.episodeNavBtn} ${u.primary}`,onClick:_t,disabled:!xe,type:"button",children:["Next EP",r(q,{name:"chevron-right",size:12})]}),s==="mobile"&&We&&r("button",{className:`${u.episodeNavBtn} ${u.episodePickerBtn}`,onClick:()=>Ct(!0),type:"button",children:[r(q,{name:"list-ul",size:12}),"Episodes"]})]});x(()=>{De&&(e.showResumeModal||y.length>0||ve||qe.current||ct&&f({type:"SET_STATE",payload:{showResumeModal:!0}}))},[De,ct,e.showResumeModal,y.length,ve,f]);const Ar=t=>{f({type:"SET_STATE",payload:{isAutoplayEnabled:t}}),kn(t)},ar=!!(e.currentEpisode&&e.watchedEpisodes.includes(e.currentEpisode)),Br=e.selectedProvider!=="megaplay"||e.selectedSource?.type==="iframe",Ht=v(A);Ht.current=A;const ir=v("");x(()=>{const t=p.videoRef.current;if(_(!1),Je(!1),!t||e.selectedSource?.type==="iframe")return;const s=()=>{const i=t.duration,c=t.currentTime;if(!i||Number.isNaN(i)){_(!1),Je(!1);return}const C=c/i;if(i-c<=60){const le=y.findIndex(se=>Mt(se,n,e.showMeta?.id)&&se.episodeNumber===e.currentEpisode),H=y.length>0?le>=0?y[le+1]||null:y[0]:null,U=H?`${H.showId}:${H.episodeNumber}`:Qt?`${n}:${xe}`:"";U&&ir.current!==U&&(ir.current=U,H?Ht.current(H.episodeNumber,H.showId):Ht.current(xe))}_(Qt&&C>=.8),Je(c>=Math.max(i*.98,i-10))};return s(),t.addEventListener("timeupdate",s),t.addEventListener("loadedmetadata",s),()=>{t.removeEventListener("timeupdate",s),t.removeEventListener("loadedmetadata",s)}},[p.videoRef,Qt,e.currentEpisode,e.selectedSource,xe,n,y,e.showMeta?.id]);const Lr=O(async()=>{if(!n||!e.currentEpisode||!e.showMeta.name||$)return;const t=p.videoRef.current?.duration,s=Math.max(t||0,e.resumeDuration||0,(e.showMeta.lengthMin||0)*60,1);await W(e.currentEpisode,s)},[n,e.currentEpisode,e.showMeta,e.resumeDuration,W,$,p.videoRef]);if(e.error&&!e.showMeta.name&&e.videoSources.length===0&&e.episodes.length===0)return r("p",{className:"error-message",children:["Error: ",e.error]});const nt=e.loadingShowData||e.loadingVideo,Ir=t=>{ge&&t.target===t.currentTarget&&(Ut(!1),localStorage.setItem("playerTheaterMode","false"))};return e.showMeta?.isAdult===!0&&!R?r("div",{className:Ge.playerPageLayout,children:r(Be,{isOpen:!0,title:"Content Warning",onClose:()=>k("/home"),children:r("div",{style:{padding:"1rem",textAlign:"center"},children:[r("p",{children:"This title contains mature content intended for adult audiences."}),r("p",{children:["By proceeding, you confirm that you are ",r("strong",{children:"18 years of age or older"})," (or the age of majority in your jurisdiction) and wish to view this content."]}),r("div",{style:{marginTop:"1rem",display:"flex",gap:"10px",justifyContent:"center"},children:[r(st,{variant:"secondary",onClick:()=>k("/home"),children:"Go Back"}),r(st,{onClick:E,children:"I'm 18+, Continue"})]})]})})}):r("div",{className:`${Ge.playerPageLayout} ${ge?Ge.theaterMode:""}`,onClick:Ir,children:[r(Be,{isOpen:Zt,onClose:sr,title:ct?"Show Completed!":"Resume Playback?",width:"sm",children:ct?r(kt,{children:[r(Be.Body,{children:r("p",{children:"Congratulations! You've finished the final episode of this series."})}),r(Be.Actions,{children:r(st,{onClick:xr,disabled:Oe,children:Oe?"Saving...":"Move to Completed"})})]}):r(kt,{children:[r(Be.Body,{children:r("p",{children:["You were watching at ",r("strong",{children:a.actions.formatTime(e.resumeTime)}),". Would you like to continue?"]})}),r(Be.Actions,{children:[r(st,{variant:"secondary",onClick:Nr,children:"Start Over"}),r(st,{onClick:_r,children:"Resume"})]})]})}),r(Be,{isOpen:Bt,onClose:sr,title:"Episode Completed",width:"sm",children:[r(Be.Body,{children:r("p",{children:["You've already watched Episode ",r("strong",{children:e.currentEpisode}),".",xe?" Would you like to watch the next episode?":""]})}),r(Be.Actions,{children:[r(st,{variant:"secondary",onClick:Pr,children:"Replay"}),xe&&r(st,{onClick:_t,children:`Watch EP ${xe}`})]})]}),r(Be,{isOpen:!!St,onClose:wr,title:"Direct stream failed",width:"sm",children:[r(Be.Body,{children:[r("p",{children:[r("strong",{children:e.selectedProvider}),"'s direct stream failed for this episode."]}),St?.retryFailed&&r("p",{children:"No working direct stream was found on the other providers either."}),r("p",{children:["You can continue with the embedded (iframe) player, but embedded players may show"," ",r("strong",{children:"ads and pop-ups"}),"."]}),r("label",{style:{display:"flex",alignItems:"center",gap:"8px",marginTop:"0.75rem",cursor:"pointer"},children:[r("input",{type:"checkbox",checked:mt,onChange:t=>I(t.target.checked)}),"Remember my choice"]})]}),r(Be.Actions,{children:[r(st,{variant:"secondary",onClick:kr,children:"Continue with iframe"}),r(st,{onClick:Tr,disabled:xt,children:xt?"Searching…":"Try another provider"})]})]}),r(en,{isOpen:!!e.showCookieModal,onClose:()=>f({type:"SET_STATE",payload:{showCookieModal:!1}}),onSuccess:()=>{j.invalidateQueries({queryKey:["video-sources",n,e.currentEpisode,e.selectedProvider,e.currentMode]})}}),!ge&&r("aside",{ref:je,className:Ge.episodeSidebar,children:e.loadingShowData?r(gn,{variant:"sidebar"}):r(bn,{episodes:e.episodes,currentEpisode:e.currentEpisode,watchedEpisodes:e.watchedEpisodes,onEpisodeClick:t=>k(`/watch/${n}/${t}`)})}),r("div",{className:Ge.playerMain,children:[r("div",{className:`${u.videoContainer} ${a.state.isFullscreen?"":Ge.videoPlayerWrapper} ${a.state.isFullscreen?u.fullscreenActive:""}`,style:{...ht?{visibility:"hidden"}:{}},onContextMenu:t=>t.preventDefault(),children:r(ys,{player:a,isAutoplayEnabled:e.isAutoplayEnabled,onAutoplayChange:Ar,fallbackChoice:re,onFallbackChoiceChange:ne,showNextEpisodeButton:!ht&&Pt&&y.length===0,onNextEpisode:_t,videoSources:e.videoSources,selectedSource:e.selectedSource,selectedLink:e.selectedLink,onSourceChange:(t,s)=>{p.videoRef.current&&!isNaN(p.videoRef.current.currentTime)&&(ee.current=p.videoRef.current.currentTime),ae(t.sourceName),f({type:"SET_STATE",payload:{selectedSource:t,selectedLink:s,showResumeModal:e.showResumeModal&&t.type!=="iframe"}})},loadingVideo:nt,skipIntervals:e.skipIntervals,animeTitle:vt,episodeNumber:e.currentEpisode,isTheaterMode:ge,onTheaterModeToggle:()=>{const t=!ge;Ut(t),localStorage.setItem("playerTheaterMode",t.toString())},anime4kEnabled:F.isEnabled,onAnime4kToggle:F.toggle,anime4kSupported:F.isWebGPUSupported,anime4kProfile:d,onAnime4kProfileChange:o,anime4kInitializing:F.isInitializing,anime4kError:F.error,videoDelayEnabled:D,onVideoDelayToggle:t=>{Y(t);try{localStorage.setItem("playerVideoDelayEnabled",String(t))}catch{}},videoDelayMs:l,onVideoDelayChange:K,onCalibrateAvSync:it,isInteractingExtra:Se||G,className:yn.shellFill,hideChrome:e.selectedSource?.type==="iframe",overlays:r(kt,{children:[a.state.isSpeedBoostActive&&r("div",{className:u.speedBoostBadge,"aria-hidden":"true",children:[r("span",{children:"2x"}),r(q,{name:"forward",size:12})]}),Qe!==null&&ve?.nextItem&&r("div",{className:u.queueCountdown,children:["Queue next in ",Qe,"s"]})]}),children:[Tt&&r("div",{className:`${u.skipIndicatorContainer} ${Tt.side==="left"?u.leftSkip:u.rightSkip} `,children:r("div",{className:u.skipBubble,children:[r("div",{className:u.skipIcon,children:Tt.side==="left"?r(q,{name:"backward"}):r(q,{name:"forward"})}),r("div",{className:u.skipText,children:"15s"})]})}),nt&&r("div",{className:u.loadingOverlay,children:r("div",{className:u.loadingDots,children:[r("div",{className:u.dot}),r("div",{className:u.dot}),r("div",{className:u.dot})]})}),a.state.isBuffering&&!nt&&e.selectedSource?.type!=="iframe"&&r("div",{className:u.bufferingOverlay,children:r("div",{className:u.bufferingSpinner})}),e.selectedSource?.type==="iframe"?!nt&&r("iframe",{src:e.selectedLink?.link,className:u.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}):r(kt,{children:[!nt&&e.videoSources.length===0&&r("div",{className:u.errorOverlay,children:[r("p",{children:["No sources found for this episode with ",e.selectedProvider,"."]}),r("p",{className:u.errorSubtext,children:"Please try selecting a different provider below."}),r("button",{className:u.retryButton,onClick:()=>window.location.reload(),"data-speed-boost-ignore":"true",style:{marginTop:8},children:"Retry"})]}),!nt&&e.videoSources.length>0&&r("video",{ref:p.videoRef,controls:a.state.useNativeControls,playsInline:!0,"webkit-playsinline":"true",disablePictureInPicture:!0,disableRemotePlayback:!0,onPlay:M.onPlay,onPause:M.onPause,onLoadedMetadata:M.onLoadedMetadata,onTimeUpdate:()=>{ie||(M.onTimeUpdate(),ve&&p.videoRef.current&&p.videoRef.current.currentTime<p.videoRef.current.duration-1&&(tt(null),Ze(null)))},onProgress:M.onProgress,onVolumeChange:M.onVolumeChange,onWaiting:M.onWaiting,onPlaying:M.onPlaying,onError:er,onContextMenu:t=>t.preventDefault(),className:Ie?u.videoElementHidden:""}),F.isWebGPUSupported&&!nt&&e.videoSources.length>0&&r("canvas",{ref:be,className:`${u.upscalerCanvas} ${Ve?u.upscalerActive:""}`}),!Ve&&!nt&&e.videoSources.length>0&&r("canvas",{ref:yt,className:`${u.upscalerCanvas} ${Ue?u.upscalerActive:""}`}),F.isEnabled&&F.isWebGPUSupported&&F.isInitializing&&r("div",{className:u.upscalerStatusBadge,children:"Preparing upscaler…"}),Ie&&r("div",{ref:Ye,className:u.subtitleOverlay}),r(Sn,{isOpen:G,ms:l,onChange:K,onApply:te,onClose:dt,testClipActive:ie,onTestClip:ue})]})]})}),!ge&&r(En,{}),!ge&&r(kt,{children:[Vt&&y.length===0?r(Ss,{count:3}):r(Mn,{title:"Queue",items:y,currentShowId:n,currentEpisode:e.currentEpisode,onNextQueue:Gt,onRemove:t=>rt.mutate({showId:t.showId,episodeNumber:t.episodeNumber}),onClear:()=>At.mutate(),showClearAll:!0,onReorder:t=>br.mutate(t.map(s=>({id:s.id,showId:s.showId,episodeNumber:s.episodeNumber})))}),r("div",{className:u.providerAndEpisodeRow,children:[r(_s,{selectedProvider:e.selectedProvider,isAdult:e.showMeta?.isAdult,options:B,onProviderChange:t=>{ze.current=!1,Me.current=[],et.current=!1,_e(null),f({type:"SET_STATE",payload:{selectedProvider:t,videoSources:[],selectedSource:null,selectedLink:null,loadingVideo:!0}}),localStorage.setItem("preferredProvider",t)}}),or(`${u.episodeActions} ${u.desktopEpisodeActions}`,"desktop")]}),nt?r("div",{className:u.sourceLoader,children:r("div",{className:u.spinner})}):r(kt,{children:r(Ps,{videoSources:e.videoSources,selectedSource:e.selectedSource,selectedLink:e.selectedLink,onSourceChange:t=>{p.videoRef.current&&!isNaN(p.videoRef.current.currentTime)&&(ee.current=p.videoRef.current.currentTime);const i=(t.links||[]).sort((c,C)=>(parseInt(C.resolutionStr)||0)-(parseInt(c.resolutionStr)||0))[0]||null;ae(t.sourceName),f({type:"SET_STATE",payload:{selectedSource:t,selectedLink:i,showResumeModal:e.showResumeModal&&t.type!=="iframe"}})},onLinkChange:t=>{e.selectedSource&&(ae(e.selectedSource.sourceName),f({type:"SET_STATE",payload:{selectedLink:t}}))}})}),r("div",{className:Ge.playerInfoContainer,children:[r("div",{className:Ge.playerInfoHeader,children:[r("div",{className:Ge.playerAnimeCard,children:r("img",{src:tn(e.showMeta.thumbnail||""),alt:vt,loading:"lazy",decoding:"async",onError:t=>{t.target.src="/placeholder.svg"}})}),r("div",{className:Ge.videoTitleSection,children:[r("div",{className:u.titleContainer,children:[r("h1",{children:vt}),r("div",{className:u.scheduleInfo,children:[e.showMeta.status&&r("span",{className:u.status,children:e.showMeta.status}),e.showMeta.nextEpisodeAirDate&&r("span",{className:u.nextEpisode,children:["Next episode: ",e.showMeta.nextEpisodeAirDate]})]})]}),r("div",{className:u.controls,children:[r("button",{className:`${u.watchlistBtn} ${e.inWatchlist?u.inList:""}`,onClick:Te,children:[e.inWatchlist?r(q,{name:"check",size:14}):r(q,{name:"plus",size:14}),e.inWatchlist?"In Watchlist":"Add to Watchlist"]}),r(Pn,{showId:n,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:`${u.watchlistBtn} ${u.queueBtn}`,activeClassName:u.queueActive}),Br&&r("button",{className:`${u.watchlistBtn} ${u.markWatchedBtn} ${ar?u.markWatchedDone:""}`,onClick:Lr,disabled:$||!e.currentEpisode,children:[r(q,{name:"check",size:14}),$?"Saving...":ar?"Watched":"Mark Watched"]}),r("button",{className:`${u.watchlistBtn} ${u.modeToggleBtn} ${e.currentMode==="dub"?u.modeToggleActive:""}`,onClick:()=>{const t=e.currentMode==="dub"?"sub":"dub";ze.current=!1,Me.current=[],et.current=!1,_e(null),f({type:"SET_MODE",payload:t}),localStorage.setItem("preferredMode",t)},type:"button","aria-pressed":e.currentMode==="dub",children:e.currentMode==="dub"?"DUB":"SUB"}),Rr&&r("button",{className:`${u.watchlistBtn} ${u.modeToggleBtn} ${a.state.useNativeControls?u.modeToggleActive:""}`,onClick:()=>{const t=!a.state.useNativeControls;a.actions.setUseNativeControls(t),localStorage.setItem("playerUseNativeControls",t.toString())},type:"button",children:a.state.useNativeControls?"NATIVE: ON":"NATIVE: OFF"})]})]})]}),or(`${u.episodeActions} ${u.mobileEpisodeActions}`,"mobile"),r("div",{className:u.descriptionSection,children:[r("h3",{children:"Synopsis"}),r(An,{text:e.showMeta.description?e.showMeta.description.replace(/<[^>]*>?/gm,""):"",emptyText:"No description available."})]}),r("button",{className:u.detailsToggleBtn,onClick:Fe,children:[e.showCombinedDetails?r(q,{name:"chevron-up"}):r(q,{name:"chevron-down"}),e.showCombinedDetails?"Hide Details":"Show Details"]}),e.showCombinedDetails&&r(xn,{showMeta:e.showMeta,styles:u})]})]})]}),r(wn,{isOpen:Se,onClose:()=>Ct(!1),episodes:e.episodes,currentEpisode:e.currentEpisode,watchedEpisodes:e.watchedEpisodes,onEpisodeClick:t=>{Ct(!1),k(`/watch/${n}/${t}`)}})]})};export{io as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{g as I,d as X,T as Y,u as e}from"./vendor-core-DfaOB3Rn.js";import{I as o}from"./vendor-icons-DrybRNxP.js";import{S as Z,O as _,a as ee,A as ne}from"./OptionListMenu-C1pvpu8X.js";import{u as te}from"./index-HZNJp28e.js";import"./AvSyncCalibrator-BroSW86T.js";import"./vendor-query-BBT5_sHx.js";import"./useProviders-CKSedfqb.js";const ae="_settingsPanel_y6z3b_1",se="_header_y6z3b_33",le="_backBtn_y6z3b_56",ie="_contentWrapper_y6z3b_76",re="_menuContent_y6z3b_82",ce="_menuItem_y6z3b_89",oe="_selected_y6z3b_114",de="_currentValue_y6z3b_134",me="_menuNote_y6z3b_141",ue="_menuError_y6z3b_150",n={settingsPanel:ae,header:se,backBtn:le,contentWrapper:ie,menuContent:re,menuItem:ce,selected:oe,currentValue:de,menuNote:me,menuError:ue},he=(A,z)=>{const{isOpen:b,onClose:pe,videoSources:be,currentSource:v,currentLink:k,onSourceChange:w,subtitles:$,activeSubtitleTrack:y,onSubtitleChange:P,subtitleSettings:V,onSubtitleSettingsChange:O,useNativeControls:g,onNativeControlsToggle:E,anime4kEnabled:u,onAnime4kToggle:U,anime4kSupported:C,anime4kProfile:i,onAnime4kProfileChange:h,anime4kInitializing:B,anime4kError:f,videoDelayEnabled:N,onVideoDelayToggle:T,videoDelayMs:S,onVideoDelayChange:D,onCalibrateAvSync:M,isAutoSkipEnabled:d,onAutoSkipChange:x,isAutoplayEnabled:m,onAutoplayChange:L,fallbackChoice:p,onFallbackChoiceChange:W}=A,{lowEndMode:G}=te(),[a,r]=X("main");I.useEffect(()=>{if(!b){const t=setTimeout(()=>r("main"),300);return()=>clearTimeout(t)}},[b]);const j=()=>e("div",{className:n.menuContent,children:[e("button",{className:n.menuItem,onClick:()=>r("quality"),children:[e("span",{children:"Quality"}),e("span",{className:n.currentValue,children:k?.resolutionStr||"Auto"})]}),e("button",{className:n.menuItem,onClick:()=>r("subtitles"),children:[e("span",{children:"Subtitles"}),e("span",{className:n.currentValue,children:y||"Off"})]}),e("button",{className:n.menuItem,onClick:()=>r("subtitle-style"),children:e("span",{children:"Subtitle Style"})}),G&&e("button",{className:`${n.menuItem} ${g?n.selected:""}`,onClick:()=>{const t=!g;E(t),localStorage.setItem("playerUseNativeControls",t.toString())},children:[e("span",{children:"Native Controls"}),g&&e(o,{name:"check",size:12})]}),C&&e("button",{className:`${n.menuItem} ${u?n.selected:""}`,onClick:()=>{U(!u)},children:[e("span",{children:"Anime4K Upscaler"}),u&&e(o,{name:"check",size:12})]}),C&&u&&e("button",{className:n.menuItem,onClick:()=>r("upscaler"),children:e("span",{children:"Upscaler Settings"})}),e("button",{className:n.menuItem,onClick:()=>r("av-sync"),children:[e("span",{children:"A/V Sync"}),e("span",{className:n.currentValue,children:N?`${S}ms`:"Off"})]}),e("button",{className:n.menuItem,onClick:()=>r("playback"),children:[e("span",{children:"Playback"}),e("span",{className:n.currentValue,children:[d?"Auto-skip On":null,m?"Autoplay On":null].filter(Boolean).join(" • ")||"Off"})]})]}),q=()=>{const t=v?.links.sort((s,c)=>(parseInt(c.resolutionStr)||0)-(parseInt(s.resolutionStr)||0))||[];return e("div",{className:n.menuContent,children:e(_,{classes:{item:n.menuItem,active:n.selected},options:t.map(s=>({key:s.resolutionStr,label:s.resolutionStr,selected:k?.resolutionStr===s.resolutionStr})),onSelect:s=>{const c=t.find(l=>l.resolutionStr===s);c&&w(v,c)}})})},F=()=>e("div",{className:n.menuContent,children:e(_,{classes:{item:n.menuItem,active:n.selected},options:[{key:"off",label:"Off",selected:y==="off"},...$.map(t=>({key:t.label||t.lang,label:t.label,selected:y===(t.label||t.lang)}))],onSelect:t=>P(t)})}),Q=()=>e("div",{className:n.menuContent,children:e(ee,{classes:{item:n.menuItem,active:n.selected},values:V,onChange:O})}),R=Y(()=>{try{const s=navigator.userAgentData?.brands?.map(l=>l.brand.toLowerCase())??[];if(s.length>0)return s.some(l=>l.includes("chromium")||l.includes("chrome")||l.includes("edge")||l.includes("opera")||l.includes("brave")||l.includes("vivaldi"));const c=navigator.userAgent.toLowerCase();return c.includes("chrome")||c.includes("chromium")||c.includes("edg")}catch{return!0}},[]),H=()=>e("div",{className:n.menuContent,children:[B&&e("div",{className:n.menuNote,role:"status",children:"Preparing GPU, this can take a few seconds…"}),f&&e("div",{className:n.menuError,role:"alert",children:["Upscaler failed: ",f]}),!R&&e("div",{className:n.menuNote,children:"Upscaling performs best in Chrome-based browsers."}),e("button",{className:`${n.menuItem} ${i==="low"?n.selected:""}`,onClick:()=>h("low"),children:[e("div",{children:[e("div",{children:"Low"}),e("div",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)"},children:"Lightest, best for weaker GPUs"})]}),i==="low"&&e(o,{name:"check",size:12})]}),e("button",{className:`${n.menuItem} ${i==="balanced"?n.selected:""}`,onClick:()=>h("balanced"),children:[e("div",{children:[e("div",{children:"Balanced"}),e("div",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)"},children:"Source + display aware"})]}),i==="balanced"&&e(o,{name:"check",size:12})]}),e("button",{className:`${n.menuItem} ${i==="high"?n.selected:""}`,onClick:()=>h("high"),children:[e("div",{children:[e("div",{children:"High"}),e("div",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)"},children:"Aggressive, needs strong GPU"})]}),i==="high"&&e(o,{name:"check",size:12})]}),e("button",{className:`${n.menuItem} ${i==="denoise"?n.selected:""}`,onClick:()=>h("denoise"),children:[e("div",{children:[e("div",{children:"Denoise"}),e("div",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)"},children:"Denoise + upscale noisy, compressed sources"})]}),i==="denoise"&&e(o,{name:"check",size:12})]})]}),K=()=>e("div",{className:n.menuContent,children:[e("button",{type:"button",className:`${n.menuItem} ${d?n.selected:""}`,onClick:()=>x(!d),"aria-pressed":d,children:[e("span",{children:"Auto-skip openings and endings"}),e("span",{className:n.currentValue,children:d?"On":"Off"})]}),e("div",{className:n.menuNote,children:"Automatically jump past opening, ending and recap segments when detected."}),e("button",{type:"button",className:`${n.menuItem} ${m?n.selected:""}`,onClick:()=>L(!m),"aria-pressed":m,children:[e("span",{children:"Autoplay next episode"}),e("span",{className:n.currentValue,children:m?"On":"Off"})]}),e("div",{className:n.menuNote,children:"Automatically start the next episode when this one ends."}),e("button",{type:"button",className:n.menuItem,onClick:()=>W(p==="ask"?"iframe":p==="iframe"?"retry":"ask"),children:[e("span",{children:"Failed direct stream"}),e("span",{className:n.currentValue,children:p==="iframe"?"Use iframe":p==="retry"?"Try provider":"Ask me"})]}),e("div",{className:n.menuNote,children:"When a direct stream fails: ask each time, go straight to the embedded player (may show ads), or automatically try another provider."})]}),J=()=>e("div",{className:n.menuContent,children:e(ne,{classes:{item:n.menuItem,active:n.selected,note:n.menuNote},enabled:N,delayMs:S,onToggle:T,onDelayChange:D,onCalibrate:M})});return b?e(Z,{classes:{panel:n.settingsPanel,header:n.header,backBtn:n.backBtn,title:"",content:n.contentWrapper},title:a==="main"?"Settings":a.charAt(0).toUpperCase()+a.slice(1).replace("-"," "),titleTag:"h3",showBack:a!=="main",onBack:()=>r("main"),panelRef:z,onPanelClick:t=>t.stopPropagation(),children:[a==="main"&&j(),a==="quality"&&q(),a==="subtitles"&&F(),a==="subtitle-style"&&Q(),a==="upscaler"&&H(),a==="av-sync"&&J(),a==="playback"&&K()]}):null},Se=I.forwardRef(he);export{Se as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{d as h,A as j,h as y,g as se,u as e,S as T,$ as _,T as K}from"./vendor-core-DfaOB3Rn.js";import{I as o}from"./vendor-icons-DrybRNxP.js";import{b as Z}from"./vendor-query-BBT5_sHx.js";import{g as x,t as G}from"./index-HZNJp28e.js";import{a}from"./Asmr.module-ChUXDZKx.js";import{r as i}from"./Radio.module-DGSZLpKM.js";const ee=300*1e3,re="https://cdn.listen.moe/covers/";function V(n){return n?n.startsWith("http")?n:`${re}${n}`:null}function le(n){return n?V(n.albums[0]?.image)||V(n.artists[0]?.image)||V(n.sources[0]?.image):null}function H(n){return n?n.artists.map(s=>s.nameRomaji||s.name).join(", "):""}const oe=()=>{const n=x();return Z({...n.radio.stations.queryOptions(),staleTime:ee})},ie=n=>{const s=x();return Z({...s.radio.search.queryOptions({q:n}),enabled:n.trim().length>0,staleTime:ee})},X={song:null,lastPlayed:[],listeners:0,startTime:null},ce=n=>{const[s,p]=h(X),[l,c]=h(!1),d=j(null);return y(()=>{if(p(X),c(!1),!n)return;let m=null,f=!1;try{m=new WebSocket(n)}catch{return}return m.onopen=()=>{f||c(!0)},m.onmessage=v=>{try{const u=JSON.parse(v.data);if(u.op===0){const b=u.d?.heartbeat||35e3;d.current&&window.clearInterval(d.current),d.current=window.setInterval(()=>{m&&m.readyState===WebSocket.OPEN&&m.send(JSON.stringify({op:9}))},b)}else u.op===1&&p({song:u.d?.song||null,lastPlayed:u.d?.lastPlayed||[],listeners:u.d?.listeners||0,startTime:u.d?.startTime||null})}catch{}},m.onclose=()=>{f||c(!1)},()=>{f=!0,d.current&&window.clearInterval(d.current),d.current=null,m&&m.close()}},[n]),{nowPlaying:s,connected:l}};function Y(n){if(!n)return"";const s=Math.max(0,Math.floor((Date.now()-new Date(n).getTime())/1e3)),p=Math.floor(s/60),l=s%60;return`${p}:${String(l).padStart(2,"0")}`}const de=({station:n,nowPlaying:s,connected:p,expanded:l,onStationStep:c,onExpandedChange:d,onClose:m})=>{const f=j(null),[v,u]=h(!1),[b,F]=h(!0),[S,I]=h(!1),[L,k]=h(!0),[M,P]=h(""),[N,A]=h(()=>{const t=parseFloat(localStorage.getItem("radioVolume")||"");return Number.isFinite(t)?t:1}),r=j(""),g=j(N);g.current=N,r.current||(r.current=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`radio-${Date.now()}-${Math.random().toString(36).slice(2)}`);const w=s.song,C=le(w)||n.favicon||null,[R,q]=h(!1);y(()=>{q(!1)},[C]);const E=R?null:C,U=!!E,B=w?`${H(w)} — ${w.title}`:n.name;y(()=>{const t=f.current;if(t)return u(!1),t.src=n.streamUrl,t.load(),t.volume=g.current,t.play().catch(()=>u(!1)),()=>{t.removeAttribute("src")}},[n.id,n.streamUrl]),y(()=>{const t=f.current;t&&(t.volume=N)},[N]),y(()=>{if(l)return document.body.classList.add("asmr-player-open"),()=>document.body.classList.remove("asmr-player-open")},[l]),y(()=>{l&&k(!0)},[l]);const te=t=>t?Math.max(0,Math.floor((Date.now()-new Date(t).getTime())/1e3)):0,O=se.useCallback(t=>{n&&(G.discord.radioPresence.mutate({title:B,stationLabel:n.name,isPlaying:t,thumbnail:E||"",currentTime:te(s.startTime),sessionId:r.current}).catch(()=>{}),G.discord.heartbeat.mutate({sessionId:r.current}).catch(()=>{}))},[n,B,E,s.startTime]);y(()=>{O(v)},[O,v,n.id,B,l]),y(()=>{if(!v)return;const t=window.setInterval(()=>O(!0),15e3);return()=>window.clearInterval(t)},[v,O]),y(()=>{const t=r.current,$=()=>{if(!t)return;const Q=JSON.stringify({sessionId:t});navigator.sendBeacon?(navigator.sendBeacon("/api/discord/clear",new Blob([Q],{type:"application/json"})),navigator.sendBeacon("/api/discord/heartbeat",new Blob([JSON.stringify({sessionId:t,bye:!0})],{type:"application/json"}))):(fetch("/api/discord/clear",{method:"POST",headers:{"Content-Type":"application/json"},body:Q,keepalive:!0}).catch(()=>{}),fetch("/api/discord/heartbeat",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:t,bye:!0}),keepalive:!0}).catch(()=>{}))},D=()=>$(),W=()=>{document.visibilityState==="hidden"&&$()};return window.addEventListener("pagehide",D),window.addEventListener("beforeunload",D),document.addEventListener("visibilitychange",W),()=>{window.removeEventListener("pagehide",D),window.removeEventListener("beforeunload",D),document.removeEventListener("visibilitychange",W),$()}},[]),y(()=>{if(!s.startTime){P("");return}P(Y(s.startTime));const t=window.setInterval(()=>P(Y(s.startTime)),1e3);return()=>window.clearInterval(t)},[s.startTime,s.song?.id]),y(()=>{if(!l)return;const t=$=>{$.key==="Escape"&&(S?I(!1):d(!1))};return window.addEventListener("keydown",t),()=>window.removeEventListener("keydown",t)},[l,S,d]);const ae=()=>{const t=f.current;t&&(t.paused?(t.load(),t.play().catch(()=>{})):t.pause())},ne=e(T,{children:[e("div",{className:a.playerButtons,children:[e("button",{className:a.playerBtn,onClick:()=>c(-1),"aria-label":"Previous station",children:e(o,{name:"step-backward"})}),e("button",{className:`${a.playerBtn} ${a.playBtn}`,onClick:ae,"aria-label":v?"Pause":"Play",children:v?e(o,{name:"pause"}):e(o,{name:"play"})}),e("button",{className:a.playerBtn,onClick:()=>c(1),"aria-label":"Next station",children:e(o,{name:"step-forward"})})]}),e("div",{className:a.seekRow,children:[e("span",{className:i.liveBadge,children:[e(o,{name:"broadcast-tower",size:10})," LIVE"]}),M&&e("span",{className:a.timeLabel,children:M}),p&&s.listeners>0&&e("span",{className:a.timeLabel,children:[s.listeners," listening"]}),!p&&n.source==="listen.moe"&&e("span",{className:a.timeLabel,children:"connecting…"})]})]}),z=e(T,{children:[e("button",{className:`${a.playerBtn} ${a.playerToggle}`,onClick:()=>d(!l),"aria-label":l?"Minimize player":"Expand player",title:l?"Minimize to browse":"Expand",children:l?e(o,{name:"chevron-down"}):e(o,{name:"chevron-up"})}),e("div",{className:a.playerInfo,children:[e("p",{className:a.playerTitle,title:B,children:B}),e("p",{className:a.playerTrack,children:n.name})]}),e("div",{className:a.playerControls,children:ne}),e("div",{className:a.playerRight,children:[N===0?e(o,{name:"volume-mute",className:a.volumeIcon}):N<.5?e(o,{name:"volume-down",className:a.volumeIcon}):e(o,{name:"volume-up",className:a.volumeIcon}),e("input",{className:a.volumeBar,type:"range",min:0,max:1,step:.01,value:N,onChange:t=>{const $=parseFloat(t.target.value);A($),localStorage.setItem("radioVolume",String($))},style:{"--volume-percent":`${N*100}%`},"aria-label":"Volume"})]}),e("div",{className:a.playerActions,children:[l&&U&&e("button",{className:a.playerBtn,onClick:()=>F(t=>!t),"aria-label":b?"Hide art":"Show art",title:b?"Hide art":"Show art",children:b?e(o,{name:"eye-slash"}):e(o,{name:"image"})}),l&&s.lastPlayed.length>0&&e("button",{className:`${a.playerBtn} ${S?a.playerBtnActive:""}`,onClick:()=>I(t=>!t),"aria-label":S?"Hide history":"Show history",title:"Recently played",children:e(o,{name:"list-ol"})}),e("button",{className:a.playerBtn,onClick:m,"aria-label":"Close player",children:e(o,{name:"times"})})]})]}),J=e("audio",{ref:f,preload:"none",onPlay:()=>u(!0),onPause:()=>u(!1)});return l?_(e(T,{children:[J,e("div",{className:`${a.npOverlay} ${L?"":a.npOverlayControlsHidden}`,children:[e("div",{className:`${a.npStage} ${!b||!U?a.npStageBlank:""}`,onClick:()=>k(t=>!t),children:b&&U&&E&&e("div",{className:i.coverWrap,children:e("img",{src:E,alt:B,loading:"lazy",decoding:"async",draggable:!1,className:i.cover,onError:()=>q(!0)})})}),e("div",{className:`${a.playerBar} ${a.playerBarDocked} ${L?"":a.playerBarDockedHidden}`,onClick:t=>t.stopPropagation(),children:[z,S&&e(T,{children:[e("div",{className:a.npBackdrop,onClick:()=>I(!1)}),e("div",{className:a.chapterPanel,children:s.lastPlayed.map(t=>e("div",{className:a.chapterRow,children:e("span",{className:a.chapterRowLabel,title:`${H(t)} — ${t.title}`,children:[H(t)," — ",t.title]})},t.id))})]})]})]})]}),document.body):_(e(T,{children:[J,e("div",{className:a.playerBar,children:z})]}),document.body)},ve=()=>{y(()=>{document.title="Radio - dango"},[]);const[n,s]=h(""),[p,l]=h(""),[c,d]=h(null),[m,f]=h(!0),{data:v,isLoading:u}=oe(),{data:b,isLoading:F}=ie(p),S=K(()=>v?.stations||[],[v]),I=K(()=>b?.stations||[],[b]),L=p?I:S,{nowPlaying:k,connected:M}=ce(c?.gateway),P=r=>{d(r),f(!0)},N=r=>{const g=L.length>0?L:S;if(g.length===0||!c)return;const w=g.findIndex(R=>R.id===c.id),C=g[(w<0?0:w+r+g.length)%g.length];d(C)},A=r=>{const g=c?.id===r.id,w=g&&k.song?`${H(k.song)} — ${k.song.title}`:null,C=[r.codec,r.bitrate?`${r.bitrate}k`:"",r.tags].filter(Boolean).join(" · ");return e("button",{className:`${i.stationRow} ${g?i.stationRowActive:""}`,onClick:()=>P(r),children:[r.favicon?e("img",{src:r.favicon,alt:"",className:i.stationThumb,loading:"lazy",decoding:"async",onError:R=>{R.target.style.display="none"}}):e("span",{className:i.stationThumbPlaceholder,children:e(o,{name:"broadcast-tower"})}),e("span",{className:i.stationMeta,children:[e("span",{className:i.stationName,children:r.name}),C&&e("span",{className:i.stationSub,children:C})]}),w&&e("span",{className:i.stationNowPlaying,children:w})]},r.id)};return e("div",{className:`${a.page} ${c?a.pageWithPlayer:""}`,children:[e("div",{className:a.header,children:[e("h1",{className:a.pageTitle,children:[e(o,{name:"broadcast-tower"})," Radio"]}),e("form",{className:a.searchForm,onSubmit:r=>{r.preventDefault(),l(n)},children:[e("input",{className:a.searchInput,value:n,onChange:r=>s(r.target.value),placeholder:"Search stations (anime, j-pop, k-pop…)","aria-label":"Search radio stations"}),e("button",{className:a.searchBtn,type:"submit","aria-label":"Search",children:e(o,{name:"search"})})]})]}),p?e(T,{children:[e("h2",{className:i.sectionTitle,children:["Results for “",p,"”"]}),F?e("p",{className:a.statusMsg,children:"Searching…"}):I.length===0?e("p",{className:a.statusMsg,children:"No stations found."}):e("div",{className:i.stationList,children:I.map(A)})]}):e(T,{children:[e("h2",{className:i.sectionTitle,children:"Featured"}),u?e("p",{className:a.statusMsg,children:"Loading…"}):e("div",{className:i.stationList,children:S.map(A)})]}),c&&e(de,{station:c,nowPlaying:k,connected:M,expanded:m,onStationStep:N,onExpandedChange:f,onClose:()=>d(null)})]})};export{ve as default};
|
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
import{d as s,A as V,h as O,u as e,q as ae,S as te,T as De,p as Ie,a as Le,g as me,_ as xe}from"./vendor-core-DfaOB3Rn.js";import{d as Pe,t as _,B as I,M as K,i as we,g as Ae,T as H,z as pe,E as oe,F as Oe,G as Ue,u as Me,H as Ee,x as ye,y as $e,I as Ge,J as Ke,V as Fe,K as He,L as Be,N as ze}from"./index-HZNJp28e.js";import{u as ue}from"./vendor-query-BBT5_sHx.js";import{I as W}from"./vendor-icons-DrybRNxP.js";const ce={"title-preference-container":"_title-preference-container_sdqgs_1","toggle-button":"_toggle-button_sdqgs_21","toggle-label":"_toggle-label_sdqgs_51"},le=["name","nativeName","englishName"],de={name:"Default (Romaji)",nativeName:"Native",englishName:"English"},qe=()=>{const{titlePreference:t,setTitlePreference:r,loading:i}=Pe(),[c,h]=s(de[t]),[d,k]=s(!1),m=V(null);O(()=>{i||h(de[t])},[t,i]);const a=async()=>{if(d)return;k(!0);const f=(le.indexOf(t)+1)%le.length,p=le[f],l=de[p];m.current&&(m.current.style.transform="translateX(-100%)",m.current.style.opacity="0"),setTimeout(async()=>{h(l),r(p),m.current&&(m.current.style.transition="none",m.current.style.transform="translateX(100%)",m.current.style.opacity="0",m.current.offsetWidth,m.current.style.transition="transform 0.3s ease-out, opacity 0.3s ease-out",m.current.style.transform="translateX(0)",m.current.style.opacity="1");try{await _.settings.set.mutate({key:"titlePreference",value:p})}catch(T){console.error("Error saving title preference:",T)}finally{k(!1)}},300)};return i?e("p",{children:"Loading title preference..."}):e("div",{className:ce["title-preference-container"],children:[e("h4",{children:"Anime Title Display Preference"}),e("button",{onClick:a,className:ce["toggle-button"],disabled:d,children:e("span",{ref:m,className:ce["toggle-label"],children:c})})]})},je="_settingsHeader_14a5d_1",We="_pageTitle_14a5d_6",Ve="_pageSubtitle_14a5d_14",Ye="_settingsLayout_14a5d_20",Qe="_sidebar_14a5d_27",Je="_sidebarIndicator_14a5d_35",Xe="_sidebarItem_14a5d_50",Ze="_active_14a5d_72",et="_mainContent_14a5d_80",tt="_tabContent_14a5d_85",at="_sectionCard_14a5d_103",nt="_settingItem_14a5d_127",rt="_settingRow_14a5d_132",st="_controls_14a5d_145",it="_status_14a5d_151",g={settingsHeader:je,pageTitle:We,pageSubtitle:Ve,settingsLayout:Ye,sidebar:Qe,sidebarIndicator:Je,sidebarItem:Xe,active:Ze,mainContent:et,tabContent:tt,sectionCard:at,settingItem:nt,settingRow:rt,controls:st,status:it},ot="_sectionCard_wt900_12",ct="_title_wt900_22",lt="_signIn_wt900_29",dt="_userInfo_wt900_36",ut="_warning_wt900_58",ht="_formGroup_wt900_65",gt="_label_wt900_69",mt="_inputWrapper_wt900_79",pt="_input_wt900_79",yt="_select_wt900_103",ft="_actions_wt900_140",wt="_hr_wt900_148",y={sectionCard:ot,title:ct,signIn:lt,userInfo:dt,warning:ut,formGroup:ht,label:gt,inputWrapper:mt,input:pt,select:yt,actions:ft,hr:wt},vt=()=>{const[t,r]=s(!0),[i,c]=s(!1),[h,d]=s(!1),[k,m]=s(null),[a,u]=s({status:"idle"}),[f,p]=s(!1),[l,T]=s(""),[w,S]=s(!1),D=V(null),[L,x]=s({show:!1,message:"",type:"info"}),U=()=>{D.current&&(window.clearInterval(D.current),D.current=null)},C=ae(N=>{d(N.authenticated),m(N.user||N.device.user||null),u(N.device),p(!!N.hasCustomClientId)},[]),R=ae(async()=>{const N=await _.auth.githubStatus.query();C(N)},[C]),E=async()=>{try{const N=await _.auth.githubPoll.query();u(N),N.status==="success"?(U(),await R(),x({show:!0,message:"GitHub authentication complete. Sync has been initialized.",type:"success"})):N.status==="error"&&(U(),x({show:!0,message:N.error||"GitHub authentication failed.",type:"error"}))}catch{U(),x({show:!0,message:"Failed to poll GitHub authentication status.",type:"error"})}},v=(N=5)=>{U(),D.current=window.setInterval(E,Math.max(N,5)*1e3)};O(()=>(R().catch(()=>{x({show:!0,message:"Failed to load GitHub sync status.",type:"error"})}).finally(()=>r(!1)),U),[R]);const b=async()=>{c(!0);try{const N=await _.auth.githubStart.mutate();u(N),v(N.verification?.interval)}catch(N){x({show:!0,message:N instanceof Error?N.message:"Failed to start GitHub authentication.",type:"error"})}finally{c(!1)}},A=async()=>{try{await _.auth.githubLogout.mutate(),d(!1),m(null),u({status:"idle"}),x({show:!0,message:"Signed out of GitHub sync.",type:"success"})}catch{x({show:!0,message:"Failed to sign out of GitHub.",type:"error"})}},M=async()=>{S(!0);try{await _.auth.saveGithubAuth.mutate({clientId:l}),T(""),await R(),x({show:!0,message:"Custom GitHub auth saved.",type:"success"})}catch{x({show:!0,message:"Failed to save override.",type:"error"})}finally{S(!1)}},z=async()=>{S(!0);try{await _.auth.saveGithubAuth.mutate({clientId:""}),T(""),await R(),x({show:!0,message:"Custom auth cleared. Using dango defaults.",type:"success"})}catch{x({show:!0,message:"Failed to clear override.",type:"error"})}finally{S(!1)}};return t?e("div",{style:{color:"var(--text-secondary)",padding:"1.5rem"},children:"Loading..."}):e("div",{className:y.sectionCard,children:[e("h3",{className:y.title,children:"GitHub Cloud Sync"}),e("p",{className:y.signIn,children:"Sync local data through a private GitHub repository named dango-sync-data."}),h&&k?e("div",{className:y.userInfo,children:[e("p",{children:["Signed in as: ",e("strong",{children:k.name||k.login})]}),e(I,{variant:"danger",onClick:A,children:"Sign Out"})]}):e("div",{className:y.signIn,children:e(I,{onClick:b,disabled:i||a.status==="pending",children:i||a.status==="pending"?"Waiting for GitHub...":"Sign in with GitHub"})}),a.status==="pending"&&a.verification&&e(te,{children:[e("hr",{className:y.hr}),e("div",{className:y.formGroup,children:[e("label",{className:y.label,children:"Verification URL"}),e("div",{className:y.inputWrapper,children:[e("input",{className:y.input,value:a.verification.verification_uri,readOnly:!0}),e(I,{onClick:()=>{const N=a.verification?.verification_uri;N&&/^https?:\/\//i.test(N)&&window.open(N,"_blank","noopener,noreferrer")},children:"Open"})]})]}),e("div",{className:y.formGroup,children:[e("label",{className:y.label,children:"Device Code"}),e("input",{className:y.input,value:a.verification.user_code,readOnly:!0})]})]}),a.status==="error"&&e("p",{className:y.warning,children:a.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:y.formGroup,style:{marginTop:"0.75rem"},children:[e("label",{className:y.label,children:"Client ID (optional)"}),e("input",{className:y.input,value:l,onChange:N=>T(N.currentTarget.value),placeholder:"Your GitHub OAuth app ID"})]}),e("div",{className:y.actions,children:[e(I,{onClick:M,disabled:w,children:"Save override"}),e(I,{variant:"secondary",onClick:z,disabled:w,children:"Use dango defaults"})]})]}),e(K,{isOpen:L.show,onClose:()=>x(N=>({...N,show:!1})),width:"sm",children:[e(K.Body,{children:e("p",{children:L.message})}),e(K.Actions,{children:e(I,{onClick:()=>x(N=>({...N,show:!1})),children:"OK"})})]})]})},bt=()=>{const[t,r]=s(!0),[i,c]=s(null),[h,d]=s(!1),[k,m]=s(!1),[a,u]=s(""),[f,p]=s(""),[l,T]=s(""),[w,S]=s(!1),[D,L]=s({show:!1,message:"",type:"info"}),x=async()=>{try{const b=await _.auth.user.query();c(b?.email?b:null)}catch{c(null)}},U=async()=>{try{const[b,A]=await Promise.all([_.auth.configStatus.query(),_.auth.googleAuth.query()]);d(!!b.hasConfig),m(!!(A.hasCustomWorkerUrl||A.hasCustomClientId||A.hasClientSecret))}catch(b){console.error("Failed to fetch config status",b)}};O(()=>{(async()=>{r(!0),await Promise.all([x(),U()]);try{new URLSearchParams(window.location.search).get("google_auth")==="success"&&(await x(),window.history.replaceState(null,"",window.location.pathname))}catch{}r(!1)})();const A=M=>{M.origin===window.location.origin&&typeof M.data=="object"&&M.data!==null&&M.data.type==="GOOGLE_AUTH_SUCCESS"&&(c(M.data.user),window.location.reload())};return window.addEventListener("message",A),()=>window.removeEventListener("message",A)},[]);const C=async()=>{try{const b=await _.auth.googleLogin.mutate();if(b.authenticated){window.location.reload();return}if(b.url){if(typeof window.DangoBridge<"u"){window.location.href=b.url;return}const M=600,z=700,N=window.innerWidth/2-M/2,ne=window.innerHeight/2-z/2;window.open(b.url,"GoogleAuth",`width=${M},height=${z},top=${ne},left=${N}`)}else throw new Error("Auth URL not available")}catch{L({show:!0,message:"Authentication failed. Ensure server is configured correctly.",type:"error"})}},R=async()=>{try{await _.auth.logout.mutate(),c(null),L({show:!0,message:"Successfully signed out.",type:"success"}),window.location.reload()}catch(b){console.error("Sign out failed",b),L({show:!0,message:"Failed to sign out.",type:"error"})}},E=async()=>{S(!0);try{await _.auth.saveGoogleAuth.mutate({workerUrl:a,clientId:f,clientSecret:l}),u(""),p(""),T(""),await U(),L({show:!0,message:"Custom auth saved. Restart may be required.",type:"success"})}catch{L({show:!0,message:"Failed to save override.",type:"error"})}finally{S(!1)}},v=async()=>{S(!0);try{await _.auth.saveGoogleAuth.mutate({workerUrl:"",clientId:"",clientSecret:""}),u(""),p(""),T(""),await U(),L({show:!0,message:"Custom auth cleared. Using dango defaults.",type:"success"})}catch{L({show:!0,message:"Failed to clear override.",type:"error"})}finally{S(!1)}};return t?e("div",{style:{color:"var(--text-secondary)",padding:"1.5rem"},children:"Loading..."}):e("div",{className:y.sectionCard,children:[e("h3",{className:y.title,children:"Google Drive Sync"}),i?e("div",{className:y.userInfo,children:[e("p",{children:["Signed in as: ",e("strong",{children:i.name})," (",i.email,")"]}),e(I,{variant:"danger",onClick:R,children:"Sign Out"})]}):e("div",{className:y.signIn,children:[e("p",{children:"Sign in with your Google account to enable synchronization features."}),e(I,{onClick:C,disabled:!h,children:"Sign in with Google"}),!h&&e("p",{className:y.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:y.formGroup,style:{marginTop:"0.75rem"},children:[e("label",{className:y.label,children:"Worker URL (optional)"}),e("input",{className:y.input,value:a,onChange:b=>u(b.currentTarget.value),placeholder:"https://your-worker.workers.dev"})]}),e("div",{className:y.formGroup,children:[e("label",{className:y.label,children:"Client ID (optional)"}),e("input",{className:y.input,value:f,onChange:b=>p(b.currentTarget.value),placeholder:"Your Google OAuth client ID"})]}),e("div",{className:y.formGroup,children:[e("label",{className:y.label,children:"Client Secret (optional)"}),e("input",{type:"password",className:y.input,value:l,onChange:b=>T(b.currentTarget.value),placeholder:"Your Google OAuth secret"})]}),e("div",{className:y.actions,children:[e(I,{onClick:E,disabled:w,children:"Save override"}),e(I,{variant:"secondary",onClick:v,disabled:w,children:"Use dango defaults"})]})]}),e(K,{isOpen:D.show,onClose:()=>L(b=>({...b,show:!1})),width:"sm",children:[e(K.Body,{children:e("p",{children:D.message})}),e(K.Actions,{children:e(I,{onClick:()=>L(b=>({...b,show:!1})),children:"OK"})})]})]})},_t="_sectionCard_1pqo4_1",kt="_settingItem_1pqo4_26",St="_settingRow_1pqo4_31",Ct="_modalOverlay_1pqo4_38",Nt="_modal_1pqo4_38",Tt="_modalActions_1pqo4_73",Rt="_modalSecondary_1pqo4_79",Dt="_modalPrimary_1pqo4_89",G={sectionCard:_t,settingItem:kt,settingRow:St,modalOverlay:Ct,modal:Nt,modalActions:Tt,modalSecondary:Rt,modalPrimary:Dt},It={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"]]}},Lt=(t,r)=>{if(t==null)return r;const i=String(t);return i==="true"||i==="1"?!0:i==="false"||i==="0"?!1:r},fe=(t,r,i)=>{const[c,h]=s(r),[d,k]=s(!1),m=ue();return O(()=>{(async()=>{try{const f=await _.settings.getByKey.query({key:t});h(Lt(f.value,r))}catch(f){console.error("Failed to fetch setting",f)}})()},[t,r]),{value:c,setValue:h,isUpdating:d,toggle:async()=>{if(d)return;k(!0);const u=!c;h(u);try{await _.settings.set.mutate({key:t,value:u});for(const f of i)m.invalidateQueries({queryKey:f})}catch(f){console.error("Error saving setting:",f),h(!u)}finally{k(!1)}}}},xt=()=>{const{contentType:t}=we(),r=It[t],[i,c]=s(!1),[h,d]=s(!0),[k,m]=s(!1),a=fe(r.ignoreKey,!0,r.invalidateKeys),u=fe(r.listOnlyKey,!1,r.invalidateKeys),[f,p]=s(null),[l,T]=s(!1),w=ue(),S=Ae();O(()=>{d(!0),(async()=>{try{const R=await _.settings.getByKey.query({key:r.skipKey});String(R.value)==="true"||String(R.value)==="1"?c(!0):c(!1)}catch(R){console.error("Failed to fetch setting",R)}finally{d(!1)}})()},[r.skipKey]);const D=async()=>{if(k)return;m(!0);const C=!i;c(C);try{await _.settings.set.mutate({key:r.skipKey,value:C})}catch(R){console.error("Error saving setting:",R),c(!C)}finally{m(!1)}},L=async()=>{if(!a.isUpdating){if(a.value)try{let C;if(t==="anime"?C=(await _.continueWatching.adultCount.query()).count:t==="manga"?C=(await _.mangaProgress.adultCount.query()).count:t==="asmr"?C=(await _.asmrProgress.adultCount.query()).count:C=(await _.tvProgress.adultCount.query()).count,typeof C=="number"&&C>0){p(C);return}}catch(C){console.error("Failed to fetch adult count",C)}a.toggle()}},x=()=>{p(null),a.toggle()},U=async()=>{if(!l){T(!0);try{let C;t==="anime"?C=(await _.continueWatching.purgeAdult.mutate()).removed:t==="manga"?C=(await _.mangaProgress.purgeAdult.mutate()).removed:t==="asmr"?C=(await _.asmrProgress.purgeAdult.mutate()).removed:C=(await _.tvProgress.purgeAdult.mutate()).removed,pe.success(r.purgeDoneText(C??0));for(const R of r.invalidateKeys)w.invalidateQueries({queryKey:R});t==="anime"&&w.invalidateQueries(S.continueWatching.pathFilter()),t==="manga"&&w.invalidateQueries(S.mangaProgress.pathFilter()),t==="asmr"&&w.invalidateQueries(S.asmrProgress.pathFilter()),t==="tv"&&w.invalidateQueries(S.tvProgress.pathFilter())}catch(C){console.error("Failed to purge adult entries",C),pe.error("Failed to remove adult entries")}finally{T(!1),p(null)}a.toggle()}};return h?e("div",{children:"Loading settings..."}):e("div",{className:G.sectionCard,children:[e("h3",{children:r.heading}),e("p",{children:r.blurb}),e("div",{className:G.settingItem,children:e("div",{className:G.settingRow,children:[e("label",{htmlFor:"skip-confirmation-toggle",children:r.skipLabel}),e(H,{isChecked:i,onChange:D,id:"skip-confirmation-toggle",disabled:k})]})}),e("div",{className:G.settingItem,children:e("div",{className:G.settingRow,children:[e("label",{htmlFor:"ignore-adult-toggle",children:r.ignoreLabel}),e(H,{isChecked:a.value,onChange:L,id:"ignore-adult-toggle",disabled:a.isUpdating})]})}),e("div",{className:G.settingItem,children:e("div",{className:G.settingRow,children:[e("label",{htmlFor:"cw-watchlist-only-toggle",children:r.listOnlyLabel}),e(H,{isChecked:u.value,onChange:u.toggle,id:"cw-watchlist-only-toggle",disabled:u.isUpdating})]})}),f!==null&&e("div",{className:G.modalOverlay,onClick:()=>p(null),children:e("div",{className:G.modal,onClick:C=>C.stopPropagation(),children:[e("h4",{children:"Show adult entries?"}),e("p",{children:[f," adult ",f===1?"entry":"entries"," not in your"," ",r.listNoun," ",f===1?"is":"are"," currently hidden from"," ",r.continueNoun,". You can purge ",f===1?"it":"them"," from the database instead of showing ",f===1?"it":"them","."]}),e("div",{className:G.modalActions,children:[e("button",{type:"button",className:G.modalSecondary,onClick:x,disabled:l,children:"Show them"}),e("button",{type:"button",className:G.modalPrimary,onClick:U,disabled:l,children:l?"Purging...":`Purge ${f}`})]})]})})]})},Pt="_sectionCard_jkggs_1",At="_statsGrid_jkggs_26",Ot="_statCard_jkggs_33",Ut="_statLabel_jkggs_43",Mt="_statValue_jkggs_51",Et="_statMeta_jkggs_57",$t="_statusBanner_jkggs_63",Gt="_statusSuccess_jkggs_74",Kt="_statusUpdating_jkggs_80",Ft="_statusError_jkggs_86",Ht="_sha_jkggs_92",Bt="_settingItem_jkggs_99",zt="_settingRow_jkggs_104",qt="_settingTitle_jkggs_111",jt="_settingSubtitle_jkggs_117",Wt="_actionsRow_jkggs_124",P={sectionCard:Pt,statsGrid:At,statCard:Ot,statLabel:Ut,statValue:Mt,statMeta:Et,statusBanner:$t,statusSuccess:Gt,statusUpdating:Kt,statusError:Ft,sha:Ht,settingItem:Bt,settingRow:zt,settingTitle:qt,settingSubtitle:jt,actionsRow:Wt},Vt=()=>{const[t,r]=s(null),[i,c]=s(!0),[h,d]=s(!1),[k,m]=s(!1),a=V(null),u=async()=>{try{const w=await _.settings.offlineDbInfo.query();return r(w),w}catch(w){console.error("Failed to fetch offline DB info:",w)}finally{c(!1)}return null};O(()=>(u(),()=>{a.current&&window.clearInterval(a.current)}),[]),O(()=>{t?.isRefreshing?a.current||(a.current=window.setInterval(async()=>{const w=await u();w&&!w.isRefreshing&&a.current&&(window.clearInterval(a.current),a.current=null)},2e3)):a.current&&(window.clearInterval(a.current),a.current=null)},[t?.isRefreshing]);const f=async()=>{if(!t||h)return;const w=!t.autoUpdateEnabled;d(!0),r({...t,autoUpdateEnabled:w});try{await _.settings.setOfflineDbAutoUpdate.mutate({enabled:w})}catch(S){console.error("Failed to update auto update setting:",S),r({...t,autoUpdateEnabled:!w})}finally{d(!1)}},p=async()=>{if(!(t?.isRefreshing||k)){m(!0);try{await _.settings.triggerOfflineDbUpdate.mutate(),r(w=>w?{...w,isRefreshing:!0,lastStatus:"updating",lastMessage:"Downloading database..."}:null)}catch(w){console.error("Failed to trigger offline DB update:",w)}finally{m(!1)}}},l=w=>{if(!w)return"Never";try{return new Date(w).toLocaleString(void 0,{dateStyle:"medium",timeStyle:"short"})}catch{return w}},T=t?.isRefreshing||k;return e("div",{className:P.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:P.statsGrid,children:[e("div",{className:P.statCard,children:[e("span",{className:P.statLabel,children:"MAL Mapped"}),e("span",{className:P.statValue,children:i?"—":(t?.totalMalMapped??0).toLocaleString()})]}),e("div",{className:P.statCard,children:[e("span",{className:P.statLabel,children:"Release"}),e("span",{className:P.statMeta,children:i?"—":t?.releaseTag??"Never"})]}),e("div",{className:P.statCard,children:[e("span",{className:P.statLabel,children:"Last Checked"}),e("span",{className:P.statMeta,children:i?"—":l(t?.lastCheckedAt??null)})]}),e("div",{className:P.statCard,children:[e("span",{className:P.statLabel,children:"Last Updated"}),e("span",{className:P.statMeta,children:i?"—":l(t?.lastUpdatedAt??null)})]})]}),t?.lastMessage&&e("div",{className:`${P.statusBanner} ${t.lastStatus==="failed"?P.statusError:t.lastStatus==="updating"?P.statusUpdating:P.statusSuccess}`,children:[e("span",{children:t.lastMessage}),t.contentSha256&&e("span",{className:P.sha,children:["sha:",t.contentSha256.slice(0,12)]})]}),e("div",{className:P.settingItem,children:e("div",{className:P.settingRow,children:[e("div",{children:[e("span",{className:P.settingTitle,children:"Weekly Automatic Updates (Saturdays)"}),e("div",{className:P.settingSubtitle,children:"Download and index new database releases in the background. Catches up on startup if the server was offline."})]}),e(H,{id:"offline-db-auto-update-toggle",isChecked:t?t.autoUpdateEnabled:!0,onChange:f,disabled:i||h})]})}),e("div",{className:P.actionsRow,children:e(I,{onClick:p,disabled:i||T,children:T?"Updating Database...":"Update Offline Database Now"})})]})},Yt="_sectionCard_1g4qx_1",Qt="_dangerCard_1g4qx_26",Jt="_status_1g4qx_34",Xt="_warningText_1g4qx_40",Zt="_ackLabel_1g4qx_44",ee={sectionCard:Yt,dangerCard:Qt,status:Jt,warningText:Xt,ackLabel:Zt},ea=()=>{const t=ue(),[r,i]=s(!1),[c,h]=s(!1),[d,k]=s(!1),[m,a]=s(""),u=()=>{h(!1),a(""),i(!0)},f=()=>{d||(i(!1),h(!1))},p=async()=>{if(!(!c||d)){k(!0),a("");try{const l=await fetch("/api/database/clear",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({confirm:!0})}),T=await l.json();if(!l.ok)throw new Error(T.error||"Failed to clear database");const w=T.deleted,S=T.deletedManga,D=T.deletedTv,L=T.deletedAsmr,x=Object.values(w).reduce((E,v)=>E+(v||0),0)+Object.values(S??{}).reduce((E,v)=>E+(v||0),0)+Object.values(D??{}).reduce((E,v)=>E+(v||0),0)+Object.values(L??{}).reduce((E,v)=>E+(v||0),0),U=(S?.manga_library??0)+(S?.manga_progress??0),C=(D?.tv_library??0)+(D?.tv_progress??0),R=(L?.asmr_library??0)+(L?.asmr_progress??0);a(`Library cleared — ${w.watchlist??0} watchlist entries, ${U} manga rows, ${C} TV rows, ${R} ASMR rows and ${x} total rows removed.`),t.invalidateQueries({queryKey:["watchlist"]}),t.invalidateQueries({queryKey:["allContinueWatching"]}),t.invalidateQueries({queryKey:["manga-library"]}),t.invalidateQueries({queryKey:["manga-library-ids"]}),t.invalidateQueries({queryKey:["manga-continue-reading"]}),t.invalidateQueries({queryKey:["tv-library"]}),t.invalidateQueries({queryKey:["tv-library-ids"]}),t.invalidateQueries({queryKey:["tv-continue-watching"]}),t.invalidateQueries({queryKey:["asmr-library"]}),t.invalidateQueries({queryKey:["asmr-library-ids"]}),t.invalidateQueries({queryKey:["asmr-continue-listening"]}),i(!1)}catch(l){a(l.message)}finally{k(!1),h(!1)}}};return e("div",{className:`${ee.sectionCard} ${ee.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(I,{variant:"danger",onClick:u,children:"Clear Library Data"}),m&&e("p",{className:ee.status,children:m}),e(K,{isOpen:r,onClose:f,title:"Clear library data?",width:"sm",children:[e(K.Body,{children:[e("p",{className:ee.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:ee.ackLabel,children:[e("input",{type:"checkbox",checked:c,onChange:l=>h(l.target.checked),disabled:d}),e("span",{children:"I understand this permanently deletes my library"})]})]}),e(K.Actions,{children:[e(I,{variant:"secondary",onClick:f,disabled:d,children:"Cancel"}),e(I,{variant:"danger",onClick:p,disabled:!c||d,children:d?"Clearing...":"Yes, delete everything"})]})]})]})},ta=()=>{const[t,r]=s(""),[i,c]=s([]),[h,d]=s(null),[k,m]=s(!0),[a,u]=s({show:!1,message:"",type:"info"}),f=async()=>{try{m(!0);const T=await(await fetch("/api/auth/settings/rclone")).json();r(T.remote||""),c(T.availableRemotes||[]),d(T.activeRemote||null)}catch(l){console.error("Failed to fetch Rclone settings",l)}finally{m(!1)}};O(()=>{f()},[]);const p=async()=>{try{if((await fetch("/api/auth/settings/rclone",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({remote:t})})).ok)u({show:!0,message:"Rclone configuration saved successfully. You must restart the server for these changes to take effect.",type:"success"}),f();else throw new Error("Failed to save")}catch{u({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:y.sectionCard,children:[e("h3",{className:y.title,children:"Rclone Cloud Sync"}),e("p",{className:y.signIn,children:"Configure which Rclone remote to use for database synchronization."}),h?e("div",{className:y.userInfo,children:e("p",{children:["Current Active Remote: ",e("strong",{children:h})]})}):e("p",{className:y.warning,style:{marginBottom:"1.5rem"},children:"Rclone sync is not currently active. Ensure rclone is installed and a remote is configured."}),e("div",{className:y.formGroup,children:[e("label",{className:y.label,children:"Remote Name"}),e("div",{className:y.inputWrapper,children:e("select",{className:y.select,value:t,onChange:l=>r(l.target.value),children:[e("option",{value:"",children:"(Disabled / None)"}),i.map(l=>e("option",{value:l,children:l},l)),t&&!i.includes(t)&&e("option",{value:t,children:[t," (Manual)"]})]})}),e("p",{className:y.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:y.actions,children:e(I,{onClick:p,children:"Save Rclone Settings"})}),e(K,{isOpen:a.show,onClose:()=>u(l=>({...l,show:!1})),width:"sm",children:[e(K.Body,{children:e("p",{children:a.message})}),e(K.Actions,{children:e(I,{onClick:()=>u(l=>({...l,show:!1})),children:"OK"})})]})]})},aa=()=>{const[t,r]=s(null),[i,c]=s(!0),h=async()=>{try{const u=await(await fetch("/api/auth/settings/sync")).json();r(u)}catch(a){console.error("Failed to fetch sync settings",a)}finally{c(!1)}};O(()=>{h()},[]);const d=async a=>{const u=a.target.value;try{const f=await fetch("/api/auth/settings/sync",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:u})});if(f.ok){const p=await f.json();r(l=>l?{...l,activeProvider:p.activeProvider}:null),await h(),oe.success(`Sync provider updated to ${u==="default"?"Default Order":u}`)}else oe.error("Failed to update sync provider")}catch{oe.error("Error updating sync provider")}};if(i||!t)return null;const k=[{value:"default",label:"Default (Priority Based)"}];t.authenticatedProviders.github&&k.push({value:"github",label:"GitHub"}),t.authenticatedProviders.google&&k.push({value:"google",label:"Google Drive"}),t.authenticatedProviders.rclone&&k.push({value:"rclone",label:"Rclone"}),k.push({value:"none",label:"None (Local Only)"});const m=a=>a==="none"?"Local Only (No Sync)":a==="google"?"Google Drive":a==="github"?"GitHub":a==="rclone"?"Rclone":a;return e("div",{className:g.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:m(t.actualActiveProvider)})]}),e("div",{className:g.settingRow,children:[e("label",{htmlFor:"sync-provider-select",children:"Selected Preference"}),e("select",{id:"sync-provider-select",value:t.activeProvider,onChange:d,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:k.map(a=>e("option",{value:a.value,children:a.label},a.value))})]})]})};function na(){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 ra=()=>{const t=De(na,[]);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:c=>{c.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(W,{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(I,{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.`})]})},sa="_sectionCard_1ag4p_1",ia="_settingItem_1ag4p_25",oa="_field_1ag4p_30",ca="_input_1ag4p_43",la="_actions_1ag4p_63",da="_status_1ag4p_69",B={sectionCard:sa,settingItem:ia,field:oa,input:ca,actions:la,status:da},ua=()=>{const[t,r]=s(!1),[i,c]=s(""),[h,d]=s(""),[k,m]=s(!0),[a,u]=s(!1),[f,p]=s("");O(()=>{(async()=>{try{const L=await(await fetch("/api/auth/app-status")).json();r(L.hasPassword)}catch{console.error("Failed to fetch LAN auth status")}finally{m(!1)}})()},[]);const l=async()=>{if(p(""),i!==h){p("Passwords do not match");return}if(i.length<4){p("Password must be at least 4 characters");return}u(!0);try{const S=await fetch("/api/auth/app-setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),D=await S.json();if(!S.ok){p(D.error||"Failed to update password");return}r(D.hasPassword),c(""),d(""),p(D.hasPassword?"Password set successfully":"Password removed")}catch{p("Network error")}finally{u(!1)}},T=async()=>{u(!0);try{const S=await fetch("/api/auth/app-setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:""})}),D=await S.json();if(!S.ok){p(D.error||"Failed to remove password");return}r(!1),c(""),d(""),p("Password removed")}catch{p("Network error")}finally{u(!1)}},w=async()=>{u(!0);try{await fetch("/api/auth/app-logout",{method:"POST"}),p("Logged out"),window.location.reload()}catch{p("Logout failed")}finally{u(!1)}};return k?e("div",{className:B.sectionCard,children:e("p",{children:"Loading..."})}):e("div",{className:B.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:B.settingItem,children:[e("div",{className:B.field,children:[e("label",{htmlFor:"lan-password",children:"New Password"}),e("input",{id:"lan-password",type:"password",value:i,onChange:S=>c(S.target.value),placeholder:t?"Leave empty to keep current password":"Enter a password...",className:B.input})]}),e("div",{className:B.field,children:[e("label",{htmlFor:"lan-confirm-password",children:"Confirm Password"}),e("input",{id:"lan-confirm-password",type:"password",value:h,onChange:S=>d(S.target.value),placeholder:"Confirm password...",className:B.input})]}),e("div",{className:B.actions,children:[e(I,{variant:"primary",onClick:l,loading:a,disabled:a,children:t?"Update Password":"Set Password"}),t&&e(I,{variant:"danger",onClick:w,loading:a,disabled:a,children:"Logout"}),t&&e(I,{variant:"secondary",onClick:T,loading:a,disabled:a,children:"Remove Password"})]}),f&&e("p",{className:B.status,children:f})]})]})},ha=()=>{const{theme:t,setTheme:r,loading:i}=Oe();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:Ue.map(c=>{const h=t===c.id;return e("button",{role:"radio","aria-checked":h,disabled:i,onClick:()=>r(c.id),style:{display:"flex",gap:"0.6rem",alignItems:"center",textAlign:"left",padding:"0.65rem 0.75rem",borderRadius:"10px",cursor:"pointer",background:h?"var(--accent-subtle)":"var(--bg-tertiary)",border:h?"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:c.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:c.label}),e("span",{style:{display:"block",fontSize:"0.75rem",color:"var(--text-secondary)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:c.blurb})]})]},c.id)})})]})},ga="_card_13wyw_1",ma="_cardHeader_13wyw_9",pa="_discordBadge_13wyw_16",ya="_cardTitle_13wyw_27",fa="_cardSub_13wyw_34",wa="_description_13wyw_40",va="_divider_13wyw_47",ba="_statsRow_13wyw_54",_a="_statBox_13wyw_61",ka="_statValue_13wyw_71",Sa="_statLabel_13wyw_78",Ca="_rolePreview_13wyw_86",Na="_badge_13wyw_93",Ta="_badgeRank_13wyw_100",Ra="_badgeDere_13wyw_106",Da="_progressSection_13wyw_112",Ia="_progressLabel_13wyw_116",La="_progressTrack_13wyw_124",xa="_progressFill_13wyw_132",Pa="_tierList_13wyw_139",Aa="_dereSection_13wyw_147",Oa="_sectionHeading_13wyw_152",Ua="_dereGrid_13wyw_161",Ma="_dereCard_13wyw_167",Ea="_dereCardActive_13wyw_178",$a="_dereName_13wyw_184",Ga="_dereGenre_13wyw_194",Ka="_actions_13wyw_199",Fa="_btnPrimary_13wyw_205",Ha="_btnSecondary_13wyw_234",Ba="_statusMsg_13wyw_257",za="_statusSuccess_13wyw_264",qa="_statusError_13wyw_270",ja="_statusInfo_13wyw_276",Wa="_userRow_13wyw_283",Va="_avatar_13wyw_294",Ya="_avatarPlaceholder_13wyw_302",Qa="_userName_13wyw_314",Ja="_userId_13wyw_320",Xa="_notice_13wyw_325",Za="_shareList_13wyw_332",en="_btnUnlink_13wyw_340",o={card:ga,cardHeader:ma,discordBadge:pa,cardTitle:ya,cardSub:fa,description:wa,divider:va,statsRow:ba,statBox:_a,statValue:ka,statLabel:Sa,rolePreview:Ca,badge:Na,badgeRank:Ta,badgeDere:Ra,progressSection:Da,progressLabel:Ia,progressTrack:La,progressFill:xa,tierList:Pa,dereSection:Aa,sectionHeading:Oa,dereGrid:Ua,dereCard:Ma,dereCardActive:Ea,dereName:$a,dereGenre:Ga,actions:Ka,btnPrimary:Fa,btnSecondary:Ha,statusMsg:Ba,statusSuccess:za,statusError:qa,statusInfo:ja,userRow:Wa,avatar:Va,avatarPlaceholder:Ya,userName:Qa,userId:Ja,notice:Xa,shareList:Za,btnUnlink:en},q=[{label:"F-Rank",hours:0},{label:"E-Rank",hours:5},{label:"D-Rank",hours:20},{label:"C-Rank",hours:50},{label:"B-Rank",hours:100},{label:"A-Rank",hours:200},{label:"S-Rank",hours:400}],ve={fantasy:"Kamidere",action:"Kamidere",isekai:"Kamidere",magic:"Kamidere","super power":"Megadere",adventure:"Himedere","martial arts":"Himedere",family:"Himedere",comedy:"Bakadere",shounen:"Bakadere",parody:"Bakadere",sports:"Undere",music:"Deredere",romance:"Deredere",ecchi:"Deredere",harem:"Deredere",drama:"Dandere","slice of life":"Dandere",yuri:"Dandere","school life":"Dandere","high school":"Tsundere",school:"Tsundere",military:"Tsundere",shoujo:"Tsundere",seinen:"Kuudere","sci-fi":"Kuudere","science fiction":"Kuudere",mystery:"Kuudere",mecha:"Kuudere",josei:"Kuudere",psychological:"Yandere",horror:"Yandere",thriller:"Sadodere",supernatural:"Dorodere",demons:"Dorodere",game:"Oujidere",historical:"Kanedere"};function tn(t){return ve[(t||"").toLowerCase().trim()]||"Tsundere"}function an(t){const r=new Set;for(const i of t){const c=ve[i.toLowerCase().trim()];c&&r.add(c)}return[...r]}const nn=[{name:"Tsundere",genres:"Romance, School, Shoujo, Military, High School"},{name:"Yandere",genres:"Psychological, Horror"},{name:"Kuudere",genres:"Seinen, Sci-Fi, Mystery, Mecha, Josei"},{name:"Dandere",genres:"Drama, Slice of Life, Yuri, School Life"},{name:"Deredere",genres:"Romance, Ecchi, Harem, Music"},{name:"Bakadere",genres:"Comedy, Shounen, Parody"},{name:"Kamidere",genres:"Fantasy, Action, Isekai, Magic"},{name:"Dorodere",genres:"Supernatural, Demons"},{name:"Himedere",genres:"Adventure, Martial Arts, Family"},{name:"Sadodere",genres:"Thriller"},{name:"Undere",genres:"Sports"},{name:"Megadere",genres:"Super Power"},{name:"Oujidere",genres:"Game"},{name:"Kanedere",genres:"Historical"}];function rn(t){return t>=400?"S-Rank":t>=200?"A-Rank":t>=100?"B-Rank":t>=50?"C-Rank":t>=20?"D-Rank":t>=5?"E-Rank":"F-Rank"}function sn(t){const r=[...q].reverse().findIndex(u=>t>=u.hours),i=r===-1?0:q.length-1-r,c=q[i].label,h=i<q.length-1?q[i+1]:null;if(!h)return{pct:100,current:c,next:"MAX",nextHours:0};const d=q[i].hours,k=q.length-1,m=(t-d)/(h.hours-d);return{pct:Math.min(100,(i+m)/k*100),current:c,next:h.label,nextHours:h.hours-t}}const se="dango_discord_user";function on({workerUrl:t}){const[r,i]=s(()=>{try{const v=localStorage.getItem(se);if(v)return JSON.parse(v)}catch{}try{const b=new URLSearchParams(window.location.search).get("discord_user");if(b)return JSON.parse(b)}catch{}return null}),[c,h]=s(null),[d,k]=s(!1),[m,a]=s(null),[u,f]=s(()=>!r);O(()=>{const v=new URLSearchParams(window.location.search),b=v.get("discord_user");if(b){try{const A=JSON.parse(b);A&&A.id&&(i(A),f(!1),localStorage.setItem(se,JSON.stringify(A)),_.insights.setDiscordUser.mutate({user:A}).catch(()=>{}))}catch{}v.delete("discord_user"),window.history.replaceState(null,"",window.location.pathname+(v.toString()?`?${v.toString()}`:""))}},[]);const p=ae(async()=>{if(r){f(!1);return}try{const v=await _.insights.discordUser.query();v.user&&(i(v.user),localStorage.setItem(se,JSON.stringify(v.user)))}catch{}finally{f(!1)}},[r]),l=ae(async()=>{try{const v=await _.insights.discordSyncStats.query();h(v)}catch{}},[]);O(()=>{p(),l()},[p,l]);const T=()=>{localStorage.removeItem(se),i(null),a(null),_.insights.setDiscordUser.mutate({user:null}).catch(()=>{})},w=async()=>{if(!(!r||!c)){k(!0),a(null);try{const v=await _.insights.discordSyncNow.mutate();v.success?a({type:"success",text:`✅ ${v.message}`}):a({type:"error",text:`❌ ${v.error||v.message||"Sync failed"}`})}catch{a({type:"error",text:"❌ Network error — check your connection"})}finally{k(!1)}}},S=c?Math.round(c.totalSeconds/3600):0,D=rn(S),L=c?tn(c.topGenre):"—",x=c?.dere||(c?.genres?an(c.genres):[L]),{pct:U,next:C,nextHours:R}=sn(S),E=r?.avatar?`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${r.avatar.startsWith("a_")?"gif":"png"}?size=80`:null;return e(te,{children:[e("div",{className:o.card,children:[e("div",{className:o.cardHeader,children:[e("div",{className:o.discordBadge,children:e("svg",{width:"20",height:"15",viewBox:"0 0 71 55",fill:"white","aria-hidden":"true",children:e("path",{d:"M60.1 4.9A58.5 58.5 0 0 0 45.5.3a.22.22 0 0 0-.23.11 40.8 40.8 0 0 0-1.8 3.7 54 54 0 0 0-16.2 0 37.5 37.5 0 0 0-1.83-3.7.23.23 0 0 0-.23-.11A58.3 58.3 0 0 0 10.9 4.9a.2.2 0 0 0-.1.08C1.58 18.73-1 32.23.31 45.55a.24.24 0 0 0 .09.17 58.8 58.8 0 0 0 17.7 8.95.23.23 0 0 0 .25-.08 42 42 0 0 0 3.61-5.88.22.22 0 0 0-.12-.31 38.7 38.7 0 0 1-5.53-2.64.23.23 0 0 1-.02-.37 29 29 0 0 0 1.1-.86.22.22 0 0 1 .23-.03c11.6 5.3 24.14 5.3 35.6 0a.22.22 0 0 1 .23.03c.36.3.73.58 1.1.86a.23.23 0 0 1-.02.37 36.4 36.4 0 0 1-5.53 2.64.22.22 0 0 0-.12.31 47.1 47.1 0 0 0 3.61 5.88.22.22 0 0 0 .25.08 58.6 58.6 0 0 0 17.72-8.95.23.23 0 0 0 .09-.16c1.47-15.27-2.47-28.65-10.46-40.47a.18.18 0 0 0-.09-.09ZM23.73 37.55c-3.49 0-6.37-3.21-6.37-7.15s2.82-7.15 6.37-7.15c3.58 0 6.42 3.24 6.37 7.15 0 3.94-2.82 7.15-6.37 7.15Zm23.54 0c-3.49 0-6.37-3.21-6.37-7.15s2.82-7.15 6.37-7.15c3.58 0 6.42 3.24 6.37 7.15 0 3.94-2.79 7.15-6.37 7.15Z"})})}),e("div",{children:[e("p",{className:o.cardTitle,children:"Discord Account"}),e("p",{className:o.cardSub,children:"Link your Discord to earn community roles"})]})]}),u?e("p",{className:o.notice,children:"Loading…"}):r?e(te,{children:[e("div",{className:o.userRow,children:[E?e("img",{className:o.avatar,src:E,alt:r.username}):e("div",{className:o.avatarPlaceholder,children:"👤"}),e("div",{children:[e("p",{className:o.userName,children:r.username}),e("p",{className:o.userId,children:["ID: ",r.id]})]}),e("button",{className:o.btnUnlink,onClick:T,title:"Disconnect your Discord account",children:"Disconnect"})]}),e("p",{className:o.notice,children:"The following data is shared with the Dango community service to assign roles:"}),e("ul",{className:o.shareList,children:[e("li",{children:"Total watch time (hours)"}),e("li",{children:"Top 3 watched genres"}),e("li",{children:"Discord user ID + username"})]})]}):e(te,{children:[e("p",{className:o.description,children:"Sign in with Discord (OAuth) to link your account. Only your public username and ID are stored — no email or DMs."}),e("div",{className:o.actions,children:[e("button",{className:o.btnPrimary,onClick:()=>{const v=encodeURIComponent(window.location.origin+"/settings?tab=community"),b=`${t}/auth/login?return_to=${v}`;window.location.href=b},children:"Login with Discord"}),e("a",{className:o.btnSecondary,href:"https://discord.gg/2FTSPXCsvn",target:"_blank",rel:"noopener noreferrer",children:"Join Server"})]})]})]}),e("div",{className:o.card,children:[e("div",{className:o.cardHeader,children:e("div",{children:[e("p",{className:o.cardTitle,children:"Your Roles"}),e("p",{className:o.cardSub,children:"Based on your current Dango watch history"})]})}),c?e(te,{children:[e("div",{className:o.statsRow,children:[e("div",{className:o.statBox,children:[e("span",{className:o.statValue,children:[S,"h"]}),e("span",{className:o.statLabel,children:"Watch Time"})]}),e("div",{className:o.statBox,children:[e("span",{className:o.statValue,children:c.topGenre||"—"}),e("span",{className:o.statLabel,children:"Top Genre"})]})]}),e("div",{className:o.rolePreview,children:[e("span",{className:`${o.badge} ${o.badgeRank}`,children:D}),e("span",{className:`${o.badge} ${o.badgeDere}`,children:L})]}),e("div",{className:o.progressSection,children:[e("div",{className:o.progressLabel,children:[e("span",{children:["Progress to ",C]}),e("span",{children:C==="MAX"?"MAX":`${R}h remaining`})]}),e("div",{className:o.progressTrack,children:e("div",{className:o.progressFill,style:{width:`${U}%`}})}),e("div",{className:o.tierList,children:[e("span",{children:"0h (F)"}),e("span",{children:"5h (E)"}),e("span",{children:"20h (D)"}),e("span",{children:"50h (C)"}),e("span",{children:"100h (B)"}),e("span",{children:"200h (A)"}),e("span",{children:"400h (S)"})]})]}),e("div",{className:o.dereSection,children:[e("p",{className:o.sectionHeading,children:"Personality Archetypes"}),e("div",{className:o.dereGrid,children:nn.map(v=>{const b=x.includes(v.name);return e("div",{className:`${o.dereCard} ${b?o.dereCardActive:""}`,children:[e("span",{className:o.dereName,children:v.name}),e("span",{className:o.dereGenre,children:v.genres})]},v.name)})})]}),e("hr",{className:o.divider}),e("div",{className:o.actions,children:[e("button",{className:o.btnPrimary,onClick:w,disabled:!r||d,id:"discord-roles-sync-btn",children:d?"Syncing…":"Sync Roles"}),!r&&e("span",{style:{fontSize:"0.78rem",color:"var(--text-tertiary)",alignSelf:"center"},children:"Login first to sync"})]}),m&&e("p",{className:`${o.statusMsg} ${m.type==="success"?o.statusSuccess:m.type==="error"?o.statusError:o.statusInfo}`,children:m.text})]}):e("p",{className:o.notice,children:"No watch data yet — start watching to earn roles!"})]}),e("div",{className:o.card,children:[e("div",{className:o.cardHeader,children:e("div",{children:[e("p",{className:o.cardTitle,children:"Dango Discord Server"}),e("p",{className:o.cardSub,children:"Community, announcements and support"})]})}),e("div",{className:o.actions,children:e("a",{className:o.btnPrimary,href:"https://discord.gg/2FTSPXCsvn",target:"_blank",rel:"noopener noreferrer",children:"Join the Server"})})]})]})}function cn({variant:t="info",children:r,className:i=""}){return e("div",{className:`alert alert-${t} ${i}`,children:r})}const ln={anime:"Watchlist",manga:"Reading List",tv:"TV Watchlist",asmr:"Listening List"},mn=()=>{const[t,r]=Ie(),i=Le(),{contentType:c}=we(),h=t.get("tab"),[d,k]=s(h&&["general","sync","watchlist","database","community"].includes(h)?h:"general"),[m,a]=s(""),u=V(null),f=V(null),p=V(new Map),[l,T]=s({top:0,height:0,left:0,width:0}),{lowEndMode:w,setLowEndMode:S}=Me(),[D,L]=s(""),[x,U]=s(localStorage.getItem("telemetry_enabled")!=="false"),[C,R]=s(localStorage.getItem("installation_id")||"");O(()=>{_.settings.installationId.query().then(n=>{n.id&&(R(n.id),localStorage.setItem("installation_id",n.id))}).catch(()=>{})},[]),O(()=>{_.discord.rolesConfig.query().then(n=>{n.workerUrl&&L(n.workerUrl)}).catch(()=>{})},[]);const[E,v]=s(Ee),[b,A]=s(!0),{data:M}=ye("discordRPCEnabled"),z=$e(),[N,ne]=s(!0),{data:Y}=ye("discordRPCHideMature"),[he,re]=s(""),[Q,ie]=s(null);O(()=>{_.discord.gatewayStatus.query().then(n=>{ie(n),n.masked&&n.masked!=="none"&&re(n.masked)}).catch(()=>{})},[]),O(()=>{M!==void 0&&A(M==="true"||M===!0||M===null)},[M]),O(()=>{Y!==void 0&&ne(Y==="true"||Y===!0||Y===null)},[Y]);const be=n=>{A(n),z.mutate({key:"discordRPCEnabled",value:String(n)})},_e=n=>{ne(n),z.mutate({key:"discordRPCHideMature",value:String(n)})},ke=n=>{U(n),localStorage.setItem("telemetry_enabled",String(n)),n?Be():ze()},Se=n=>{v(n),localStorage.setItem(Fe,String(n)),window.dispatchEvent(new CustomEvent(He))};me.useEffect(()=>{document.title="Settings - dango"},[]),me.useEffect(()=>{const n=t.get("tab");n&&["general","sync","watchlist","database","community"].includes(n)&&k(n)},[t]);const J=n=>{k(n),r(n==="general"?{}:{tab:n})},X=ae(()=>{const n=p.current.get(d),$=f.current;if(n&&$){const j=$.getBoundingClientRect(),F=n.getBoundingClientRect(),Z=window.matchMedia("(max-width: 900px)").matches;T(Z?{top:F.top-j.top,height:F.height,left:F.left-j.left,width:F.width}:{top:F.top-j.top,height:F.height,left:0,width:0})}},[d]);xe(()=>{X()},[d,X]),O(()=>{const n=()=>X();window.addEventListener("resize",n);let $=!1;return document.fonts?.ready&&document.fonts.ready.then(()=>{$||X()}),()=>{$=!0,window.removeEventListener("resize",n)}},[d,X]);const Ce=()=>{a("Exporting databases...");const n=window.DangoBridge;if(n?.downloadFile){n.downloadFile("/api/backup-db","dango-backup.json"),setTimeout(()=>{a("Databases exported successfully!")},1500);return}const $=document.createElement("a");$.href="/api/backup-db",$.download="dango-backup.json",document.body.appendChild($),$.click(),$.remove(),setTimeout(()=>{a("Databases exported successfully!")},1500)},Ne=async n=>{const $=n.target.files?.[0];if(!$)return;a("Importing databases...");const j=new FormData;j.append("dbfile",$);try{const F=await fetch("/api/restore-db",{method:"POST",body:j}),Z=await F.json();if(F.ok){const ge=Array.isArray(Z.restored)?Z.restored.join(", "):null;a(ge?`Databases imported successfully (${ge})!`:"Database imported successfully!"),setTimeout(()=>window.location.reload(),2e3)}else a(`Import failed: ${Z.error}`)}catch{a("Import failed: An unexpected error occurred.")}finally{n.target.value=""}},Te=()=>{u.current?.click()},Re=()=>{switch(d){case"general":return e("div",{className:g.tabContent,children:e("div",{className:g.sectionCard,children:[e("h3",{children:"Appearance & Preferences"}),e("p",{children:"Configure how titles are displayed and other general preferences."}),e("div",{className:g.settingItem,children:e(qe,{})}),e("div",{className:g.settingItem,style:{marginTop:"1.5rem"},children:e(ha,{})}),e("div",{className:g.settingItem,style:{marginTop:"1.5rem"},children:e("div",{className:g.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(H,{isChecked:w,onChange:n=>S(n.target.checked),id:"low-end-mode"})]})}),e("div",{className:g.settingItem,style:{marginTop:"1.5rem"},children:e("div",{className:g.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(H,{isChecked:E,onChange:n=>Se(n.target.checked),id:"virtual-keyboard-enabled"})]})}),e("div",{className:g.settingItem,style:{marginTop:"1.5rem"},children:e("div",{className:g.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(H,{isChecked:b,onChange:n=>be(n.target.checked),id:"discord-rpc-enabled"})]})}),e("div",{style:{marginTop:"2rem"},children:e(ua,{})}),b&&e("div",{className:g.settingItem,style:{marginTop:"1rem"},children:e("div",{className:g.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(H,{isChecked:N,onChange:n=>_e(n.target.checked),id:"discord-hide-mature"})]})}),e("div",{className:g.settingItem,style:{marginTop:"1.5rem",background:"var(--bg-tertiary)",padding:"1rem",borderRadius:"8px",border:"1px solid var(--border-color)"},children:[e("div",{className:g.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(cn,{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:he,onChange:n=>re(n.target.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(I,{variant:"primary",size:"sm",onClick:async()=>{try{const n=await _.discord.gatewaySave.mutate({token:he});ie({hasToken:!0,masked:n.masked,enabled:!0}),re(n.masked)}catch(n){alert(n instanceof Error?n.message:"Failed to save token")}},children:"Save"}),e(I,{variant:"secondary",size:"sm",onClick:async()=>{await _.discord.gatewayRemove.mutate().catch(()=>{}),re(""),ie({hasToken:!1,masked:null,enabled:!1})},children:"Remove"})]}),Q&&e("p",{style:{marginTop:"0.5rem",fontSize:"0.8rem",color:Q.hasToken?"green":"var(--text-secondary)"},children:["Status:"," ",Q.hasToken?`Token saved (${Q.masked})`:"No token saved",Q.enabled?" - Gateway active":""]}),e(ra,{})]}),e("div",{className:g.settingItem,style:{marginTop:"1.5rem"},children:[e("div",{className:g.settingRow,children:[e("div",{style:{minWidth:0},children:[e("h4",{style:{margin:0,fontSize:"1rem"},children:"Telemetry Tracking"}),e("p",{style:{margin:"0.25rem 0 0",fontSize:"0.85rem",color:"var(--text-secondary)"},children:"Share anonymous installation data to help track active users. Collected: Browser type and OS (e.g. 'Chrome on Windows'), App Version, First Seen/Last Seen timestamps, and timezone (e.g. 'Europe/Berlin'). No other personal information or usage habits are collected."})]}),e(H,{isChecked:x,onChange:n=>ke(n.target.checked),id:"telemetry-enabled"})]}),x&&e("div",{style:{marginTop:"0.75rem",fontSize:"0.8rem",color:"var(--text-secondary)"},children:[e("p",{style:{margin:"0 0 0.5rem 0",fontWeight:"bold"},children:"Data currently being shared:"}),e("div",{style:{background:"var(--bg-tertiary)",padding:"0.5rem",borderRadius:"4px",wordBreak:"break-all",fontFamily:"monospace"},children:[e("p",{style:{margin:"0"},children:[e("strong",{children:"ID:"})," ",C||"Loading..."]}),e("p",{style:{margin:"0"},children:[e("strong",{children:"Version:"})," ",Ge.version]}),e("p",{style:{margin:"0"},children:[e("strong",{children:"Browser:"})," ",Ke()]}),e("p",{style:{margin:"0"},children:[e("strong",{children:"Timezone:"})," ",Intl.DateTimeFormat().resolvedOptions().timeZone]})]})]}),e("div",{style:{marginTop:"1rem"},children:e(I,{variant:"secondary",size:"sm",onClick:()=>i("/map"),children:"View User Map"})})]}),localStorage.getItem("agreedToViewMature")==="true"&&e("div",{className:g.settingItem,style:{marginTop:"1.5rem"},children:e("div",{className:g.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:"You have previously agreed to view 18+ content. Toggle this off to re-enable the blur gate and filtering."})]}),e(H,{isChecked:!0,onChange:n=>{n.target.checked||(localStorage.removeItem("agreedToViewMature"),window.location.reload())},id:"mature-content-enabled"})]})})]})});case"sync":return e("div",{className:g.tabContent,children:[e(aa,{}),e(vt,{}),e(bt,{}),e(ta,{})]});case"watchlist":return e("div",{className:g.tabContent,children:e(xt,{})});case"database":return e("div",{className:g.tabContent,children:[e("div",{className:g.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:g.controls,children:[e(I,{onClick:Ce,children:"Backup Database"}),e(I,{variant:"secondary",onClick:Te,children:"Restore Database"})]}),e("input",{type:"file",ref:u,onChange:Ne,style:{position:"absolute",width:1,height:1,opacity:0,overflow:"hidden"},accept:".json,.db,application/octet-stream"}),m&&e("p",{className:g.status,children:m})]}),e(Vt,{}),e(ea,{})]});case"community":return e("div",{className:g.tabContent,children:D?e(on,{workerUrl:D}):e("div",{className:g.sectionCard,children:[e("h3",{children:"Discord Community Roles"}),e("p",{children:"Discord Roles integration is not configured on this instance."})]})});default:return null}};return e("div",{className:"page-container",children:[e("div",{className:g.settingsHeader,children:[e("h1",{className:g.pageTitle,children:"Settings"}),e("p",{className:g.pageSubtitle,children:"Manage your preferences and data synchronization"})]}),e("div",{className:g.settingsLayout,children:[e("aside",{className:g.sidebar,ref:f,children:[e("div",{className:g.sidebarIndicator,style:{top:l.top,height:l.height,left:l.left,...l.width?{width:l.width}:{}}}),e("button",{ref:n=>{n&&p.current.set("general",n)},className:`${g.sidebarItem} ${d==="general"?g.active:""}`,onClick:()=>J("general"),children:[e(W,{name:"cog"})," ",e("span",{children:"General"})]}),e("button",{ref:n=>{n&&p.current.set("sync",n)},className:`${g.sidebarItem} ${d==="sync"?g.active:""}`,onClick:()=>J("sync"),children:[e(W,{name:"cloud"})," ",e("span",{children:"Synchronization"})]}),e("button",{ref:n=>{n&&p.current.set("watchlist",n)},className:`${g.sidebarItem} ${d==="watchlist"?g.active:""}`,onClick:()=>J("watchlist"),children:[e(W,{name:"list"})," ",e("span",{children:ln[c]})]}),e("button",{ref:n=>{n&&p.current.set("database",n)},className:`${g.sidebarItem} ${d==="database"?g.active:""}`,onClick:()=>J("database"),children:[e(W,{name:"database"})," ",e("span",{children:"Database"})]}),D&&e("button",{ref:n=>{n&&p.current.set("community",n)},className:`${g.sidebarItem} ${d==="community"?g.active:""}`,onClick:()=>J("community"),children:[e(W,{name:"discord"})," ",e("span",{children:"Community"})]})]}),e("main",{className:g.mainContent,children:e("div",{className:g.tabContent,children:Re()},d)})]})]})};export{mn as default};
|