7 lines
345 KiB
HTML
7 lines
345 KiB
HTML
<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><link rel="preconnect" href="https://images.tmdb.org"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover"><meta name="theme-color" content="#101419"><title>Nostr 推荐</title><script>
|
||
window.WEBHOME_PAGE_OPENED_AT=Date.now(),window.fongmiBridge&&document.documentElement.classList.add("fm-native"),function(){for(var t=[window.Element&&Element.prototype,window.Document&&Document.prototype,window.DocumentFragment&&DocumentFragment.prototype],e=0;e<t.length;e++){var n=t[e];n&&(n.replaceChildren||(n.replaceChildren=function(){for(;this.firstChild;)this.removeChild(this.firstChild);for(var t=0;t<arguments.length;t++){var e=arguments[t];this.appendChild(e&&e.nodeType?e:document.createTextNode(String(e)))}}))}window.Element&&!Element.prototype.matches&&(Element.prototype.matches=Element.prototype.msMatchesSelector||Element.prototype.webkitMatchesSelector),window.Element&&!Element.prototype.closest&&(Element.prototype.closest=function(t){for(var e=this;e&&1===e.nodeType;){if(e.matches&&e.matches(t))return e;e=e.parentElement||e.parentNode}return null}),Object.values||(Object.values=function(t){return Object.keys(t||{}).map(function(e){return t[e]})}),Object.entries||(Object.entries=function(t){return Object.keys(t||{}).map(function(e){return[e,t[e]]})}),Array.from||(Array.from=function(t,e,n){var o=[];if(null==t)return o;var r="undefined"!=typeof Symbol&&t[Symbol.iterator],i=0;if("function"==typeof r){for(var a,d=r.call(t);!(a=d.next()).done;)o.push(e?e.call(n,a.value,i++):a.value);return o}for(var c=Number(t.length)||0;i<c;i++)o.push(e?e.call(n,t[i],i):t[i]);return o}),window.NodeList&&!NodeList.prototype.forEach&&(NodeList.prototype.forEach=Array.prototype.forEach),window.HTMLCollection&&!HTMLCollection.prototype.forEach&&(HTMLCollection.prototype.forEach=Array.prototype.forEach),Array.prototype.includes||(Array.prototype.includes=function(t,e){return-1!==this.indexOf(t,e||0)}),Array.prototype.flat||(Array.prototype.flat=function(t){var e=null==t?1:Number(t)||0,n=function(t,o){for(var r=[],i=0;i<t.length;i++){var a=t[i];if(Array.isArray(a)&&o<e)for(var d=n(a,o+1),c=0;c<d.length;c++)r.push(d[c]);else r.push(a)}return r};return n(this,0)}),Array.prototype.flatMap||(Array.prototype.flatMap=function(t,e){return this.map(t,e).flat()}),String.prototype.includes||(String.prototype.includes=function(t,e){return-1!==this.indexOf(t,e||0)}),String.prototype.startsWith||(String.prototype.startsWith=function(t,e){return this.substr(e||0,t.length)===t}),String.prototype.endsWith||(String.prototype.endsWith=function(t,e){var n=String(this),o=null==e?n.length:Math.min(Number(e)||0,n.length);return n.substring(o-t.length,o)===t}),window.Promise&&!Promise.prototype.finally&&(Promise.prototype.finally=function(t){var e=this.constructor;return this.then(function(n){return e.resolve(t()).then(function(){return n})},function(n){return e.resolve(t()).then(function(){throw n})})});var o=function(){if(document&&document.body&&document.documentElement){var t=document.documentElement,e=document.createElement("div"),n=document.createElement("div"),o=function(){var t=document.createElement("div");return t.style.height="1px",t.style.width="1px",t};try{e.style.cssText="position:absolute;left:-9999px;top:-9999px;display:flex;flex-direction:column;gap:1px;visibility:hidden;",e.appendChild(o()),e.appendChild(o()),n.style.cssText="position:absolute;left:-9999px;top:-9999px;display:grid;grid-template-columns:1px;gap:1px;visibility:hidden;",n.appendChild(o()),n.appendChild(o()),document.body.appendChild(e),document.body.appendChild(n),(e.scrollHeight<3||n.scrollHeight<3)&&t.classList.add("no-layout-gap")}catch(e){t.classList.add("no-layout-gap")}try{e.parentNode&&e.parentNode.removeChild(e),n.parentNode&&n.parentNode.removeChild(n)}catch(t){}}};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",o):o(),function(){if(document&&document.documentElement&&window.CSS&&CSS.supports)try{CSS.supports("width","min(10px, 20px)")&&CSS.supports("width","clamp(10px, 2vw, 20px)")||document.documentElement.classList.add("no-css-functions")}catch(t){document.documentElement.classList.add("no-css-functions")}else document.documentElement.classList.add("no-css-functions")}(),function(){if(document&&document.documentElement){var t=document.documentElement;if(window.CSS&&CSS.supports){try{if(!CSS.supports("aspect-ratio","2 / 3"))return void t.classList.add("no-aspect-ratio")}catch(e){return void t.classList.add("no-aspect-ratio")}var e=function(){if(document.body){var e=document.createElement("div");try{e.style.cssText="position:absolute;left:-9999px;top:-9999px;width:20px;aspect-ratio:2/1;visibility:hidden;",document.body.appendChild(e);var n=e.getBoundingClientRect?e.getBoundingClientRect().height:e.offsetHeight;(n<8||n>12)&&t.classList.add("no-aspect-ratio")}catch(e){t.classList.add("no-aspect-ratio")}try{e.parentNode&&e.parentNode.removeChild(e)}catch(t){}}};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",e):e()}else t.classList.add("no-aspect-ratio")}}()}()
|
||
</script><style>
|
||
:root{color-scheme:dark;--bg:transparent;--panel-rgb:76,88,98;--panel:rgba(var(--panel-rgb), .58);--panel-soft:rgba(var(--panel-rgb), .44);--panel-strong:rgba(var(--panel-rgb), .82);--panel-2:rgba(var(--panel-rgb), .62);--text:#f4f7fb;--muted:rgba(226, 234, 242, .72);--line:rgba(255, 255, 255, .2);--line-strong:rgba(255, 255, 255, .34);--control:rgba(34, 43, 51, .42);--control-active:rgba(48, 61, 70, .58);--accent:rgba(245, 249, 252, .86);--accent-2:rgba(221, 232, 241, .66);--focus-line:rgba(168, 218, 255, .72);--focus-line-soft:rgba(168, 218, 255, .42);--focus-glow:rgba(96, 165, 250, .24);--focus-surface:rgba(255, 255, 255, .12);--ok:#9fd8ad;--danger:#f09d9d;--shadow:0 16px 42px rgba(0, 0, 0, .24);--radius:8px;--fm-web-height:100vh;--fm-safe-top:0px;--fm-safe-right:0px;--fm-safe-bottom:20px;--fm-safe-left:0px;--safe-top:max(var(--fm-safe-top, 0px), env(safe-area-inset-top, 0px));--safe-right:max(var(--fm-safe-right, 0px), env(safe-area-inset-right, 0px));--safe-bottom:max(var(--fm-safe-bottom, 0px), env(safe-area-inset-bottom, 0px));--safe-left:max(var(--fm-safe-left, 0px), env(safe-area-inset-left, 0px));--active-safe-top:0px;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"PingFang SC","Microsoft YaHei",sans-serif}html.safe-top-active{--active-safe-top:var(--safe-top)}@supports (height:100dvh){:root{--fm-web-height:100dvh}}*{box-sizing:border-box}body,html{margin:0;width:100%;max-width:100%;min-height:var(--fm-web-height);background:0 0;color:var(--text);overflow-x:hidden}html:not(.fm-native),html:not(.fm-native) body{background-color:#303840;background-image:linear-gradient(45deg,rgba(255,255,255,.07) 25%,transparent 25%),linear-gradient(-45deg,rgba(255,255,255,.07) 25%,transparent 25%),linear-gradient(45deg,transparent 75%,rgba(255,255,255,.07) 75%),linear-gradient(-45deg,transparent 75%,rgba(255,255,255,.07) 75%);background-position:0 0,0 16px,16px -16px,-16px 0;background-size:32px 32px}html.fm-native,html.fm-native body{background:0 0}body{overflow-x:hidden;letter-spacing:0;position:relative;overscroll-behavior-x:none}button,input,select,textarea{font:inherit;color:inherit}button{border:0;cursor:pointer;touch-action:manipulation;margin:0;padding:0;appearance:none;-webkit-appearance:none;background:0 0;text-align:inherit}img{display:block;max-width:100%;background:0 0}.app{width:100%;max-width:100%;min-width:0;min-height:var(--fm-web-height);overflow-x:hidden;padding:max(12px,var(--active-safe-top)) 14px calc(18px + var(--safe-bottom));background:0 0}body.detail-active .app{visibility:hidden;pointer-events:none}body.detail-active .back-top{opacity:0;visibility:hidden;pointer-events:none}body.episode-active #detailSheet{visibility:hidden;pointer-events:none}.mobile-detail-back{display:none;position:fixed;top:max(12px,var(--active-safe-top));left:12px;z-index:90;width:42px;height:42px;place-items:center;border-radius:999px;color:rgba(255,255,255,.92);background:rgba(12,18,24,.18);border:1px solid rgba(255,255,255,.16);box-shadow:0 8px 22px rgba(0,0,0,.18);backdrop-filter:blur(8px) saturate(1.05);transition:opacity .16s ease,visibility .16s ease,transform .16s ease}.mobile-detail-back .icon{width:21px;height:21px}.mobile-detail-back:focus{z-index:95;background:rgba(16,24,32,.34)}.mobile-detail-back.is-hidden{opacity:0;visibility:hidden;pointer-events:none;transform:translateY(-8px)}html.native-phone-app body.detail-active .mobile-detail-back,html.native-phone-app body.episode-active .image-viewer .mobile-detail-back{display:grid}.icon-btn{width:42px;height:42px;display:grid;place-items:center;border-radius:var(--radius);background:var(--control);border:1px solid var(--line);color:var(--text);text-shadow:0 1px 2px rgba(0,0,0,.38);backdrop-filter:blur(12px) saturate(1.05)}.icon{width:19px;height:19px;fill:none;stroke:currentColor;stroke-width:2.2;stroke-linecap:round;stroke-linejoin:round}.pill{width:fit-content;color:var(--text);background:var(--control-active);border:1px solid var(--line);padding:5px 9px;border-radius:999px;font-size:12px;font-weight:800;text-shadow:0 1px 2px rgba(0,0,0,.38)}.actions{display:flex;gap:10px;flex-wrap:wrap}.btn{min-height:42px;display:inline-flex;align-items:center;justify-content:center;gap:7px;padding:0 14px;border-radius:var(--radius);background:var(--control);border:1px solid var(--line);color:var(--text);font-weight:760;text-decoration:none;text-shadow:0 1px 2px rgba(0,0,0,.38);backdrop-filter:blur(12px) saturate(1.05)}.btn.primary{color:var(--text);background:var(--control-active);border-color:var(--line-strong)}.btn.blue{background:var(--control-active);color:var(--text);border-color:var(--line-strong)}.btn.danger{color:#fff0f0;background:rgba(240,157,157,.2);border-color:rgba(255,220,220,.24)}.btn.link{min-height:30px;padding:0;border:0;background:0 0;color:rgba(184,226,255,.92);font-size:13px;font-weight:760;text-shadow:0 1px 2px rgba(0,0,0,.38);backdrop-filter:none}.search{width:100%;min-width:0;display:flex;align-items:stretch;display:grid;grid-template-columns:minmax(0,1fr) auto auto;gap:10px;margin:14px 0 8px;position:relative;z-index:20}.search .field{flex:1 1 auto;min-width:0}.search .btn,.search .icon-btn{flex:0 0 auto;margin-left:10px}.search .icon-btn{width:44px;height:auto;min-height:44px;align-self:stretch}@supports (display:grid){.search .btn,.search .icon-btn{margin-left:0}}.search.suggesting{z-index:95}html.tv-mode .search{grid-template-columns:minmax(0,1fr) auto auto auto;align-items:stretch}html.tv-mode .search>.connection-dock{align-self:stretch;margin-left:0;border:0;background:0 0;box-shadow:none}html.tv-mode .search>.connection-dock .connection-toggle{min-height:44px;height:100%;border-radius:var(--radius);border:1px solid var(--line);background:var(--control)}html.tv-mode .search>.connection-dock .connection-toggle:focus{transform:translateY(-1px);background:rgba(70,85,96,.72);border-color:var(--focus-line);box-shadow:none}.suggest-panel{position:absolute;left:0;right:0;top:calc(100% + 8px);z-index:1;display:none;max-height:460px;max-height:54vh;max-height:min(54vh,460px);overflow-y:auto;padding:6px;border-radius:var(--radius);border:1px solid var(--line);background:rgba(22,28,34,.94);box-shadow:var(--shadow);backdrop-filter:blur(14px) saturate(1.08);scrollbar-width:none}.suggest-panel.open{display:block;display:grid;gap:6px}.suggest-panel::-webkit-scrollbar{display:none}.suggest-item{min-width:0;display:flex;justify-content:space-between;gap:8px;display:grid;grid-template-columns:minmax(0,1fr) auto;gap:8px;align-items:center;min-height:42px;padding:8px 10px;border-radius:var(--radius);color:var(--text);text-align:left;background:rgba(42,52,60,.56);border:1px solid rgba(255,255,255,.12)}.suggest-item b{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:14px;line-height:1.25}.suggest-item span{color:var(--muted);font-size:12px;white-space:nowrap}.field{width:100%;min-height:44px;border-radius:var(--radius);border:1px solid var(--line);background:var(--control);color:var(--text);padding:0 12px;outline:0;text-shadow:0 1px 2px rgba(0,0,0,.35);backdrop-filter:blur(12px) saturate(1.05)}textarea.field{min-height:74px;padding:10px 12px;resize:vertical}.field::placeholder{color:rgba(226,234,242,.5)}.chips{width:100%;max-width:100%;min-width:0;display:flex;gap:8px;overflow-x:auto;padding:3px 0 2px;overscroll-behavior-x:contain}.chips::-webkit-scrollbar,.rail::-webkit-scrollbar{display:none}.chip{flex:0 0 auto;min-height:36px;padding:0 12px;border-radius:999px;background:var(--control);border:1px solid var(--line);color:var(--text);font-weight:700;font-size:13px;text-shadow:0 1px 2px rgba(0,0,0,.38);backdrop-filter:blur(12px) saturate(1.05)}.chip.active{background:var(--control-active);color:var(--text);border-color:var(--line-strong)}.section{width:100%;max-width:100%;min-width:0;margin-top:24px;overflow:hidden}#recommendSection{overflow:visible}.section-head{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:10px;position:relative;overflow:visible}.section h3{margin:0;font-size:18px;line-height:1.2}.section small{color:var(--muted);font-size:12px;white-space:nowrap}.section-actions{min-width:0;display:flex;align-items:center;gap:8px}.mini-icon-btn{width:32px;height:32px;display:grid;place-items:center;border-radius:var(--radius);background:var(--control);border:1px solid var(--line);color:var(--text);backdrop-filter:blur(12px) saturate(1.05)}.mini-icon-btn .icon{width:16px;height:16px}.stack{display:block;gap:18px;min-width:0}.list-block{width:100%;max-width:100%;min-width:0;overflow:hidden;margin-top:18px}.list-block:first-child{margin-top:0}html.tv-mode .list-block{overflow:visible}.subsection-head{min-width:0;display:flex;align-items:baseline;justify-content:space-between;gap:12px;margin-bottom:9px}.subsection-head h4{margin:0;font-size:15px;line-height:1.2}.subsection-head span{color:var(--muted);font-size:12px;white-space:nowrap}.rail{width:100%;max-width:100%;min-width:0;display:flex;gap:12px;overflow-x:auto;overflow-y:hidden;overscroll-behavior-x:contain;scroll-snap-type:none;-webkit-overflow-scrolling:touch;scrollbar-width:none;touch-action:pan-x pan-y;padding:2px 0 5px}html.tv-mode .rail{overflow-y:visible;padding:10px 5px 14px}.media-grid{width:100%;max-width:100%;min-width:0;display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px}html.tv-mode .media-grid{overflow:visible;padding:10px 5px 14px}.list-panel[hidden]{display:none!important}.infinite-sentinel{width:100%;height:1px;pointer-events:none;overflow-anchor:none}.card{flex:0 0 142px;min-width:0;max-width:172px;position:relative;border-radius:var(--radius);background:var(--panel-soft);border:1px solid var(--line);overflow:hidden;padding:0;text-align:left;color:var(--text);scroll-snap-align:start;backdrop-filter:blur(10px) saturate(1.05)}.media-grid .card{width:100%;max-width:none;flex:none;contain:layout style}.poster{aspect-ratio:2/3;width:100%;object-fit:cover}.poster-wrap{position:relative;width:calc(100% + 2px);max-width:calc(100% + 2px);margin:-1px -1px 0;overflow:hidden}.poster-wrap .poster{width:100%;max-width:100%}.card>.poster{width:calc(100% + 2px);max-width:calc(100% + 2px);margin:-1px -1px 0}.card-body{padding:10px;background:var(--panel);border-top:1px solid var(--line)}.card-title{font-size:12px;font-weight:760;line-height:1.2;min-height:15px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;text-shadow:0 1px 2px rgba(0,0,0,.42)}.rating-badge{position:absolute;right:7px;top:7px;min-width:34px;height:24px;display:grid;place-items:center;border-radius:999px;background:rgba(6,9,12,.48);border:1px solid rgba(255,255,255,.18);color:rgba(255,255,255,.94);font-size:12px;font-weight:800;line-height:1;backdrop-filter:blur(8px)}.card-meta{margin-top:6px;color:var(--muted);font-size:12px;line-height:1.3;text-shadow:0 1px 2px rgba(0,0,0,.38)}.card-meta:empty{display:none}.card.recent-card{background:rgba(var(--panel-rgb),.26)}.block-select-hint{display:none;margin:6px 0 10px;color:rgba(244,247,251,.78);font-size:13px;line-height:1.35}body.block-select-active .block-select-hint{display:block}body.block-select-active #recommendRail .card{outline:1px solid rgba(255,255,255,.18);outline-offset:-1px}body.block-select-active #recommendRail .card::after{content:"按 OK 屏蔽";position:absolute;top:7px;left:7px;z-index:5;min-height:24px;display:inline-flex;align-items:center;padding:0 8px;border-radius:999px;background:rgba(6,9,12,.68);border:1px solid rgba(255,255,255,.18);color:rgba(255,255,255,.9);font-size:11px;font-weight:800;line-height:1;text-shadow:0 1px 2px rgba(0,0,0,.5)}body.block-select-active #recommendRail .card.blocked{opacity:.62;border-color:rgba(240,157,157,.55)}body.block-select-active #recommendRail .card.blocked::after{content:"已屏蔽";background:rgba(132,38,38,.78);border-color:rgba(255,210,210,.24);color:rgba(255,240,240,.95)}body.block-select-active #recommendRail .card.blocked img{filter:grayscale(.3) brightness(.7)}.card.recent-card>.poster{width:calc(100% + 2px);max-width:calc(100% + 2px);margin:-1px}.recent-card .card-body{position:absolute;left:0;right:0;bottom:0;z-index:2;padding:28px 9px 9px;border-top:0;background:linear-gradient(180deg,rgba(0,0,0,0),rgba(5,7,9,.72) 46%,rgba(5,7,9,.88))}.recent-badge,.recent-card .card-meta,.recent-card .card-title{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.recent-card .card-title{min-height:0;font-size:12px;line-height:1.2}.recent-card .card-meta{max-width:100%;margin-top:4px;color:rgba(238,244,250,.74);font-size:11px;line-height:1.2}.recent-badge{position:absolute;top:7px;right:7px;z-index:2;max-width:calc(100% - 14px);min-height:22px;display:inline-flex;align-items:center;padding:0 7px;border-radius:999px;background:rgba(6,9,12,.46);border:1px solid rgba(255,255,255,.16);color:rgba(255,255,255,.9);font-size:11px;font-weight:780;line-height:1;text-shadow:0 1px 2px rgba(0,0,0,.48);backdrop-filter:blur(8px)}.recent-progress{position:absolute;left:0;right:0;bottom:0;z-index:3;height:3px;background:rgba(255,255,255,.2)}.recent-progress span{display:block;width:var(--recent-progress,0%);height:100%;background:rgba(255,255,255,.82)}.card-people{position:absolute;right:7px;bottom:7px;z-index:2;min-height:22px;display:inline-flex;align-items:center;padding:0 7px;border-radius:999px;background:rgba(6,9,12,.48);border:1px solid rgba(255,255,255,.16);color:rgba(255,255,255,.88);font-size:11px;font-weight:760;line-height:1;text-shadow:0 1px 2px rgba(0,0,0,.46);pointer-events:none}.person-info{display:block;padding:12px;border-radius:var(--radius);background:var(--panel-soft);border:1px solid var(--line);backdrop-filter:blur(10px) saturate(1.05)}.person-info-body{min-width:0}.person-info-body p{margin:8px 0 0;color:var(--muted);font-size:12px;line-height:1.45}.live-entry-card{width:100%;min-height:96px;display:grid;grid-template-columns:auto minmax(0,1fr) auto;align-items:center;gap:10px;padding:12px;border-radius:var(--radius);background:linear-gradient(135deg,rgba(var(--panel-rgb),.72),rgba(34,43,51,.36));border:1px solid var(--line);color:var(--text);text-align:left;box-shadow:0 12px 30px rgba(0,0,0,.14);backdrop-filter:blur(12px) saturate(1.05)}.live-icon{width:42px;height:42px;display:grid;place-items:center;border-radius:var(--radius);background:rgba(255,255,255,.1);border:1px solid rgba(255,255,255,.18)}.live-icon .icon{width:21px;height:21px}.live-copy{min-width:0}.live-copy h5{margin:0;font-size:16px;line-height:1.2}.live-copy p{margin:5px 0 0;color:var(--muted);font-size:12px;line-height:1.35}.live-tags{display:flex;flex-wrap:wrap;gap:5px;margin-top:8px}.live-tag{min-height:21px;display:inline-flex;align-items:center;padding:0 7px;border-radius:999px;background:rgba(255,255,255,.08);border:1px solid rgba(255,255,255,.14);color:rgba(238,244,250,.86);font-size:11px;font-weight:720;line-height:1}.live-action{min-height:32px;display:inline-flex;align-items:center;justify-content:center;padding:0 10px;border-radius:var(--radius);background:rgba(255,255,255,.12);border:1px solid rgba(255,255,255,.2);font-size:12px;font-weight:800;white-space:nowrap}.empty{min-height:92px;display:grid;place-items:center;padding:14px;border-radius:var(--radius);border:1px dashed rgba(255,255,255,.18);color:var(--muted);background:rgba(255,255,255,.03);font-size:13px;text-align:center}.grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px}.metric{flex:0 0 210px;max-width:260px;min-height:82px;padding:12px;border-radius:var(--radius);background:var(--panel);border:1px solid var(--line)}.metric b{display:block;font-size:20px;line-height:1.1}.metric span{display:block;margin-top:8px;color:var(--muted);font-size:12px;line-height:1.35}.sheet{--sheet-x:14px;display:none;position:fixed;top:0;right:0;bottom:0;left:0;inset:0;z-index:60;width:100%;max-width:100%;min-width:0;height:100vh;min-height:var(--fm-web-height);background:0 0;backdrop-filter:none;overflow-y:auto;overflow-x:hidden;padding:max(16px,var(--active-safe-top)) var(--sheet-x) calc(22px + var(--safe-bottom))}.sheet.active{display:block}.detail-cover{position:relative;width:100%;max-width:100%;height:56.25vw;min-height:180px;max-height:42vh;aspect-ratio:16/9;border-radius:var(--radius);overflow:hidden;background:0 0;margin:14px 0}.detail-cover.loading::before{content:"";position:absolute;top:0;right:0;bottom:0;left:0;inset:0;background:linear-gradient(110deg,rgba(255,255,255,.04),rgba(255,255,255,.11),rgba(255,255,255,.04));background-size:220% 100%;animation:cover-loading 1.25s ease-in-out infinite}@keyframes cover-loading{0%{background-position:120% 0}100%{background-position:-120% 0}}.detail-cover img{position:absolute;top:0;right:0;bottom:0;left:0;inset:0;width:100%;height:100%;object-fit:contain;object-position:left center;opacity:0;transition:opacity .18s ease}.detail-cover img.active{opacity:1}.detail-cover.poster-mode{background:0 0!important;background-image:none!important}.detail-cover.poster-mode::before{display:none!important}.detail-cover.poster-mode::after{display:none!important}.detail-cover.poster-mode img{top:0;right:0;bottom:0;left:0;inset:0;width:100%;height:100%;object-fit:cover!important;object-position:center 24%;z-index:1}@media (max-width:719px){html:not(.tv-mode) #imageViewer.episode-mode #closeImageBtn{display:none}html:not(.tv-mode) #detailSheet:not(.detail-large) .detail-cover{border-radius:14px;overflow:hidden;isolation:isolate}html:not(.tv-mode) #detailSheet:not(.detail-large) .detail-cover img,html:not(.tv-mode) #detailSheet:not(.detail-large) .detail-cover::before{border-radius:inherit}html:not(.tv-mode) .detail-cover.has-multiple{touch-action:pan-y}}html.tv-mode .detail-cover{width:min(calc(100vw - 68px),calc(clamp(360px,58vh,680px) * 16 / 9));max-width:none;height:auto;min-height:180px;max-height:none;aspect-ratio:16/9;margin-top:0}@media (max-height:760px){html.tv-mode .detail-cover{width:min(calc(100vw - 68px),calc(clamp(320px,56vh,430px) * 16 / 9))}}.detail-info{padding:0 2px 12px}.detail-title-row{display:flex;align-items:baseline;gap:8px;flex-wrap:wrap;margin:0 0 8px}.detail-info h2{margin:0 0 8px;font-size:clamp(22px, 6vw, 32px);line-height:1.12}.detail-title-row h2{margin:0}.detail-title-logo{display:none;max-width:100%;width:auto;height:auto;object-fit:contain}.detail-title-meta{display:inline-flex;align-items:baseline;gap:6px;color:rgba(244,247,251,.9);font-size:13px;font-weight:720;line-height:1.2;text-shadow:0 1px 2px rgba(0,0,0,.38)}.detail-title-meta .score{color:rgba(255,218,128,.95);font-weight:820}.detail-title-meta .sep{color:rgba(244,247,251,.42);font-weight:600}.detail-info p{margin:0;color:rgba(244,247,251,.82);line-height:1.5;font-size:14px}.detail-info p.clamped{max-height:var(--detail-text-max,none);overflow:hidden}#detailMoreBtn{margin-top:2px;display:none}.detail-meta{display:flex;gap:8px;flex-wrap:wrap;margin:8px 0 14px}.meta-pill{padding:5px 8px;border-radius:999px;color:var(--muted);background:var(--panel);border:1px solid var(--line);font-size:12px;line-height:1.2}.meta-pill.strong{color:var(--text);border-color:var(--line-strong);background:var(--control-active);font-weight:760}.detail-block{margin-top:18px}.detail-block h3{margin:0 0 10px;font-size:17px;line-height:1.2}.episode-card{flex:0 0 230px;max-width:260px;min-height:138px;padding:11px;border-radius:var(--radius);background:var(--panel);border:1px solid var(--line);color:var(--text);text-align:left;scroll-snap-align:start;contain:layout style}.episode-card.has-still{padding:0;overflow:hidden}.episode-card.has-still .episode-body{padding:8px 9px 9px}.episode-still-wrap{width:calc(100% + 2px);max-width:calc(100% + 2px);display:block;margin:-1px -1px 0;aspect-ratio:16/9;overflow:hidden;line-height:0;background:0 0}.episode-still{width:100%;max-width:none;height:100%;margin:0;aspect-ratio:16/9;object-fit:cover;object-position:center top}.episode-card b,.person-card b{display:block;font-size:14px;line-height:1.18}.person-card b{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.episode-card span,.person-card span{display:block;margin-top:3px;color:var(--muted);font-size:12px;line-height:1.22}#detailSheet .episode-card .episode-badge{display:none}.person-card span{display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;word-break:break-word}.episode-card p{margin:3px 0 0;color:rgba(244,247,251,.78);font-size:12px;line-height:1.26;display:-webkit-box;-webkit-line-clamp:4;-webkit-box-orient:vertical;overflow:hidden}.person-card{flex:0 0 116px;max-width:128px;height:244px;display:flex;flex-direction:column;border-radius:var(--radius);background:var(--panel);border:1px solid var(--line);color:var(--text);overflow:hidden;padding:0;text-align:left;scroll-snap-align:start;contain:layout style}.person-card img{width:calc(100% + 2px);max-width:calc(100% + 2px);height:176px;flex:0 0 176px;margin:-1px -1px 0;object-fit:cover;object-position:center top;background:rgba(255,255,255,.04)}.person-card div{flex:1 1 auto;min-height:0;min-width:0;padding:8px 9px 9px;overflow:hidden}#detailSheet.detail-large{--detail-side-pad:clamp(42px, 5.4vw, 80px);--detail-top-pad:clamp(46px, 7.2vh, 82px);background:#06111b;padding:var(--detail-top-pad) var(--detail-side-pad) calc(34px + var(--safe-bottom));overflow-y:auto;overflow-x:hidden}#detailSheet.detail-large::after,#detailSheet.detail-large::before{content:"";position:fixed;top:0;right:0;bottom:0;left:0;inset:0;pointer-events:none;z-index:0}#detailSheet.detail-large::before{background-image:var(--detail-hero-bg,none);background-size:cover;background-position:center top;filter:brightness(1) saturate(1.05);opacity:1}#detailSheet.detail-large::after{background:linear-gradient(90deg,rgba(6,17,27,.9) 0,rgba(6,17,27,.72) 32%,rgba(6,17,27,.22) 66%,rgba(6,17,27,.1) 100%),linear-gradient(180deg,rgba(6,17,27,.08) 0,rgba(6,17,27,.2) 48%,#06111b 100%)}#detailSheet.detail-large>*{position:relative;z-index:2}#detailSheet.detail-large .detail-cover{display:none!important}#detailSheet.detail-large .detail-cover[data-cover-mode=landscape]{-webkit-mask-image:linear-gradient(90deg,transparent 0%,rgba(0,0,0,.28) 3%,rgba(0,0,0,.76) 7%,#000 12%,#000 100%);mask-image:linear-gradient(90deg,transparent 0%,rgba(0,0,0,.28) 3%,rgba(0,0,0,.76) 7%,#000 12%,#000 100%);-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat;-webkit-mask-size:100% 100%;mask-size:100% 100%}#detailSheet.detail-large .detail-cover[data-cover-mode=landscape]::before{content:"";position:absolute;top:0;bottom:0;left:0;z-index:1;width:16%;pointer-events:none;background-image:var(--detail-cover-bg,none);background-size:cover;background-position:center top;opacity:.16;filter:blur(8px) saturate(.92);transform:scale(1.04);transform-origin:left center;-webkit-mask-image:linear-gradient(90deg,transparent 0%,#000 36%,rgba(0,0,0,.66) 68%,transparent 100%);mask-image:linear-gradient(90deg,transparent 0%,#000 36%,rgba(0,0,0,.66) 68%,transparent 100%)}#detailSheet.detail-large .detail-cover::after{content:"";position:absolute;top:0;right:0;bottom:0;left:0;inset:0;z-index:2;background:linear-gradient(90deg,#06111b 0,rgba(6,17,27,.78) 5%,rgba(6,17,27,.34) 13%,rgba(6,17,27,.1) 24%,rgba(6,17,27,.1) 100%),linear-gradient(180deg,rgba(6,17,27,.1) 0,rgba(6,17,27,.06) 56%,#06111b 100%)}#detailSheet.detail-large .detail-cover.poster-mode::after{display:block!important}#detailSheet.detail-large .detail-cover img{object-fit:cover!important;object-position:center top;filter:saturate(.92) contrast(.98) brightness(.76)}#detailSheet.detail-large .detail-cover[data-cover-mode=landscape] img{transform:translateZ(0) scale(1.012);transform-origin:center top}#detailSheet.detail-large .detail-cover.poster-mode img{object-fit:cover!important;object-position:center 18%}#detailSheet.detail-large .detail-block,#detailSheet.detail-large .detail-info,#detailSheet.detail-large>.actions{max-width:min(760px,54vw)}#detailSheet.detail-large .detail-info{min-height:0;padding:0}#detailSheet.detail-large .detail-title-row{gap:20px;align-items:baseline;margin:0 0 22px}#detailSheet.detail-large .detail-info h2{font-size:clamp(38px, 5.2vw, 64px);line-height:1.04;font-weight:850;letter-spacing:0;text-shadow:0 3px 16px rgba(0,0,0,.48)}#detailSheet.detail-large .detail-title-meta{gap:0;font-size:clamp(20px, 2.3vw, 28px);line-height:1;font-weight:820;color:rgba(244,188,129,.96)}#detailSheet.detail-large .detail-title-meta .score{color:rgba(244,188,129,.96)}#detailSheet.detail-large .detail-title-meta .sep{display:none}#detailSheet.detail-large .detail-meta{gap:10px;margin:0 0 18px}#detailSheet.detail-large .meta-pill{min-height:34px;display:inline-flex;align-items:center;border-radius:6px;padding:0 12px;color:rgba(245,249,252,.92);background:rgba(65,82,96,.52);border-color:rgba(255,255,255,.14);font-size:17px;font-weight:620;backdrop-filter:none}#detailSheet.detail-large .detail-info p{max-width:min(620px,42vw);color:rgba(232,239,247,.82);font-size:clamp(15px, 1.45vw, 18px);line-height:1.72;text-shadow:0 2px 10px rgba(0,0,0,.42)}#detailSheet.detail-large #detailMoreBtn{min-height:30px;margin:4px 0 0;padding:0;border:0;background:0 0;color:rgba(129,190,255,.92);font-size:15px;box-shadow:none}#detailSheet.detail-large.episode-preview-active .detail-info{max-width:calc(100vw - var(--detail-side-pad) - var(--detail-side-pad));height:var(--episode-preview-info-height,auto);overflow:visible}#detailSheet.detail-large.episode-preview-active .detail-title-row{flex-wrap:nowrap;max-width:calc(100vw - var(--detail-side-pad) - var(--detail-side-pad));height:64px;height:clamp(50px,5.8vw,74px);overflow:hidden;text-shadow:none!important;box-shadow:none!important;filter:none!important;backdrop-filter:none!important}#detailSheet.detail-large.episode-preview-active .detail-info h2{flex:0 1 auto;min-width:0;max-width:min(760px,54vw);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;text-shadow:none!important;box-shadow:none!important;filter:none!important;backdrop-filter:none!important}#detailSheet.detail-large.episode-preview-active .detail-title-meta{display:none;flex:0 0 auto;white-space:nowrap;text-shadow:none!important;box-shadow:none!important;filter:none!important;backdrop-filter:none!important}#detailSheet.detail-large.episode-preview-active>.actions{visibility:hidden;pointer-events:none}#detailSheet.detail-large.episode-preview-active .detail-info p#detailText{max-width:min(620px,42vw);outline:0!important;border-color:transparent!important;box-shadow:none!important;pointer-events:none;user-select:none;-webkit-user-select:none;-webkit-tap-highlight-color:transparent}#detailSheet.detail-large.episode-preview-active .detail-info p#detailText.clamped[data-more-label]{position:relative;padding-right:64px}#detailSheet.detail-large.episode-preview-active .detail-info p#detailText.clamped[data-more-label]::after{content:attr(data-more-label);position:absolute;right:0;bottom:0;min-width:0;color:rgba(129,190,255,.96);font-weight:780;text-align:right;background:0 0!important;background-color:transparent!important;background-image:none!important;box-shadow:none!important;text-shadow:none!important;filter:none!important;backdrop-filter:none!important}#detailSheet.detail-large.episode-preview-active #detailMoreBtn{background:0 0!important;background-color:transparent!important;background-image:none!important;box-shadow:none!important;text-shadow:none!important;filter:none!important;backdrop-filter:none!important;display:none!important}#detailSheet.detail-large.episode-preview-active .detail-info p#detailText.clamped{max-height:var(--episode-preview-text-max,7.6em);overflow:hidden}#detailSheet.detail-large.episode-preview-expanded .detail-info p#detailText{visibility:visible;max-width:none;width:calc(100vw - var(--detail-side-pad) - var(--detail-side-pad));max-height:none;overflow:visible}#detailSheet.detail-large.episode-preview-expanded .detail-info h2{max-width:calc(100vw - var(--detail-side-pad) - var(--detail-side-pad))}#detailSheet.detail-large.episode-preview-expanded #seasonBlock>h3,#detailSheet.detail-large.episode-preview-expanded #seasonTabs{visibility:hidden;pointer-events:none}html.legacy-detail-layout #detailSheet.detail-large.episode-preview-active .detail-info,html.legacy-detail-layout #detailSheet.detail-large.episode-preview-active .detail-title-row,html.no-css-functions #detailSheet.detail-large.episode-preview-active .detail-info,html.no-css-functions #detailSheet.detail-large.episode-preview-active .detail-title-row{max-width:1152px}html.legacy-detail-layout #detailSheet.detail-large .detail-info p,html.legacy-detail-layout #detailSheet.detail-large.episode-preview-active .detail-info p#detailText,html.no-css-functions #detailSheet.detail-large .detail-info p,html.no-css-functions #detailSheet.detail-large.episode-preview-active .detail-info p#detailText{max-width:560px}html.legacy-detail-layout #detailSheet.detail-large.episode-preview-active .detail-info,html.no-css-functions #detailSheet.detail-large.episode-preview-active .detail-info{height:220px;max-height:220px}html.legacy-detail-layout #detailSheet.detail-large.episode-preview-active .detail-title-row,html.no-css-functions #detailSheet.detail-large.episode-preview-active .detail-title-row{height:64px}html.legacy-detail-layout #detailSheet.detail-large.episode-preview-active .detail-info p#detailText.clamped,html.no-css-functions #detailSheet.detail-large.episode-preview-active .detail-info p#detailText.clamped{max-height:116px}html.legacy-detail-layout #detailSheet.detail-large.episode-preview-expanded .detail-info p#detailText,html.no-css-functions #detailSheet.detail-large.episode-preview-expanded .detail-info p#detailText{width:1152px}#detailSheet.detail-large>.actions{gap:16px;margin-top:24px}#detailSheet.detail-large>.actions .btn{min-width:144px;min-height:58px;border-radius:8px;padding:0 26px;color:rgba(246,250,253,.92);background:rgba(54,68,80,.56);border-color:rgba(255,255,255,.12);box-shadow:none;font-size:clamp(18px, 1.8vw, 22px);font-weight:820;backdrop-filter:none;text-shadow:none}#detailSheet.detail-large>.actions .btn:focus{color:#06111b;background:rgba(249,251,253,.96);border-color:rgba(255,255,255,.9);box-shadow:0 16px 36px rgba(0,0,0,.28),0 0 0 1px rgba(255,255,255,.1) inset}#detailSheet.detail-large>.actions .btn:focus .icon{color:#06111b}#detailSheet.detail-large .detail-block{margin-top:34px}#detailSheet.detail-large #castBlock,#detailSheet.detail-large #personWorkBlock,#detailSheet.detail-large #recommendBlock,#detailSheet.detail-large #seasonBlock{max-width:none}#detailSheet.detail-large #seasonBlock{margin-top:clamp(34px,5.2vh,58px)}#detailSheet.detail-large .detail-block h3{margin:0 0 14px;font-size:clamp(21px, 2vw, 28px);font-weight:820;text-shadow:0 2px 12px rgba(0,0,0,.45)}#detailSheet.detail-large #seasonTabs{max-width:min(760px,54vw);padding-bottom:8px}#detailSheet.detail-large #seasonTabs:empty{display:none}#detailSheet.detail-large .rail{gap:18px;padding:6px 6px 16px;overflow-y:visible}#detailSheet.detail-large .episode-card{flex:0 0 clamp(210px,18.4vw,286px);max-width:clamp(210px,18.4vw,286px);min-height:0;aspect-ratio:16/9;padding:0;overflow:hidden;position:relative;border-radius:7px;background:rgba(32,45,58,.74);border-color:rgba(255,255,255,.15);box-shadow:0 12px 28px rgba(0,0,0,.24)}#detailSheet.detail-large .episode-card::before{content:"";position:absolute;right:0;bottom:0;left:0;z-index:1;height:62%;background:linear-gradient(180deg,rgba(0,0,0,0),rgba(4,10,16,.72) 55%,rgba(4,10,16,.92));pointer-events:none}#detailSheet.detail-large .episode-still{width:100%;max-width:100%;height:100%;margin:0;aspect-ratio:auto;object-fit:cover;opacity:.92}#detailSheet.detail-large .episode-badge{display:inline-flex;position:absolute;top:8px;left:8px;z-index:2;min-height:26px;align-items:center;padding:0 8px;border-radius:5px;background:rgba(54,119,199,.84);border:1px solid rgba(255,255,255,.18);color:rgba(255,255,255,.94);font-size:14px;font-weight:780;line-height:1}.episode-badge{display:none}#detailSheet.detail-large .episode-body{position:absolute;right:0;bottom:0;left:0;z-index:2;padding:0 12px 12px}#detailSheet.detail-large .episode-card b{color:#fff;font-size:clamp(15px, 1.35vw, 18px);font-weight:800;line-height:1.18;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;text-shadow:0 2px 8px rgba(0,0,0,.72)}#detailSheet.detail-large .episode-card p,#detailSheet.detail-large .episode-card span:not(.episode-badge){display:none}#detailSheet.detail-large .person-card{flex:0 0 clamp(240px,20vw,310px);max-width:clamp(240px,20vw,310px);height:96px;display:-webkit-box;display:-webkit-flex;display:flex;-webkit-box-orient:horizontal;-webkit-box-direction:normal;-webkit-flex-direction:row;flex-direction:row;align-items:center;border-radius:8px;background:0 0;border-color:transparent;box-shadow:none}#detailSheet.detail-large .person-card img{width:96px;max-width:96px;height:96px;-webkit-box-flex:0;-webkit-flex:0 0 96px;flex:0 0 96px;margin:0;aspect-ratio:auto;border-radius:999px;object-fit:cover;object-position:center 18%;background:rgba(255,255,255,.08)}#detailSheet.detail-large .person-card div{-webkit-box-flex:1;-webkit-flex:1 1 auto;flex:1 1 auto;min-width:0;min-height:auto;padding:0 0 0 18px;overflow:hidden}#detailSheet.detail-large .person-card b{display:block;color:rgba(255,255,255,.94);font-size:clamp(18px, 1.55vw, 24px);font-weight:820;line-height:1.08;text-shadow:0 2px 10px rgba(0,0,0,.5)}#detailSheet.detail-large .person-card span{margin-top:7px;color:rgba(232,239,247,.58);font-size:clamp(14px, 1.25vw, 18px);line-height:1.08;-webkit-line-clamp:1}#detailSheet.detail-large .card.landscape-card{flex:0 0 clamp(222px,18.6vw,300px);max-width:clamp(222px,18.6vw,300px);aspect-ratio:16/9;border-radius:8px;background:rgba(34,47,60,.7);border-color:rgba(255,255,255,.13);box-shadow:0 12px 28px rgba(0,0,0,.22)}#detailSheet.detail-large .landscape-card .poster{width:100%;max-width:100%;height:100%;margin:0;aspect-ratio:auto;object-fit:cover;opacity:.88}#detailSheet.detail-large .landscape-card .card-body{position:absolute;right:0;bottom:0;left:0;z-index:2;padding:38px 12px 11px;border-top:0;background:linear-gradient(180deg,rgba(0,0,0,0),rgba(3,8,14,.76) 48%,rgba(3,8,14,.92))}#detailSheet.detail-large .landscape-card .card-title{font-size:16px;line-height:1.18;min-height:0}#detailSheet.detail-large .landscape-card .card-meta,#detailSheet.detail-large .landscape-card .rating-badge{display:none}#detailSheet.detail-large .pan-search-block.active{max-width:min(980px,calc(100vw - var(--detail-side-pad) * 2))}@media (max-width:960px){#detailSheet.detail-large{--detail-side-pad:38px}#detailSheet.detail-large #seasonTabs,#detailSheet.detail-large .detail-block,#detailSheet.detail-large .detail-info,#detailSheet.detail-large>.actions{max-width:min(720px,68vw)}#detailSheet.detail-large .detail-cover{width:72vw}}html.native-mobile-app #detailSheet:not(.detail-large){--mobile-detail-x:20px;--mobile-hero-min:min(72vh, 680px);background:#081016;padding:0 var(--mobile-detail-x) calc(32px + var(--safe-bottom));overflow-y:auto;overflow-x:hidden;overscroll-behavior:contain}html.native-mobile-app #detailSheet:not(.detail-large).active{display:flex;flex-direction:column}html.native-mobile-app #detailSheet:not(.detail-large)::after,html.native-mobile-app #detailSheet:not(.detail-large)::before{content:"";position:fixed;top:0;right:0;left:0;pointer-events:none;z-index:0}html.native-mobile-app #detailSheet:not(.detail-large)::before{bottom:0;background:radial-gradient(72% 34% at 22% 58%,rgba(96,132,150,.18) 0,rgba(96,132,150,.08) 42%,transparent 72%),radial-gradient(68% 32% at 78% 48%,rgba(178,120,86,.14) 0,rgba(178,120,86,.06) 45%,transparent 74%),var(--detail-hero-bg,none);background-size:cover,cover,cover;background-position:center,center,center top;background-repeat:no-repeat,no-repeat,no-repeat;filter:blur(28px) saturate(1.32) contrast(1.06) brightness(.9);opacity:.98;transform:scale(1.12);transform-origin:center top}html.native-mobile-app #detailSheet:not(.detail-large)::after{bottom:0;background:linear-gradient(180deg,rgba(2,5,8,0) 0,rgba(3,7,11,0) 52%,rgba(5,10,15,.28) 70%,rgba(5,10,15,.78) 88%,#081016 100%)}html.native-mobile-app #detailSheet:not(.detail-large)>*{position:relative;z-index:2}html.native-mobile-app #detailSheet:not(.detail-large) .mobile-detail-back{position:fixed;top:max(14px,var(--active-safe-top));left:16px;width:54px;height:54px;color:rgba(255,255,255,.96);background:rgba(25,35,44,.28);border-color:rgba(255,255,255,.22);box-shadow:0 12px 30px rgba(0,0,0,.24),inset 0 1px 0 rgba(255,255,255,.12);backdrop-filter:blur(14px) saturate(1.08)}html.native-mobile-app #detailSheet:not(.detail-large) .mobile-detail-back .icon{width:25px;height:25px;stroke-width:2.4}html.native-mobile-app #detailSheet:not(.detail-large) .detail-cover{position:fixed;top:0;right:0;left:0;z-index:1;width:100vw;max-width:none;height:var(--mobile-hero-min);min-height:520px;max-height:none;margin:0;border-radius:0;aspect-ratio:auto;pointer-events:none;overflow:hidden;background:0 0;opacity:1;-webkit-mask-image:linear-gradient(180deg,#000 0%,#000 84%,rgba(0,0,0,.9) 89%,rgba(0,0,0,.42) 96%,transparent 100%);mask-image:linear-gradient(180deg,#000 0%,#000 84%,rgba(0,0,0,.9) 89%,rgba(0,0,0,.42) 96%,transparent 100%);-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat;-webkit-mask-size:100% 100%;mask-size:100% 100%}html.native-mobile-app #detailSheet:not(.detail-large) .detail-cover::after{content:"";position:absolute;top:82%;right:0;bottom:0;left:0;z-index:2;background:radial-gradient(90% 72% at 28% 42%,rgba(98,137,154,.18) 0,rgba(98,137,154,.07) 45%,transparent 78%),radial-gradient(86% 70% at 76% 38%,rgba(190,135,92,.14) 0,rgba(190,135,92,.05) 48%,transparent 80%),linear-gradient(180deg,rgba(0,0,0,0) 0,rgba(5,9,13,.08) 30%,rgba(5,9,13,.2) 72%,rgba(8,16,22,.34) 100%);-webkit-backdrop-filter:blur(10px) saturate(1.16);backdrop-filter:blur(10px) saturate(1.16);-webkit-mask-image:linear-gradient(180deg,transparent 0%,rgba(0,0,0,.2) 18%,#000 46%,#000 100%);mask-image:linear-gradient(180deg,transparent 0%,rgba(0,0,0,.2) 18%,#000 46%,#000 100%)}html.native-mobile-app #detailSheet:not(.detail-large) .detail-cover.poster-mode::after{display:block!important}html.native-mobile-app #detailSheet:not(.detail-large) .detail-cover.loading::before{z-index:3}html.native-mobile-app #detailSheet:not(.detail-large) .detail-cover img{width:100%;height:100%;object-fit:cover!important;object-position:center top;filter:brightness(1) saturate(1.05);-webkit-mask-image:linear-gradient(180deg,#000 0%,#000 84%,rgba(0,0,0,.88) 89%,rgba(0,0,0,.36) 96%,transparent 100%);mask-image:linear-gradient(180deg,#000 0%,#000 84%,rgba(0,0,0,.88) 89%,rgba(0,0,0,.36) 96%,transparent 100%);-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat;-webkit-mask-size:100% 100%;mask-size:100% 100%}html.native-mobile-app #detailSheet:not(.detail-large) .detail-info{display:contents;margin-top:max(410px,calc(var(--mobile-hero-min) - 220px));padding:0;text-shadow:0 2px 14px rgba(0,0,0,.56)}html.native-mobile-app #detailSheet:not(.detail-large) .detail-title-row{order:1}html.native-mobile-app #detailSheet:not(.detail-large) .detail-meta{order:2}html.native-mobile-app #detailSheet:not(.detail-large) .detail-info p{order:3}html.native-mobile-app #detailSheet:not(.detail-large)>.actions{order:4}html.native-mobile-app #detailSheet:not(.detail-large) #detailMoreBtn{order:5}html.native-mobile-app #detailSheet:not(.detail-large) .detail-block{order:6}html.native-mobile-app #detailSheet:not(.detail-large) #detailMoreBtn,html.native-mobile-app #detailSheet:not(.detail-large) .detail-info p,html.native-mobile-app #detailSheet:not(.detail-large) .detail-meta,html.native-mobile-app #detailSheet:not(.detail-large) .detail-title-row{position:relative;z-index:2}html.native-mobile-app #detailSheet:not(.detail-large) .detail-title-row{display:block;margin:max(410px,calc(var(--mobile-hero-min) - 220px)) 0 12px}html.native-mobile-app #detailSheet:not(.detail-large) .detail-title-row.has-logo #detailTitle,html.native-mobile-app #detailSheet:not(.detail-large) .detail-title-row.logo-pending #detailTitle{display:none}html.native-mobile-app #detailSheet:not(.detail-large) .detail-title-row.has-logo .detail-title-logo{display:block;max-width:calc(100vw - var(--mobile-detail-x) * 2 - 92px);max-height:96px;margin:0 0 12px;filter:drop-shadow(0 5px 22px rgba(0, 0, 0, .62))}html.native-mobile-app #detailSheet:not(.detail-large) .detail-info h2{max-width:calc(100vw - var(--mobile-detail-x) * 2 - 92px);margin:0 0 10px;color:rgba(255,255,255,.98);font-size:clamp(38px, 11vw, 54px);line-height:1.02;font-weight:900;letter-spacing:0;text-shadow:0 4px 20px rgba(0,0,0,.62)}html.native-mobile-app #detailSheet:not(.detail-large) .detail-title-meta{display:flex;flex-wrap:wrap;gap:7px;color:rgba(245,248,251,.86);font-size:20px;font-weight:780;line-height:1.2}html.native-mobile-app #detailSheet:not(.detail-large) .detail-title-meta .score{color:rgba(255,213,96,.98)}html.native-mobile-app #detailSheet:not(.detail-large) .detail-title-meta .sep{color:rgba(245,248,251,.48)}html.native-mobile-app #detailSheet:not(.detail-large) .detail-meta{gap:8px;margin:10px 0 20px}html.native-mobile-app #detailSheet:not(.detail-large) .meta-pill{min-height:34px;display:inline-flex;align-items:center;padding:0 13px;border:0;border-radius:999px;color:rgba(245,248,251,.78);background:rgba(255,255,255,.13);font-size:15px;font-weight:620;backdrop-filter:blur(10px) saturate(1.04)}html.native-mobile-app #detailSheet:not(.detail-large) .meta-pill.strong{color:rgba(255,225,132,.98);background:rgba(255,255,255,.16);font-weight:820}html.native-mobile-app #detailSheet:not(.detail-large) .detail-info p{color:rgba(246,249,252,.82);font-size:17px;line-height:1.72;font-weight:430;text-shadow:0 2px 12px rgba(0,0,0,.64)}html.native-mobile-app #detailSheet:not(.detail-large) .detail-info p.clamped{max-height:var(--detail-text-max,6.9em);padding-right:0;overflow:hidden;cursor:pointer}html.native-mobile-app #detailSheet:not(.detail-large) #detailMoreBtn{min-height:0;margin:2px 0 0;padding:0;border:0;background:0 0;color:rgba(190,220,255,.92);box-shadow:none;font-size:15px;line-height:1.72;text-shadow:none;backdrop-filter:none}html.native-mobile-app #detailSheet:not(.detail-large)>.actions{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px;margin:20px 0 0}html.native-mobile-app #detailSheet:not(.detail-large)>.actions.has-continue{grid-template-columns:minmax(132px,1fr) minmax(82px,.58fr) minmax(82px,.58fr);gap:8px}html.native-mobile-app #detailSheet:not(.detail-large)>.actions .btn{min-width:0;min-height:50px;justify-content:center;border-radius:999px;border-color:rgba(255,255,255,.18);background:rgba(255,255,255,.15);color:rgba(255,255,255,.95);box-shadow:0 10px 26px rgba(0,0,0,.18),inset 0 1px 0 rgba(255,255,255,.1);font-size:16px;font-weight:800;backdrop-filter:blur(16px) saturate(1.08)}html.native-mobile-app #detailSheet:not(.detail-large)>.actions.has-continue .btn{min-height:50px;gap:6px;padding:0 8px;border-radius:14px;font-size:14px;line-height:1.05;white-space:nowrap;backdrop-filter:none;-webkit-font-smoothing:antialiased}html.native-mobile-app #detailSheet:not(.detail-large)>.actions.has-continue .icon{width:18px;height:18px}html.native-mobile-app #detailSheet:not(.detail-large)>.actions.has-continue #detailContinueBtn{color:#fff;background:radial-gradient(circle at 24% 20%,rgba(255,255,255,.34),rgba(255,255,255,0) 34%),linear-gradient(135deg,#12d7ff 0,#0b91ff 58%,#0867f7 100%);border-color:rgba(255,255,255,.16);box-shadow:0 16px 30px rgba(0,128,255,.28),inset 0 1px 0 rgba(255,255,255,.26);font-size:15px;font-weight:800;text-shadow:none}html.native-mobile-app #detailSheet:not(.detail-large)>.actions.has-continue #detailSearchBtn,html.native-mobile-app #detailSheet:not(.detail-large)>.actions.has-continue #panSearchBtn{color:#111827;background:rgba(255,255,255,.98);border-color:rgba(255,255,255,.72);box-shadow:0 14px 28px rgba(0,0,0,.18),inset 0 1px 0 rgba(255,255,255,.72);font-weight:800;text-shadow:none}html.native-mobile-app #detailSheet:not(.detail-large)>.actions .btn.primary{background:rgba(255,255,255,.19)}html.native-mobile-app #detailSheet:not(.detail-large)>.actions .icon{width:21px;height:21px}html.native-mobile-app #detailSheet:not(.detail-large) .detail-block{margin-top:28px}html.native-mobile-app #detailSheet:not(.detail-large) .detail-block h3{margin:0 0 14px;color:rgba(255,255,255,.96);font-size:21px;line-height:1.18;font-weight:880;text-shadow:0 2px 12px rgba(0,0,0,.52)}html.native-mobile-app #detailSheet:not(.detail-large) .rail{width:calc(100% + var(--mobile-detail-x) * 2);max-width:none;gap:12px;margin-right:calc(var(--mobile-detail-x) * -1);margin-left:calc(var(--mobile-detail-x) * -1);padding:0 var(--mobile-detail-x) 14px;scroll-padding-left:var(--mobile-detail-x)}html.native-mobile-app #detailSheet:not(.detail-large) #seasonTabs{width:calc(100% + var(--mobile-detail-x) * 2);max-width:none;margin-right:calc(var(--mobile-detail-x) * -1);margin-left:calc(var(--mobile-detail-x) * -1);padding-right:var(--mobile-detail-x);padding-left:var(--mobile-detail-x);scroll-padding-left:var(--mobile-detail-x)}html.native-mobile-app #detailSheet:not(.detail-large) .episode-card{flex-basis:168px;max-width:178px;min-height:112px;display:flex;flex-direction:column;border-radius:12px;background:rgba(255,255,255,.1);border-color:rgba(255,255,255,.13);overflow:hidden;box-shadow:0 10px 24px rgba(0,0,0,.2)}html.native-mobile-app #detailSheet:not(.detail-large) .episode-card.has-still{padding:0}html.native-mobile-app #detailSheet:not(.detail-large) .episode-still-wrap{width:calc(100% + 2px);max-width:calc(100% + 2px);height:94px;min-height:94px;display:block;order:0;margin:-1px -1px 0;padding:0;border:0;aspect-ratio:auto;overflow:hidden;line-height:0;flex:0 0 94px;background:0 0}html.native-mobile-app #detailSheet:not(.detail-large) .episode-still{width:100%;max-width:none;height:100%;min-height:100%;margin:0;display:block;aspect-ratio:auto;object-fit:cover;object-position:center top}html.native-mobile-app #detailSheet:not(.detail-large) .episode-body{order:1;flex:1 1 auto}html.native-mobile-app #detailSheet:not(.detail-large) .episode-card b{font-size:13px;line-height:1.22}html.native-mobile-app #detailSheet:not(.detail-large) .person-card{flex:0 0 86px;max-width:92px;height:auto;align-items:center;background:0 0;border-color:transparent;box-shadow:none;text-align:center}html.native-mobile-app #detailSheet:not(.detail-large) .person-card img{width:68px;max-width:68px;height:68px;flex-basis:68px;margin:0 auto;border-radius:999px;object-position:center 18%;box-shadow:0 8px 20px rgba(0,0,0,.22)}html.native-mobile-app #detailSheet:not(.detail-large) .person-card div{width:100%;min-width:0;padding:8px 0 0;text-align:center}html.native-mobile-app #detailSheet:not(.detail-large) .person-card b{width:100%;color:rgba(255,255,255,.94);font-size:13px;font-weight:820;text-align:center}html.native-mobile-app #detailSheet:not(.detail-large) .person-card span{width:100%;margin-top:2px;color:rgba(232,239,247,.58);font-size:11px;text-align:center;-webkit-line-clamp:1}@media (max-width:380px){html.native-mobile-app #detailSheet:not(.detail-large){--mobile-detail-x:16px}html.native-mobile-app #detailSheet:not(.detail-large) .detail-info{margin-top:max(380px,calc(var(--mobile-hero-min) - 240px))}html.native-mobile-app #detailSheet:not(.detail-large) .detail-title-row{margin-top:max(380px,calc(var(--mobile-hero-min) - 240px))}html.native-mobile-app #detailSheet:not(.detail-large) .detail-info h2{font-size:34px}html.native-mobile-app #detailSheet:not(.detail-large) .detail-title-row.has-logo .detail-title-logo{max-height:78px}html.native-mobile-app #detailSheet:not(.detail-large) .detail-title-meta{font-size:18px}html.native-mobile-app #detailSheet:not(.detail-large)>.actions.has-continue{grid-template-columns:minmax(122px,1fr) minmax(72px,.58fr) minmax(72px,.58fr);gap:6px}html.native-mobile-app #detailSheet:not(.detail-large)>.actions.has-continue .btn{min-height:48px;padding:0 6px;font-size:13px}html.native-mobile-app #detailSheet:not(.detail-large)>.actions.has-continue .icon{width:17px;height:17px}html.native-mobile-app #detailSheet:not(.detail-large)>.actions.has-continue #detailContinueBtn{font-size:13px}}html.native-mobile-app.mobile-detail-translucent #detailSheet:not(.detail-large){--mobile-detail-x:14px;--sheet-x:14px;background:0 0;padding:max(16px,var(--active-safe-top)) var(--mobile-detail-x) calc(22px + var(--safe-bottom));backdrop-filter:none}html.native-mobile-app.mobile-detail-translucent #detailSheet:not(.detail-large)::after,html.native-mobile-app.mobile-detail-translucent #detailSheet:not(.detail-large)::before{display:none}html.native-mobile-app.mobile-detail-translucent #detailSheet:not(.detail-large)>*{position:relative;z-index:auto}html.native-mobile-app.mobile-detail-translucent #detailSheet:not(.detail-large) .mobile-detail-back{position:relative;top:auto;left:auto;align-self:flex-start;width:42px;height:42px;margin:0 0 10px;color:rgba(255,255,255,.92);background:rgba(12,18,24,.18);border-color:rgba(255,255,255,.16);box-shadow:0 8px 22px rgba(0,0,0,.18);backdrop-filter:blur(8px) saturate(1.05)}html.native-mobile-app.mobile-detail-translucent #detailSheet:not(.detail-large) .mobile-detail-back .icon{width:21px;height:21px;stroke-width:2.2}html.native-mobile-app.mobile-detail-translucent #detailSheet:not(.detail-large) .detail-cover{position:relative;top:auto;right:auto;left:auto;z-index:auto;opacity:1;width:100%;max-width:100%;height:56.25vw;min-height:180px;max-height:42vh;margin:14px 0;border-radius:14px;aspect-ratio:16/9;pointer-events:auto;overflow:hidden;background:0 0;isolation:isolate;-webkit-mask-image:none;mask-image:none}html.native-mobile-app.mobile-detail-translucent #detailSheet:not(.detail-large) .detail-cover::after{display:none}html.native-mobile-app.mobile-detail-translucent #detailSheet:not(.detail-large) .detail-cover img{object-fit:contain!important;object-position:left center;filter:none;border-radius:inherit;-webkit-mask-image:none;mask-image:none}html.native-mobile-app.mobile-detail-translucent #detailSheet:not(.detail-large) .detail-cover.poster-mode img{object-fit:cover!important;object-position:center 24%}html.native-mobile-app.mobile-detail-translucent #detailSheet:not(.detail-large) .detail-info{margin-top:0;padding:0 2px 12px;text-shadow:none}html.native-mobile-app.mobile-detail-translucent #detailSheet:not(.detail-large) .detail-title-row{display:flex;align-items:baseline;gap:8px;flex-wrap:wrap;margin:0 0 8px}html.native-mobile-app.mobile-detail-translucent #detailSheet:not(.detail-large) .detail-title-row.has-logo{display:block}html.native-mobile-app.mobile-detail-translucent #detailSheet:not(.detail-large) .detail-title-row.has-logo .detail-title-logo{max-width:78vw;max-height:54px;margin:0 0 8px;filter:none}html.native-mobile-app.mobile-detail-translucent #detailSheet:not(.detail-large) .detail-info h2{max-width:none;margin:0;color:var(--text);font-size:clamp(22px, 6vw, 32px);line-height:1.12;font-weight:800;text-shadow:none}html.native-mobile-app.mobile-detail-translucent #detailSheet:not(.detail-large) .detail-title-meta{display:inline-flex;align-items:baseline;flex-wrap:wrap;gap:6px;color:rgba(244,247,251,.9);font-size:13px;font-weight:720;line-height:1.2;text-shadow:0 1px 2px rgba(0,0,0,.38)}html.native-mobile-app.mobile-detail-translucent #detailSheet:not(.detail-large) .detail-title-meta .score{color:rgba(255,218,128,.95)}html.native-mobile-app.mobile-detail-translucent #detailSheet:not(.detail-large) .detail-title-meta .sep{display:inline;color:rgba(244,247,251,.42)}html.native-mobile-app.mobile-detail-translucent #detailSheet:not(.detail-large) .detail-meta{gap:8px;margin:8px 0 14px}html.native-mobile-app.mobile-detail-translucent #detailSheet:not(.detail-large) .meta-pill{min-height:0;padding:5px 8px;border:1px solid var(--line);border-radius:999px;color:var(--muted);background:var(--panel);font-size:12px;font-weight:400;backdrop-filter:none}html.native-mobile-app.mobile-detail-translucent #detailSheet:not(.detail-large) .meta-pill.strong{color:var(--text);border-color:var(--line-strong);background:var(--control-active);font-weight:760}html.native-mobile-app.mobile-detail-translucent #detailSheet:not(.detail-large) .detail-info p{color:rgba(244,247,251,.82);font-size:14px;line-height:1.62;font-weight:400;text-shadow:none}html.native-mobile-app.mobile-detail-translucent #detailSheet:not(.detail-large) .detail-info p.clamped{cursor:pointer}html.native-mobile-app.mobile-detail-translucent #detailSheet:not(.detail-large) #detailMoreBtn{min-height:0;margin:2px 0 0;padding:0;border:0;background:0 0;color:rgba(184,226,255,.92);box-shadow:none;font-size:13px;line-height:1.62}html.native-mobile-app.mobile-detail-translucent #detailSheet:not(.detail-large)>.actions{display:flex;flex-wrap:wrap;gap:10px;margin:18px 0 0}html.native-mobile-app.mobile-detail-translucent #detailSheet:not(.detail-large)>.actions.has-continue{display:grid;grid-template-columns:minmax(122px,1fr) minmax(72px,.58fr) minmax(72px,.58fr);gap:8px}html.native-mobile-app.mobile-detail-translucent #detailSheet:not(.detail-large)>.actions .btn{min-width:0;min-height:42px;justify-content:center;border-radius:var(--radius);border-color:var(--line);background:var(--control);color:var(--text);box-shadow:none;font-size:14px;font-weight:760;text-shadow:0 1px 2px rgba(0,0,0,.38);backdrop-filter:blur(12px) saturate(1.05)}html.native-mobile-app.mobile-detail-translucent #detailSheet:not(.detail-large)>.actions.has-continue .btn{min-height:44px;gap:5px;padding:0 7px;border-radius:13px;font-size:13px;line-height:1.05;white-space:nowrap}html.native-mobile-app.mobile-detail-translucent #detailSheet:not(.detail-large)>.actions.has-continue .icon{width:18px;height:18px}html.native-mobile-app.mobile-detail-translucent #detailSheet:not(.detail-large)>.actions.has-continue #detailContinueBtn{color:#fff;background:radial-gradient(circle at 24% 20%,rgba(255,255,255,.34),rgba(255,255,255,0) 34%),linear-gradient(135deg,#12d7ff 0,#0b91ff 58%,#0867f7 100%);border-color:rgba(255,255,255,.16);box-shadow:0 14px 26px rgba(0,128,255,.24),inset 0 1px 0 rgba(255,255,255,.24);font-weight:800;text-shadow:none}html.native-mobile-app.mobile-detail-translucent #detailSheet:not(.detail-large)>.actions.has-continue #detailSearchBtn,html.native-mobile-app.mobile-detail-translucent #detailSheet:not(.detail-large)>.actions.has-continue #panSearchBtn{color:#111827;background:rgba(255,255,255,.97);border-color:rgba(255,255,255,.72);box-shadow:0 12px 24px rgba(0,0,0,.14),inset 0 1px 0 rgba(255,255,255,.72);font-weight:800;text-shadow:none}html.native-mobile-app.mobile-detail-translucent #detailSheet:not(.detail-large)>.actions .btn.primary{background:var(--control-active);border-color:var(--line-strong)}html.native-mobile-app.mobile-detail-translucent #detailSheet:not(.detail-large)>.actions .icon{width:19px;height:19px}html.native-mobile-app.mobile-detail-translucent #detailSheet:not(.detail-large) .detail-block{margin-top:18px}html.native-mobile-app.mobile-detail-translucent #detailSheet:not(.detail-large) .detail-block h3{margin:0 0 10px;color:var(--text);font-size:17px;line-height:1.2;font-weight:760;text-shadow:none}html.native-mobile-app.mobile-detail-translucent #detailSheet:not(.detail-large) .rail{width:100%;max-width:100%;gap:12px;margin:0;padding:2px 0 5px;scroll-padding-left:0}html.native-mobile-app.mobile-detail-translucent #detailSheet:not(.detail-large) #seasonTabs{width:100%;max-width:100%;margin:0;padding-right:0;padding-left:0;scroll-padding-left:0}html.native-mobile-app.mobile-detail-translucent #detailSheet:not(.detail-large) .episode-card{flex:0 0 230px;max-width:260px;min-height:138px;display:flex;flex-direction:column;border-radius:var(--radius);background:var(--panel);border-color:var(--line);box-shadow:none}html.native-mobile-app.mobile-detail-translucent #detailSheet:not(.detail-large) .episode-still-wrap{height:130px;min-height:130px;flex-basis:130px}html.native-mobile-app.mobile-detail-translucent #detailSheet:not(.detail-large) .episode-card b{font-size:14px;line-height:1.18}html.native-mobile-app.mobile-detail-translucent #detailSheet:not(.detail-large) .person-card{flex:0 0 116px;max-width:128px;height:244px;align-items:stretch;background:var(--panel);border-color:var(--line);box-shadow:none;text-align:left}html.native-mobile-app.mobile-detail-translucent #detailSheet:not(.detail-large) .person-card img{width:calc(100% + 2px);max-width:calc(100% + 2px);height:176px;flex-basis:176px;margin:-1px -1px 0;border-radius:0;object-position:center top;box-shadow:none}html.native-mobile-app.mobile-detail-translucent #detailSheet:not(.detail-large) .person-card div{width:auto;min-width:0;padding:8px 9px 9px;text-align:left}html.native-mobile-app.mobile-detail-translucent #detailSheet:not(.detail-large) .person-card b{width:auto;color:var(--text);font-size:14px;font-weight:760;text-align:left}html.native-mobile-app.mobile-detail-translucent #detailSheet:not(.detail-large) .person-card span{width:auto;margin-top:3px;color:var(--muted);font-size:12px;text-align:left;-webkit-line-clamp:2}html.native-mobile-app .image-viewer.episode-mode{display:none;grid-template-rows:minmax(0,1fr);gap:0;background:#081016;padding:0 0 calc(28px + var(--safe-bottom));overflow:hidden}html.native-mobile-app .image-viewer.episode-mode.active{display:grid}html.native-mobile-app .image-viewer.episode-mode #closeImageBtn{display:none}html.native-mobile-app .image-viewer.episode-mode .mobile-detail-back{position:fixed;top:max(14px,var(--active-safe-top));left:16px;width:54px;height:54px;z-index:95;color:rgba(255,255,255,.96);background:rgba(25,35,44,.28);border-color:rgba(255,255,255,.22);box-shadow:0 12px 30px rgba(0,0,0,.24),inset 0 1px 0 rgba(255,255,255,.12);backdrop-filter:blur(14px) saturate(1.08)}html.native-mobile-app .image-viewer.episode-mode .mobile-detail-back .icon{width:25px;height:25px;stroke-width:2.4}html.native-mobile-app .image-viewer.episode-mode .image-content{width:100%;height:100%;display:block;overflow-y:auto;overscroll-behavior:contain;background:#081016}html.native-mobile-app .image-viewer.episode-mode .episode-view{width:100%;min-height:var(--fm-web-height);display:block;padding:0 22px calc(34px + var(--safe-bottom));border:0;border-radius:0;background:#081016;box-shadow:none}html.native-mobile-app .image-viewer.episode-mode .episode-view img{width:calc(100% + 44px);max-width:none;height:min(64vh,620px);max-height:none;margin:0 -22px;aspect-ratio:auto;object-fit:cover;object-position:center top;border:0;border-radius:0;filter:saturate(.94) contrast(.98) brightness(.84)}html.native-mobile-app .image-viewer.episode-mode .episode-view::before{content:"";position:fixed;top:0;right:0;left:0;height:min(68vh,660px);z-index:1;pointer-events:none;background:linear-gradient(180deg,rgba(2,5,8,.02) 0,rgba(2,5,8,.1) 42%,rgba(5,10,15,.72) 76%,#081016 100%),linear-gradient(90deg,rgba(3,7,11,.28),transparent 42%,rgba(3,7,11,.22))}html.native-mobile-app .image-viewer.episode-mode .episode-view>div,html.native-mobile-app .image-viewer.episode-mode .episode-view>p{position:relative;z-index:2;text-shadow:0 2px 12px rgba(0,0,0,.58)}html.native-mobile-app .image-viewer.episode-mode .episode-view>div{margin-top:-142px;padding-bottom:18px}html.native-mobile-app .image-viewer.episode-mode .episode-view.no-still{padding-top:max(96px,var(--active-safe-top));background:linear-gradient(180deg,rgba(12,20,28,.96),#081016 42%),var(--detail-hero-bg,none);background-size:cover;background-position:center top}html.native-mobile-app .image-viewer.episode-mode .episode-view.no-still>div{margin-top:0}html.native-mobile-app .image-viewer.episode-mode .episode-view h3{margin:0 0 10px;color:rgba(255,255,255,.98);font-size:30px;line-height:1.14;font-weight:900;letter-spacing:0}html.native-mobile-app .image-viewer.episode-mode .episode-view span{display:inline-flex;min-height:30px;align-items:center;padding:0 11px;border-radius:999px;color:rgba(245,248,251,.76);background:rgba(255,255,255,.12);font-size:14px;line-height:1;backdrop-filter:blur(10px) saturate(1.04)}html.native-mobile-app .image-viewer.episode-mode .episode-view p{margin:0;color:rgba(246,249,252,.84);font-size:17px;line-height:1.78;white-space:pre-wrap}.sync-panel{display:grid;gap:12px;padding:12px;border-radius:var(--radius);background:var(--panel);border:1px solid var(--line)}.hint{margin:0;color:var(--muted);font-size:13px;line-height:1.55}.mono{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;word-break:break-all}.toast{position:fixed;left:50%;bottom:max(18px,var(--safe-bottom));z-index:90;transform:translateX(-50%) translateY(24px);max-width:calc(100vw - 28px);padding:10px 12px;border-radius:var(--radius);background:rgba(6,8,10,.86);border:1px solid var(--line);color:var(--text);box-shadow:var(--shadow);opacity:0;pointer-events:none;transition:.18s ease;font-size:13px}.toast.show{opacity:1;transform:translateX(-50%) translateY(0)}.back-top{position:fixed;right:max(14px,var(--safe-right));bottom:max(76px,calc(58px + var(--safe-bottom)));z-index:55;width:44px;height:44px;display:grid;place-items:center;border-radius:var(--radius);background:rgba(34,43,51,.68);border:1px solid var(--line);color:var(--text);box-shadow:0 12px 32px rgba(0,0,0,.24);backdrop-filter:blur(12px) saturate(1.05);opacity:0;visibility:hidden;pointer-events:none;transform:translateY(10px);transition:opacity .16s ease,transform .16s ease,visibility .16s ease}.back-top.show{opacity:1;visibility:visible;pointer-events:auto;transform:translateY(0)}.connection-dock{position:relative;z-index:50;width:auto;width:fit-content;max-width:100%;justify-self:end;margin-left:auto;margin:0;border-radius:var(--radius);border:1px solid var(--line);background:var(--control);box-shadow:0 12px 32px rgba(0,0,0,.2);backdrop-filter:blur(12px) saturate(1.05);overflow:visible}.connection-toggle{width:auto;min-height:34px;display:inline-flex;align-items:center;display:grid;grid-template-columns:auto auto auto;align-items:center;gap:7px;padding:0 9px;background:0 0;color:var(--text);text-align:left}.connection-title{font-size:13px;font-weight:800;white-space:nowrap}.connection-arrow{color:var(--muted);font-size:13px;transition:transform .16s ease}.connection-dock.open .connection-arrow{transform:rotate(180deg)}.connection-body{display:none;position:absolute;right:0;top:calc(100% + 8px);z-index:80;width:420px;max-width:92vw;max-width:calc(100vw - 28px);max-width:calc(var(--fm-web-width,100vw) - 28px);width:min(calc(var(--fm-web-width,100vw) - 28px),420px);max-width:calc(var(--fm-web-width,100vw) - 28px);margin:0;padding:11px;border:1px solid var(--line);border-radius:var(--radius);background:#222b33;box-shadow:0 14px 36px rgba(0,0,0,.24);backdrop-filter:blur(14px) saturate(1.05);transform:translateX(var(--connection-shift,0))}.connection-body.open{display:block}.connection-grid{display:block;display:grid;gap:8px;margin-top:10px}.connection-item{display:flex;align-items:baseline;display:grid;grid-template-columns:minmax(56px,74px) minmax(0,1fr);gap:8px;align-items:baseline;font-size:12px;line-height:1.45}.connection-item b{flex:0 0 74px;color:var(--muted);font-weight:700}.connection-item span,.connection-item>.detail-style-segmented{flex:1 1 auto;min-width:0;word-break:break-word}.connection-item.refresh-progress{align-items:start}.connection-item.refresh-progress span{white-space:pre-line}.detail-style-segmented{min-width:0;display:inline-flex;display:inline-grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:2px;padding:2px;border-radius:8px;border:1px solid rgba(255,255,255,.14);background:rgba(255,255,255,.06)}.detail-style-option{min-width:0;min-height:28px;display:inline-flex;align-items:center;justify-content:center;padding:0 8px;border-radius:6px;border:1px solid transparent;color:rgba(244,247,251,.7);font-size:12px;font-weight:760;line-height:1;white-space:nowrap}.detail-style-option.active{color:var(--text);background:rgba(184,226,255,.2);border-color:rgba(184,226,255,.34)}.relay-mirror-config{display:grid;gap:8px;margin-top:10px;padding-top:10px;border-top:1px solid rgba(255,255,255,.12)}.relay-mirror-config label{display:grid;gap:5px;color:var(--muted);font-size:12px;font-weight:700}.relay-mirror-config .field{width:100%;min-height:36px;padding:8px 10px;font-size:12px}.relay-mirror-config textarea.field{min-height:68px}.relay-mirror-progress{min-height:58px;padding:8px 10px;border:1px solid rgba(255,255,255,.12);border-radius:var(--radius);color:var(--text);background:rgba(0,0,0,.16);font-size:12px;line-height:1.45;white-space:pre-line;word-break:break-word}.connection-body .actions{display:flex;flex-wrap:wrap;display:grid;grid-template-columns:repeat(auto-fit,minmax(96px,1fr));gap:8px}.connection-body .btn{min-width:0;padding:0 10px;font-size:12px;white-space:nowrap}html.tv-mode .search{display:flex;align-items:stretch;gap:0}html.tv-mode .search .field{flex:1 1 auto;min-width:0}html.tv-mode .search .btn,html.tv-mode .search .icon-btn,html.tv-mode .search>.connection-dock{flex:0 0 auto;margin-left:10px}html.tv-mode .search .btn,html.tv-mode .search .icon-btn{height:44px;min-height:44px;align-self:stretch}html.tv-mode .search #searchSubmitBtn{box-sizing:border-box;min-width:98px;display:flex;align-items:center;justify-content:center;padding:0 16px;line-height:1;white-space:nowrap}html.tv-mode .search #searchSubmitBtn .icon{display:block;flex:0 0 auto;margin-right:7px}html.tv-mode .search #homeSettingBtn{box-sizing:border-box;width:58px;min-width:58px;max-width:58px;flex-basis:58px;display:flex;align-items:center;justify-content:center;padding:0;line-height:1}html.tv-mode .search #homeSettingBtn .icon{display:block;width:24px;height:24px;margin:0}html.tv-mode .search>.connection-dock{box-sizing:border-box;width:104px;min-width:104px;max-width:104px;flex-basis:104px;height:44px;min-height:44px;align-self:stretch;justify-self:auto;overflow:visible}html.tv-mode .search>.connection-dock .connection-toggle{box-sizing:border-box;width:100%;min-width:104px;max-width:104px;height:44px;min-height:44px;display:flex;flex-direction:row;flex-wrap:nowrap;align-items:center;justify-content:center;padding:0 11px;white-space:nowrap;line-height:1}html.tv-mode .search>.connection-dock .connection-arrow,html.tv-mode .search>.connection-dock .connection-title,html.tv-mode .search>.connection-dock .dot{flex:0 0 auto;display:inline-block;line-height:1;white-space:nowrap}html.tv-mode .search>.connection-dock .dot{width:10px;height:10px;margin-right:8px;vertical-align:middle}html.tv-mode .search>.connection-dock .connection-title{font-size:15px;font-weight:800;margin-right:7px;vertical-align:middle}html.tv-mode .search>.connection-dock .connection-arrow{font-size:15px;margin-left:0;vertical-align:middle}.pan-config{display:grid;gap:8px;margin-top:10px;padding-top:10px;border-top:1px solid rgba(255,255,255,.12)}.pan-config label{display:grid;gap:5px;color:var(--muted);font-size:12px;line-height:1.35}.pan-config .field{min-height:38px;font-size:12px}.pan-disk-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(70px,1fr));gap:6px}.pan-disk-grid label{min-width:0;min-height:32px;display:flex;align-items:center;gap:6px;padding:0 8px;border-radius:var(--radius);border:1px solid rgba(255,255,255,.14);background:rgba(255,255,255,.04);color:var(--text);font-size:12px;font-weight:720}.pan-disk-grid input{width:14px;height:14px;accent-color:rgba(244,247,251,.82)}.pan-disk-grid label:focus-within{background:rgba(70,85,96,.72);border-color:var(--focus-line);color:var(--text)}.panel-editing{background:rgba(24,36,46,.88)!important;border-color:rgba(184,226,255,.9)!important}.pan-search-block{display:none;margin-top:18px}.pan-search-block.active{display:block}.pan-result-list{display:grid;gap:9px;align-content:flex-start;align-items:start;grid-auto-rows:max-content;height:52vh;max-height:560px;min-height:260px;overflow-y:auto;overscroll-behavior-y:contain;padding-right:2px;scrollbar-width:none}.pan-result-list::-webkit-scrollbar{display:none}.pan-tabs{margin:0 0 9px}.pan-tabs:empty{display:none}.pan-tabs .chip{min-height:30px;padding:0 10px;font-size:12px}.pan-tabs .chip.active{background:rgba(82,98,108,.82);border-color:rgba(184,226,255,.74)}.pan-result-item{width:100%;min-width:0;display:grid;gap:7px;padding:11px;border-radius:var(--radius);border:1px solid var(--line);background:var(--panel);color:var(--text);text-align:left;backdrop-filter:blur(10px) saturate(1.05);contain:layout style}.pan-result-item.is-bad{opacity:.58}.pan-result-title{display:flex;min-width:0;align-items:center;gap:8px;font-size:13px;font-weight:800;line-height:1.3}.pan-result-title span:first-child{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.pan-result-meta,.pan-result-url{color:var(--muted);font-size:12px;line-height:1.35}.pan-result-url{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.pan-health{flex:0 0 auto;display:inline-block;width:.55rem;height:.55rem;border-radius:999px;background:#94a3b8;box-shadow:0 0 0 1px rgba(255,255,255,.18)}.pan-health.ok{background:#22c55e}.pan-health.bad{background:#ef4444}.pan-health.locked{background:#f59e0b}.pan-health.pending{background:#60a5fa;animation:pulse-dot 1.1s ease-in-out infinite}.pan-health.uncertain,.pan-health.unsupported{background:#94a3b8}@keyframes pulse-dot{0%,100%{opacity:.45;transform:scale(.92)}50%{opacity:1;transform:scale(1.08)}}.dot{width:9px;height:9px;border-radius:999px;background:var(--muted)}.dot.ok{background:var(--ok)}.dot.warn{background:#ffcc4d}.dot.bad{background:var(--danger)}.image-viewer{display:none;position:fixed;top:0;right:0;bottom:0;left:0;inset:0;z-index:100;height:100vh;min-height:var(--fm-web-height);background:var(--panel-strong);backdrop-filter:blur(8px) saturate(1.05);padding:max(14px,var(--active-safe-top)) 14px calc(18px + var(--safe-bottom))}.image-viewer.episode-mode{background:0 0;backdrop-filter:none}.image-viewer.active{display:grid;grid-template-rows:auto minmax(0,1fr);gap:14px}.image-content{min-width:0;min-height:0;display:grid;place-items:center;overflow-y:auto;scrollbar-width:none}.image-content::-webkit-scrollbar{display:none}.image-content img{align-self:center;justify-self:center;width:100%;height:100%;max-height:calc(var(--fm-web-height) - 86px - var(--safe-bottom));object-fit:contain;background:0 0}.episode-view{width:min(860px,100%);min-width:0;align-self:start;display:grid;gap:12px;padding:12px;padding-bottom:20px;border-radius:var(--radius);border:1px solid var(--line);background:var(--panel);box-shadow:var(--shadow)}.episode-view img{width:100%;height:auto;max-height:min(48vh,460px);aspect-ratio:16/9;object-fit:cover;border-radius:var(--radius);border:1px solid var(--line);background:rgba(0,0,0,.18)}.episode-view h3{margin:0;font-size:19px;line-height:1.3}.episode-view span{color:var(--muted);font-size:13px;line-height:1.4}.episode-view p{margin:0;color:rgba(244,247,251,.9);font-size:15px;line-height:1.65;white-space:pre-wrap}.focusable:focus,button:focus,input:focus,textarea:focus{outline:0;border-color:var(--focus-line);box-shadow:none;z-index:5;transition:none}.focusable:not(.back-top):focus,button:not(.back-top):focus,input:focus,textarea:focus{position:relative}.back-top:focus{position:fixed;z-index:55}.card:focus,.episode-card:focus,.person-card:focus{transform:translateY(-1px) scale(1.035);border-color:var(--focus-line);background:rgba(var(--panel-rgb),.66);box-shadow:none}.card:focus img,.episode-card:focus img,.person-card:focus img{filter:brightness(1.06) saturate(1.04)}html.tv-mode .card:focus,html.tv-mode .episode-card:focus,html.tv-mode .person-card:focus{transform:translateY(-1px) scale(1.025);outline:2px solid rgba(255,255,255,.9);outline-offset:-2px;border-color:rgba(255,255,255,.96);background:rgba(var(--panel-rgb),.72);box-shadow:inset 0 0 0 1px rgba(168,218,255,.72);transition:none;z-index:12}html.tv-mode .episode-card:focus{transform:translateY(-1px) scale(1.03)}html.tv-mode .card:focus{border-color:rgba(255,255,255,.98);box-shadow:inset 0 0 0 1px rgba(168,218,255,.74)}html.tv-mode .btn,html.tv-mode .card,html.tv-mode .chip,html.tv-mode .connection-toggle,html.tv-mode .field,html.tv-mode .live-entry-card,html.tv-mode .mini-icon-btn,html.tv-mode .pan-result-item,html.tv-mode .person-info,html.tv-mode .rating-badge,html.tv-mode .recent-badge{backdrop-filter:none}html.tv-mode .card:focus img,html.tv-mode .episode-card:focus img,html.tv-mode .person-card:focus img{filter:none}.pan-result-item:focus{outline:2px solid rgba(168,218,255,.86);outline-offset:-2px;border-color:rgba(188,228,255,.9);background:rgba(82,100,112,.86);box-shadow:none}.pan-result-item:focus .pan-result-title{color:#fff}.btn:focus,.chip:focus,.connection-toggle:focus,.detail-style-option:focus,.mini-icon-btn:focus{transform:translateY(-1px);background:rgba(70,85,96,.72);border-color:var(--focus-line);box-shadow:none}.chip.active:focus{background:rgba(82,98,108,.78);border-color:rgba(184,226,255,.8)}.field:focus,input.focusable:focus,textarea.focusable:focus{transform:none;background:rgba(28,38,46,.72);border-color:var(--focus-line);box-shadow:none}.suggest-item:focus{background:rgba(60,76,90,.82);border-color:var(--focus-line);box-shadow:none}.image-content:focus{border-radius:var(--radius);box-shadow:none}.focusable:active,button:active{transform:translateY(1px)}@media (min-width:720px){.app,.sheet{--sheet-x:34px;padding-left:34px;padding-right:34px}.detail-cover{width:min(100%,78vw,960px);max-width:calc(100vw - 68px);height:auto;aspect-ratio:16/9;min-height:180px;max-height:none;margin:14px 0;border-radius:var(--radius)}.grid{grid-template-columns:repeat(4,minmax(0,1fr))}.rail{gap:14px}.card{flex-basis:176px}.media-grid{gap:14px;grid-template-columns:repeat(auto-fill,minmax(132px,1fr))}}@media (min-width:1180px){.app,.sheet{--sheet-x:56px;padding-left:56px;padding-right:56px}.grid{grid-template-columns:repeat(4,minmax(0,1fr))}.media-grid{grid-template-columns:repeat(auto-fill,minmax(156px,1fr))}}html.tv-mode #listStack .media-grid,html.tv-mode #recommendRail,html.tv-mode #searchRail{transform:translateZ(0);backface-visibility:hidden}html.tv-mode #searchRail .card,html.tv-mode .episode-card,html.tv-mode .live-entry-card,html.tv-mode .media-grid .card,html.tv-mode .pan-result-item,html.tv-mode .person-card{will-change:transform;transform:translateZ(0);backface-visibility:hidden}html.tv-mode .card:focus{transform:translateY(-1px) scale(1.025) translateZ(0)}html.tv-mode .episode-card:focus,html.tv-mode .person-card:focus{transform:translateY(-1px) scale(1.03) translateZ(0)}html.tv-mode .media-grid,html.tv-mode .rail{contain:layout style}html.no-layout-gap .search .btn{margin-left:10px!important}html.no-layout-gap .search .icon-btn{margin-left:10px!important}html.no-layout-gap .btn .icon{margin-right:7px}html.no-layout-gap .btn .icon:only-child{margin-right:0}html.no-layout-gap .chips>.chip{margin-right:8px}html.no-layout-gap .chips>.chip:last-child{margin-right:0}html.no-layout-gap .rail>.card,html.no-layout-gap .rail>.episode-card,html.no-layout-gap .rail>.person-card{margin-right:12px}html.no-layout-gap .rail>.card:last-child,html.no-layout-gap .rail>.episode-card:last-child,html.no-layout-gap .rail>.person-card:last-child{margin-right:0}html.no-layout-gap .media-grid{margin:-5px}html.no-layout-gap .media-grid>.card{width:auto;margin:5px}html.no-layout-gap .actions>.btn{margin:0 10px 10px 0}html.no-layout-gap .detail-meta>.meta-pill{margin:0 8px 8px 0}html.no-layout-gap .detail-title-row>*{margin-right:8px}html.no-layout-gap .detail-title-row>:last-child{margin-right:0}html.no-layout-gap .connection-grid>.connection-item,html.no-layout-gap .pan-config>*,html.no-layout-gap .relay-mirror-config>*{margin-top:8px}html.no-layout-gap .connection-body .actions>.btn{margin:4px}html.no-layout-gap .connection-grid>.connection-item:first-child,html.no-layout-gap .pan-config>:first-child,html.no-layout-gap .relay-mirror-config>:first-child{margin-top:0}html.no-layout-gap .connection-item>b{margin-right:8px}html.no-css-functions .connection-body{width:420px;max-width:calc(100vw - 28px)}html.no-layout-gap .pan-disk-grid{margin:-3px}html.no-layout-gap .pan-disk-grid>label{margin:3px}html.no-layout-gap #detailSheet.detail-large .rail>.card,html.no-layout-gap #detailSheet.detail-large .rail>.episode-card,html.no-layout-gap #detailSheet.detail-large .rail>.person-card{margin-right:18px}html.no-layout-gap #detailSheet.detail-large .rail>.card:last-child,html.no-layout-gap #detailSheet.detail-large .rail>.episode-card:last-child,html.no-layout-gap #detailSheet.detail-large .rail>.person-card:last-child{margin-right:0}html.no-layout-gap #detailSheet.detail-large>.actions>.btn{margin-right:16px;margin-bottom:16px}html.no-layout-gap #detailSheet.detail-large .detail-meta>.meta-pill{margin-right:10px;margin-bottom:10px}html.no-aspect-ratio .poster-wrap{position:relative;display:block;height:0;padding-top:150%;overflow:hidden;border-radius:var(--radius) var(--radius) 0 0}html.no-aspect-ratio .poster-wrap .poster{position:absolute;top:0;right:0;bottom:0;left:0;width:100%;max-width:100%;height:100%;margin:0;object-fit:cover;border-radius:inherit}html.no-aspect-ratio .card.landscape-card .poster-wrap{padding-top:56.25%}html.no-aspect-ratio .card.recent-card{height:128px}html.no-aspect-ratio .card.recent-card>.poster{position:absolute;top:0;right:0;bottom:0;left:0;width:100%;max-width:100%;height:100%;margin:0;object-fit:cover;border-radius:inherit}html.no-aspect-ratio .media-grid>.card,html.no-aspect-ratio .rail>.card{overflow:hidden;border-radius:var(--radius)}html.no-aspect-ratio #detailSheet.detail-large .episode-card{height:141px}html.no-aspect-ratio #detailSheet.detail-large .episode-still,html.no-aspect-ratio #detailSheet.detail-large .landscape-card .poster{position:absolute;top:0;right:0;bottom:0;left:0;width:100%;max-width:100%;height:100%;margin:0;object-fit:cover}html.no-aspect-ratio #detailSheet.detail-large .card.landscape-card{height:146px}html.legacy-detail-layout #detailSheet.detail-large,html.no-css-functions #detailSheet.detail-large{--detail-side-pad:64px;--detail-top-pad:56px;padding:56px 64px 54px}html.legacy-detail-layout #detailSheet.detail-large .detail-cover,html.no-css-functions #detailSheet.detail-large .detail-cover{width:870px;height:560px}html.legacy-detail-layout #detailSheet.detail-large .detail-block,html.legacy-detail-layout #detailSheet.detail-large .detail-info,html.legacy-detail-layout #detailSheet.detail-large>.actions,html.no-css-functions #detailSheet.detail-large .detail-block,html.no-css-functions #detailSheet.detail-large .detail-info,html.no-css-functions #detailSheet.detail-large>.actions{max-width:720px}html.legacy-detail-layout #detailSheet.detail-large .detail-info h2,html.no-css-functions #detailSheet.detail-large .detail-info h2{font-size:52px}html.legacy-detail-layout #detailSheet.detail-large .detail-title-meta,html.no-css-functions #detailSheet.detail-large .detail-title-meta{font-size:24px}html.legacy-detail-layout #detailSheet.detail-large .detail-info p,html.no-css-functions #detailSheet.detail-large .detail-info p{font-size:17px}html.legacy-detail-layout #detailSheet.detail-large>.actions .btn,html.no-css-functions #detailSheet.detail-large>.actions .btn{font-size:20px}html.legacy-detail-layout #detailSheet.detail-large #seasonBlock,html.no-css-functions #detailSheet.detail-large #seasonBlock{margin-top:46px}html.legacy-detail-layout #detailSheet.detail-large .detail-block h3,html.no-css-functions #detailSheet.detail-large .detail-block h3{font-size:25px}html.legacy-detail-layout #detailSheet.detail-large #seasonTabs,html.no-css-functions #detailSheet.detail-large #seasonTabs{max-width:720px}html.legacy-detail-layout #detailSheet.detail-large .episode-card,html.no-css-functions #detailSheet.detail-large .episode-card{flex:0 0 250px;max-width:250px;height:141px}html.legacy-detail-layout #detailSheet.detail-large .episode-card b,html.no-css-functions #detailSheet.detail-large .episode-card b{font-size:17px}html.legacy-detail-layout #detailSheet.detail-large .person-card,html.no-css-functions #detailSheet.detail-large .person-card{flex:0 0 280px;max-width:280px}html.legacy-detail-layout #detailSheet.detail-large .person-card b,html.no-css-functions #detailSheet.detail-large .person-card b{font-size:22px}html.legacy-detail-layout #detailSheet.detail-large .person-card span,html.no-css-functions #detailSheet.detail-large .person-card span{font-size:16px}html.legacy-detail-layout #detailSheet.detail-large .card.landscape-card,html.no-css-functions #detailSheet.detail-large .card.landscape-card{flex:0 0 260px;max-width:260px;height:146px}
|
||
</style></head><body><main class="app" id="home"><form class="search" id="searchForm" autocomplete="off"><input class="field focusable" id="searchInput" type="search" inputmode="search" enterkeyhint="search" placeholder="搜索关键词" aria-autocomplete="list" aria-controls="suggestPanel" readonly><button class="btn blue focusable" id="searchSubmitBtn" type="submit"><svg class="icon" viewbox="0 0 24 24"><circle cx="11" cy="11" r="8" /><path d="M21 21l-4.35-4.35" /></svg>搜索</button><button class="icon-btn focusable" id="homeSettingBtn" type="button" aria-label="设置" title="设置"><svg class="icon" viewbox="0 0 24 24" aria-hidden="true"><path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z" /><circle cx="12" cy="12" r="3" /></svg></button><div class="suggest-panel" id="suggestPanel" role="listbox"></div></form><nav class="chips" id="chips"></nav><section class="section" id="searchSection" style="display:none"><div class="section-head"><h3>搜索结果</h3><div class="section-actions"><button class="mini-icon-btn focusable" id="clearSearchBtn" type="button" aria-label="清空搜索结果" title="清空搜索结果"><svg class="icon" viewbox="0 0 24 24"><path d="M18 6 6 18" /><path d="m6 6 12 12" /></svg></button></div></div><div class="rail" id="searchRail"></div></section><section class="section" id="recommendSection"><div class="section-head"><h3>Nostr 推荐</h3><aside class="connection-dock" id="connectionDock"><button class="connection-toggle focusable" id="connectionToggle" type="button" aria-expanded="false" aria-controls="connectionBody"><span class="dot warn" id="connectionDot"></span><span class="connection-title">状态</span><span class="connection-arrow">⌃</span></button><div class="connection-body" id="connectionBody" aria-hidden="true"><div class="connection-grid"><div class="connection-item"><b>App SDK</b><span id="statusSdk">检测中</span></div><div class="connection-item"><b>TMDB</b><span id="statusTmdb">等待请求</span></div><div class="connection-item"><b>Nostr</b><span id="statusNostr">等待连接</span></div><div class="connection-item"><b>盘搜</b><span id="statusPan">未搜索</span></div><div class="connection-item"><b>发布</b><span id="statusPublish">暂无发布</span></div><div class="connection-item"><b>身份</b><span class="mono" id="statusIdentity">未就绪</span></div><div class="connection-item refresh-progress"><b>刷新</b><span id="statusRefresh">未执行</span></div><div class="connection-item"><b>Relays</b><span id="statusRelays">未连接</span></div><div class="connection-item"><b>分级限制</b><div class="detail-style-segmented" id="ratingLimitSegmented" role="group" aria-label="分级限制"><button class="detail-style-option focusable" id="ratingLimitOnBtn" type="button" data-rating-limit="on">开启</button><button class="detail-style-option focusable" id="ratingLimitOffBtn" type="button" data-rating-limit="off">关闭</button></div></div><div class="connection-item"><b>首页全屏</b><div class="detail-style-segmented" id="homeFullscreenSegmented" role="group" aria-label="首页全屏"><button class="detail-style-option focusable" id="homeFullscreenOnBtn" type="button" data-home-fullscreen="on">开启</button><button class="detail-style-option focusable" id="homeFullscreenOffBtn" type="button" data-home-fullscreen="off">关闭</button></div></div><div class="connection-item"><b>高清剧照</b><div class="detail-style-segmented" id="highResBackdropSegmented" role="group" aria-label="高清剧照"><button class="detail-style-option focusable" id="highResBackdropOnBtn" type="button" data-high-res-backdrop="on">开启</button><button class="detail-style-option focusable" id="highResBackdropOffBtn" type="button" data-high-res-backdrop="off">关闭</button></div></div><div class="connection-item"><b>手机详情</b><div class="detail-style-segmented" id="mobileDetailStyleSegmented" role="group" aria-label="手机详情样式"><button class="detail-style-option focusable" id="mobileDetailImmersiveBtn" type="button" data-mobile-detail-style="immersive">沉浸式</button><button class="detail-style-option focusable" id="mobileDetailTranslucentBtn" type="button" data-mobile-detail-style="translucent">半透明</button></div></div></div><div class="pan-config"><label for="tmdbKeyInput">TMDB Key<input class="field focusable mono" id="tmdbKeyInput" type="password" inputmode="text" autocomplete="off" placeholder="TMDB API Key" readonly></label><label for="panBaseInput">盘搜地址<input class="field focusable" id="panBaseInput" type="url" inputmode="url" placeholder="https://so.252035.xyz" readonly></label><label for="panChannelsInput">TG频道<textarea class="field focusable" id="panChannelsInput" rows="2" placeholder="可选,多个频道用逗号或换行分隔" readonly></textarea></label><label for="panUserInput">账号<input class="field focusable" id="panUserInput" autocomplete="username" placeholder="未启用认证可留空" readonly></label><label for="panPassInput">密码<input class="field focusable" id="panPassInput" type="password" autocomplete="current-password" placeholder="未启用认证可留空" readonly></label><div class="pan-disk-grid" id="panDiskGrid"></div><button class="btn focusable" id="savePanConfigBtn" type="button">保存配置</button></div><div class="relay-mirror-config"><label for="mirrorSourceInput">镜像源 Relays<textarea class="field focusable mono" id="mirrorSourceInput" rows="3" placeholder="每行一个源 relay" readonly></textarea></label><label for="mirrorTargetInput">镜像目标 Relays<textarea class="field focusable mono" id="mirrorTargetInput" rows="2" placeholder="每行一个目标 relay,例如 wss://your-relay.example" readonly></textarea></label><div class="relay-mirror-progress mono" id="mirrorProgress">镜像未执行</div><button class="btn focusable" id="mirrorRelayBtn" type="button">镜像榜单</button></div><div class="actions" style="margin-top:10px"><button class="btn focusable" id="refreshNostrBtn" type="button">刷新榜单</button><button class="btn focusable" id="syncBtn" type="button">同步身份</button><button class="btn danger focusable" id="deleteDataBtn" type="button">删除数据</button></div></div></aside></div><div class="block-select-hint" id="blockSelectHint">屏蔽选择模式:按 OK 切换屏蔽,按返回退出</div><div class="media-grid" id="recommendRail"></div></section><section class="section" id="listSection"><div class="stack" id="listStack"><div class="empty">正在加载片单...</div></div></section><div class="infinite-sentinel" id="infiniteSentinel" aria-hidden="true"></div></main><section class="sheet" id="detailSheet" aria-hidden="true"><button class="mobile-detail-back focusable" id="mobileDetailBackBtn" type="button" aria-label="返回"><svg class="icon" viewbox="0 0 24 24"><path d="M19 12H5" /><path d="M12 19l-7-7 7-7" /></svg></button><div class="detail-cover"><img id="detailImage" alt=""></div><div class="detail-info"><div class="detail-title-row"><img class="detail-title-logo" id="detailTitleLogo" alt=""><h2 id="detailTitle"></h2><span class="detail-title-meta" id="detailTitleMeta"></span></div><div class="detail-meta" id="detailMeta"></div><p id="detailText" tabindex="-1"></p><button class="btn link focusable" id="detailMoreBtn" type="button">更多</button></div><div class="actions"><button class="btn primary focusable" id="detailContinueBtn" type="button" style="display:none" aria-hidden="true"><svg class="icon" viewbox="0 0 24 24"><path d="M8 5v14l11-7Z" /></svg><span id="detailContinueText">继续观看</span></button><button class="btn primary focusable" id="detailSearchBtn" type="button"><svg class="icon" viewbox="0 0 24 24"><circle cx="11" cy="11" r="8" /><path d="M21 21l-4.35-4.35" /></svg><span id="detailSearchText">搜索播放</span></button><button class="btn focusable" id="panSearchBtn" type="button"><svg class="icon" viewbox="0 0 24 24"><path d="M6.2 18.3h11.6a4.1 4.1 0 0 0 .42-8.18 6.2 6.2 0 0 0-11.9 1.68A3.28 3.28 0 0 0 6.2 18.3Z" /></svg>盘搜</button></div><div class="detail-block pan-search-block" id="panSearchBlock" style="display:none"><div class="subsection-head"><h4>盘搜资源</h4><span id="panSearchHint"></span></div><div class="chips pan-tabs" id="panTabs"></div><div class="pan-result-list" id="panResultList"></div></div><div class="detail-block" id="seasonBlock" style="display:none"><h3>剧情概要</h3><div class="chips" id="seasonTabs"></div><div class="rail" id="episodeRail"></div></div><div class="detail-block" id="castBlock" style="display:none"><h3>演职员表</h3><div class="rail" id="castRail"></div></div><div class="detail-block" id="personWorkBlock" style="display:none"><h3 id="personWorkTitle">简介</h3><div id="personInfo"></div><h3 style="margin-top:16px">关联作品</h3><div class="rail" id="personWorkRail"></div></div><div class="detail-block" id="recommendBlock" style="display:none"><h3>相关推荐</h3><div class="rail" id="recommendWorkRail"></div></div></section><section class="sheet" id="syncSheet" aria-hidden="true"><button class="btn focusable" id="closeSyncBtn" type="button"><svg class="icon" viewbox="0 0 24 24"><path d="M19 12H5" /><path d="M12 19l-7-7 7-7" /></svg>返回</button><div class="sync-panel" style="margin-top:14px"><h3 style="margin:0">Nostr 同步身份</h3><p class="hint">页面会自动生成本机身份并把有效观看偏好签名发布到 relay。手机和电脑如果想同步同一个用户的推荐,请导入同一个 nsec。只看全网热度时不需要导入。</p><div><label class="hint" for="nsecInput">nsec 私钥</label><textarea class="field focusable mono" id="nsecInput" placeholder="nsec1..."></textarea></div><div class="actions"><button class="btn primary focusable" id="saveNsecBtn" type="button">导入身份</button><button class="btn focusable" id="newNsecBtn" type="button">生成新身份</button></div><p class="hint mono" id="identityText">身份未就绪</p><p class="hint" id="relayText">relay 未连接</p></div></section><section class="image-viewer" id="imageViewer" aria-hidden="true"><button class="mobile-detail-back focusable" id="mobileImageBackBtn" type="button" aria-label="返回"><svg class="icon" viewbox="0 0 24 24"><path d="M19 12H5" /><path d="M12 19l-7-7 7-7" /></svg></button><button class="btn focusable" id="closeImageBtn" type="button"><svg class="icon" viewbox="0 0 24 24"><path d="M19 12H5" /><path d="M12 19l-7-7 7-7" /></svg>返回</button><div class="image-content focusable" id="imageContent" tabindex="0"><img id="viewerImage" alt=""><div class="episode-view" id="episodeViewer" style="display:none"></div></div></section><div class="toast" id="toast"></div><button class="back-top focusable" id="backTopBtn" type="button" aria-label="返回顶部"><svg class="icon" viewbox="0 0 24 24"><path d="M12 19V5" /><path d="M5 12l7-7 7 7" /></svg></button><script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/nostr.bundle.js"></script><script>
|
||
window.WEBHOME_CONFIG={siteKey:"",tmdb:{apiKey:"304ca56b1b7b57ca7a47d9b59946be94",apiBase:"https://api.tmdb.org/3",language:"zh-CN",imageBase:"https://images.tmdb.org/t/p/w342",backdropBase:"https://images.tmdb.org/t/p/w780",lists:[{id:"cn-movie",title:"电影",hint:"大陆电影优先",mediaType:"movie",endpoint:"discover/movie",params:{with_original_language:"zh",with_origin_country:"CN",region:"CN",sort_by:"primary_release_date.desc",primary_release_date_lte:"today",include_adult:"false",include_video:"false",page:"1"}},{id:"cn-tv",title:"剧集",hint:"大陆剧集优先",mediaType:"tv",endpoint:"discover/tv",params:{with_original_language:"zh",with_origin_country:"CN",sort_by:"first_air_date.desc",first_air_date_lte:"today",include_null_first_air_dates:"false",page:"1"}},{id:"western-animation",title:"美漫",hint:"英文动画剧集",mobileHidden:!0,mediaType:"tv",endpoint:"discover/tv",params:{with_genres:"16",with_original_language:"en",sort_by:"first_air_date.desc",first_air_date_lte:"today",include_null_first_air_dates:"false",page:"1"}}]},nostr:{kind:30078,tag:"fish2018-home-v1",eventsKey:"fish2018_home_v1_events",nsecKey:"fish2018_home_v1_nsec",relays:["wss://relay-sgp.signedbyme.com","wss://kotukonostr.onrender.com","wss://nostr.spicyz.io","wss://x.kojira.io","wss://relay.wellorder.net"]},pan:{apiBase:"https://so.252035.xyz",cacheKey:"fish2018_home_v1_pan_config",diskTypes:["quark","aliyun","baidu","uc","tianyi","xunlei","123","115","mobile","pikpak","guangya","magnet","ed2k"],checkableDiskTypes:["quark","aliyun","baidu","uc","tianyi","xunlei","123","115","mobile"],pollIntervals:[4500,9e3]}};const $=e=>document.getElementById(e),DEFAULT_TMDB_API_KEY=String(window.WEBHOME_CONFIG.tmdb.apiKey||"").trim(),PAN_DISK_TYPES=[{id:"quark",name:"夸克"},{id:"aliyun",name:"阿里"},{id:"baidu",name:"百度"},{id:"uc",name:"UC"},{id:"tianyi",name:"天翼"},{id:"xunlei",name:"迅雷"},{id:"123",name:"123"},{id:"115",name:"115"},{id:"mobile",name:"移动"},{id:"pikpak",name:"PikPak"},{id:"guangya",name:"光鸭"},{id:"magnet",name:"磁力"},{id:"ed2k",name:"电驴"}],PAN_CHECKABLE_DISK_TYPES=new Set(window.WEBHOME_CONFIG.pan.checkableDiskTypes||["quark","aliyun","baidu","uc","tianyi","xunlei","123","115","mobile"]),PAN_HEALTH_PRIORITY={ok:0,locked:1,pending:2,idle:3,unsupported:4,uncertain:5,bad:6},PAGE_OPENED_AT=window.WEBHOME_PAGE_OPENED_AT||Date.now(),GRID_INITIAL_ROWS=3,GRID_APPEND_ROWS=2,RECENT_UI_TTL_MS=3e4,DETAIL_TEXT_CLAMP_LIMIT=150,DETAIL_TEXT_CLAMP_LIMIT_LARGE=210,state={site:null,config:null,identity:null,selected:null,detail:null,activeList:"all",catalog:{},catalogPage:{},recent:{items:[],loading:!1,loaded:!1,error:"",refreshedAt:0},pushArtwork:{loaded:!1,items:{}},gridRender:{},gridColumnCache:{},fallback:[],fallbackPage:{sourceIndex:0,page:0,loading:!1,loaded:!1,done:!1},loadingMore:!1,chipFocusTimer:0,railScroll:{},searchItems:[],searchReturnCard:null,searchHold:{timer:0,fired:!1,suppressClickUntil:0,pointer:null,target:null},suggestions:{keyword:"",items:[],loading:!1,timer:0,seq:0,controller:null},hot:{db:null,dbPromise:null,idb:!1,ready:!1,items:[],media:new Map,users:new Map,ingestQueue:Promise.resolve(),refreshTimer:0},relay:{connected:0,published:0,total:0,lastOk:0,lastDone:0,statuses:{},subscribeStarted:!1,subscribeDone:0,subscribeFinished:{},subscribeToken:0,refresh:null,backfillBusy:{},backfillTimers:{},backfillCandidates:{},primaryBackfillRelay:"",fallbackReadyAt:0,fallbackTimer:0,fallbackPrefetchTimer:0},recommendationSource:"pending",status:{sdk:"检测中",tmdb:"等待请求",nostr:"等待连接",pan:"未搜索",publish:"暂无发布",identity:"未就绪",refresh:"未执行"},deleteState:{loaded:!1,users:{}},tmdb:{config:null,configDirty:!1},uiPrefs:{loaded:!1,mobileDetailStyle:"immersive",homeFullscreenEnabled:!0,ratingLimitEnabled:!0,highResBackdropEnabled:!0},autoBlocked:{loaded:!1,items:{},pending:{},queue:[],queued:{},active:0,timer:0,viewportTimer:0,refreshTimer:0,saveTimer:0,version:0},blocked:{loaded:!1,items:{},selecting:!1,holdTimer:0,holdTarget:null,longPressFired:!1,pointer:null,suppressClickUntil:0,saveTimer:0,lastPosition:null,restoring:!1,restoreSeq:0},pan:{config:null,configDirty:!1,loading:!1,keyword:"",activeType:"",results:[],health:{},pending:{},queued:new Map,inFlight:new Set,observer:null,flushTimer:0,pollTimers:[],pollRound:0,viewToken:"",renderKeys:"",tabKeys:"",checkEnabled:!1,focusKey:"",focusMode:"",playbackReturn:null},watch:{item:null,timer:0,bestMs:0,durationMs:0,lastAt:0,published:!1,intentAction:""},detailCover:{images:[],index:0,timer:0,token:0,swipe:null},playbackArtworkPreloadKey:"",episodeViewer:{episodes:[],effectiveIndexes:[],index:-1,episodeNumber:"",swipe:null},episodePreview:{active:!1,expanded:!1,index:-1,episodeNumber:"",lastEpisodeNumber:"",infoHeight:0},deviceMode:"unknown",detailReturn:null,homeReturn:null,focusReturnEl:null,remoteInitialFocused:!1,renderTimer:0,homeContentTimer:0,homeContentSeq:0,activeGridAppendTimer:0,activeGridAppendId:"",focusScrollTimer:0,focusScrollTarget:null,remoteKeyGate:{key:"",at:0},scrollingUntil:0,infiniteObserver:null,scrollLoadTimer:0,resume:{timer:0,lastAt:0}},WATCH_HEAT_MS=6e5,FALLBACK_PREFETCH_MS=1e3,FALLBACK_SHOW_MS=1500,HOT_WINDOW_DAYS=90,HOT_DAY_SECONDS=86400,HOT_WINDOW_SECONDS=7776e3,HOT_WINDOW_MS=7776e6,HOT_DB_NAME="fish2018_home_v1_hot_compact_index",HOT_DB_VERSION=1,HOT_VECTOR_D="heat:user:90d:v2",HOT_VECTOR_VERSION=5,HOT_USER_VECTOR_LIMIT=300,HOT_TITLE_LIMIT=60,HOT_POSTER_LIMIT=96,HOT_PAGE_LIMIT=1e3,HOT_SUBSCRIBE_LIMIT=500,HOT_RECENT_PAGES_PER_RELAY=6,HOT_HISTORY_PAGES_PER_RELAY=10,HOT_BACKFILL_IDLE_MS=650,HOT_BACKFILL_RETRY_MS=3e4,HOT_BACKFILL_RETRY_MAX_MS=3e5,HOT_BACKUP_WINDOW_SECONDS=604800,HOT_REFRESH_IDLE_MS=260,HOT_REFRESH_BACKFILL_MS=900,HOT_PRUNE_BATCH=1e3,HOT_RENDER_LIMIT=1e3,RETURN_CONTEXT_TTL_MS=432e5,UI_SNAPSHOT_TTL_MS=432e5,PAN_PLAYBACK_RETURN_TTL_MS=432e5,DELETE_REPUBLISH_BLOCK_MS=864e5,DELETE_TOMBSTONE_TTL_MS=78624e5,AUTO_BLOCK_SCAN_SCREENS=3,AUTO_BLOCK_SCAN_BATCH=10,AUTO_BLOCK_SCAN_CONCURRENCY=10,AUTO_BLOCK_VIEWPORT_BATCH=32,AUTO_BLOCK_VIEWPORT_CONCURRENCY=32,AUTO_BLOCK_QUEUE_LIMIT=80,AUTO_BLOCK_FAILED_RETRY_MS=216e5;let nativeSdkWait=null;function waitForNativeSdk(e){return window.fm||!window.fongmiBridge?Promise.resolve(!!window.fm):nativeSdkWait||(nativeSdkWait=new Promise(t=>{let n=!1;const a=()=>{n||(n=!0,window.removeEventListener("fmsdk",a),nativeSdkWait=null,t(!!window.fm))};window.addEventListener("fmsdk",a),setTimeout(a,null==e?1500:e)}),nativeSdkWait)}function sdk(){if(window.fm){const e=window.fm.pan||{};return Object.assign({},window.fm,{pan:e,check:e.check||window.fm.check})}const e=async e=>({results:(e||[]).map(e=>({type:e.type,url:e.url,normalized_url:e.url,state:"idle",summary:"浏览器预览不检测",cache_hit:!1,checked_at:Date.now(),expires_at:Date.now()+3e5}))});return{req:browserRequest,res:e=>e,play:async(e,t)=>window.open(e,"_blank","noopener,noreferrer"),search:async e=>toast("原生搜索:"+e),openLive:async()=>toast("请在 App 中打开直播"),openKeep:async()=>toast("请在 App 中打开收藏"),openSetting:async()=>toast("请在 App 中打开设置"),history:async()=>[],vod:async(e,t,n)=>toast("原生播放:"+(n||t||e||"")),preloadArtwork:async()=>{},pan:{check:e,play:async e=>{const t=e||{},n=addPanPassword(String(t.url||""),t.password||"",{diskType:t.type});n&&window.open(n,"_blank","noopener,noreferrer")}},check:e,ui:{setToolbar:async()=>{},setChrome:async()=>{},restoreChrome:async()=>{},getViewport:async()=>({width:innerWidth,height:innerHeight,safeTop:0,safeRight:0,safeBottom:0,safeLeft:0,chromeMode:"normal",systemBarsHidden:!1})},cache:{get:async e=>localStorage.getItem("fm_"+e)||"",set:async(e,t)=>localStorage.setItem("fm_"+e,t),del:async e=>localStorage.removeItem("fm_"+e)},site:async()=>({key:"browser",name:"浏览器预览"}),config:async()=>({id:"browser",url:location.href,driveCheck:!1}),device:async()=>({type:1})}}function isTvMode(){return document.documentElement.classList.contains("tv-mode")}function isNativeMobileClient(){const e=window.fongmiClient||{};return!0===e.isMobile||"mobile"===String(e.mode||"").toLowerCase()}function isNativeLeanbackClient(){const e=window.fongmiClient||{};return!0===e.isLeanback||"leanback"===String(e.mode||"").toLowerCase()}function syncClientModeClasses(){const e=isNativeMobileClient();document.documentElement.classList.toggle("native-mobile-app",e),document.documentElement.classList.toggle("native-phone-app",e&&isPhoneViewport())}function readRootPixel(e){let t="";try{t=getComputedStyle(document.documentElement).getPropertyValue(e)}catch(e){}const n=parseFloat(t);return isNaN(n)?0:n}function shouldUseTopSafeArea(e){if(e=e||{},!isNativeMobileClient())return!1;const t=String(e.chromeMode||"").toLowerCase(),n=isNaN(Number(e.safeTop))?readRootPixel("--fm-safe-top"):Number(e.safeTop),a=isNaN(Number(e.statusBarHeight))?readRootPixel("--fm-status-bar-height"):Number(e.statusBarHeight);return!(e.systemBarsHidden&&n<=0&&a<=0)&&(("edge"===t||"immersive"===t)&&(n>0||a>0))}function updateSafeAreaMode(e){document.documentElement.classList.toggle("safe-top-active",shouldUseTopSafeArea(e||{}))}function refreshSafeAreaMode(){updateSafeAreaMode({});try{const e=sdk().ui||{};if(!e.getViewport)return;e.getViewport().then(e=>updateSafeAreaMode(e||{})).catch(()=>{})}catch(e){}}function setTvMode(e){document.documentElement.classList.toggle("tv-mode",!!e),syncClientModeClasses(),syncNativeToolbarForRoute(),syncConnectionDockPlacement()}function setNativeToolbarVisible(e,t){if(t||isTvMode()||isNativeMobileClient())try{const t=sdk().ui||{};if(isNativeLeanbackClient()&&t.setChrome)return!0===e?void t.setChrome({mode:isHomeFullscreenEnabled()?"edge":"tv-normal"}):void t.setChrome({mode:"tv-full"});if(isNativeMobileClient()&&t.setChrome){const n=!0===e,a=n?isHomeFullscreenEnabled()?"edge":"normal":"immersive";return t.setChrome({mode:a,statusBarStyle:"light",navigationBarStyle:"light",restoreAffordance:n?"auto":"none",startup:n}),void updateSafeAreaMode({chromeMode:a,systemBarsHidden:!n})}t.setToolbar&&t.setToolbar(e)}catch(e){}}function syncNativeToolbarForRoute(){setNativeToolbarVisible("home"===uiSnapshotRoute())}async function detectDeviceMode(){try{window.fongmiBridge&&!window.fm&&await waitForNativeSdk(1500);const e=sdk();if(isNativeLeanbackClient())return state.deviceMode="leanback",setTvMode(!0),!0;if(isNativeMobileClient()&&(state.deviceMode="mobile"),!e.device)return setNativeToolbarVisible(!0,!0),document.documentElement.classList.remove("tv-mode"),syncClientModeClasses(),!1;const t=await e.device(),n=String(t&&t.mode||"").toLowerCase(),a=0===Number(t&&t.type)||"leanback"===n,i=!!(window.fm||window.fongmiBridge||window.fongmiClient);return state.deviceMode=a?"leanback":!i||1!==Number(t&&t.type)&&"mobile"!==n?"browser":"mobile",setTvMode(a),a}catch(e){return setNativeToolbarVisible(!0,!0),document.documentElement.classList.remove("tv-mode"),state.deviceMode=isNativeMobileClient()?"mobile":"browser",syncClientModeClasses(),!1}}function cacheKey(e){return"events"===e?window.WEBHOME_CONFIG.nostr.eventsKey||"fish2018_home_v1_events":"nsec"===e?window.WEBHOME_CONFIG.nostr.nsecKey||"fish2018_home_v1_nsec":"pan"===e?window.WEBHOME_CONFIG.pan.cacheKey||"fish2018_home_v1_pan_config":"ui"===e?"fish2018_home_v1_ui_snapshot":"uiPrefs"===e?"fish2018_home_v1_ui_prefs":"pushArtwork"===e?"fish2018_home_v1_push_artwork":"deleteState"===e?"fish2018_home_v1_delete_state":"blockedRecommend"===e?"fish2018_home_v1_blocked_recommend":"autoBlockedMedia"===e?"fish2018_home_v1_auto_blocked_media":"tmdb"===e?"fish2018_home_v1_tmdb_config":e}function sanitizeUiPrefs(e){const t=e&&"object"==typeof e?e:{};return{mobileDetailStyle:"translucent"===t.mobileDetailStyle?"translucent":"immersive",homeFullscreenEnabled:!1!==t.homeFullscreenEnabled,ratingLimitEnabled:!1!==t.ratingLimitEnabled,highResBackdropEnabled:!1!==t.highResBackdropEnabled}}function isHomeFullscreenEnabled(){return!state.uiPrefs||!1!==state.uiPrefs.homeFullscreenEnabled}function isRatingLimitEnabled(){return!state.uiPrefs||!1!==state.uiPrefs.ratingLimitEnabled}function isHighResBackdropEnabled(){return!state.uiPrefs||!1!==state.uiPrefs.highResBackdropEnabled}function applyUiPrefs(){const e=sanitizeUiPrefs(state.uiPrefs||{});state.uiPrefs=Object.assign({loaded:state.uiPrefs&&state.uiPrefs.loaded},e),document.documentElement.classList.toggle("mobile-detail-translucent","translucent"===e.mobileDetailStyle),renderUiPrefsControls(),syncNativeToolbarForRoute(),$("detailSheet")&&$("detailSheet").classList.contains("active")&&(resetDetailCoverFrame($("detailImage")&&$("detailImage").parentElement),scheduleDetailTextClamp(),updateMobileDetailBackButton())}async function initUiPrefs(e){e=e||{},window.fongmiBridge&&!window.fm&&await waitForNativeSdk(null==e.timeout?1500:e.timeout);let t=null;try{t=safeJson(await sdk().cache.get(cacheKey("uiPrefs")),null)}catch(e){t=null}state.uiPrefs=Object.assign({loaded:!0},sanitizeUiPrefs(t)),applyUiPrefs()}function renderUiPrefsControls(){const e=state.uiPrefs&&"translucent"===state.uiPrefs.mobileDetailStyle?"translucent":"immersive";document.querySelectorAll("[data-mobile-detail-style]").forEach(t=>{const n=t.dataset.mobileDetailStyle===e;t.classList.toggle("active",n),t.setAttribute("aria-pressed",n?"true":"false")});const t=isRatingLimitEnabled()?"on":"off";document.querySelectorAll("[data-rating-limit]").forEach(e=>{const n=e.dataset.ratingLimit===t;e.classList.toggle("active",n),e.setAttribute("aria-pressed",n?"true":"false")});const n=isHomeFullscreenEnabled()?"on":"off";document.querySelectorAll("[data-home-fullscreen]").forEach(e=>{const t=e.dataset.homeFullscreen===n;e.classList.toggle("active",t),e.setAttribute("aria-pressed",t?"true":"false")});const a=isHighResBackdropEnabled()?"on":"off";document.querySelectorAll("[data-high-res-backdrop]").forEach(e=>{const t=e.dataset.highResBackdrop===a;e.classList.toggle("active",t),e.setAttribute("aria-pressed",t?"true":"false")})}async function setMobileDetailStyle(e){const t="translucent"===e?"translucent":"immersive";state.uiPrefs=Object.assign({},sanitizeUiPrefs(state.uiPrefs||{}),{mobileDetailStyle:t,loaded:!0}),applyUiPrefs(),window.fongmiBridge&&!window.fm&&await waitForNativeSdk(1200);try{await sdk().cache.set(cacheKey("uiPrefs"),JSON.stringify(sanitizeUiPrefs(state.uiPrefs)))}catch(e){}toast("translucent"===state.uiPrefs.mobileDetailStyle?"手机详情:半透明背景":"手机详情:全屏沉浸式"),scheduleUiSnapshotSave()}async function setHomeFullscreenEnabled(e){state.uiPrefs=Object.assign({},state.uiPrefs||{},sanitizeUiPrefs(state.uiPrefs||{}),{homeFullscreenEnabled:!1!==e,loaded:!0}),applyUiPrefs(),window.fongmiBridge&&!window.fm&&await waitForNativeSdk(1200);try{await sdk().cache.set(cacheKey("uiPrefs"),JSON.stringify(sanitizeUiPrefs(state.uiPrefs)))}catch(e){}syncNativeToolbarForRoute(),toast(isHomeFullscreenEnabled()?"首页全屏:已开启":"首页全屏:已关闭"),scheduleUiSnapshotSave()}async function setHighResBackdropEnabled(e){state.uiPrefs=Object.assign({},state.uiPrefs||{},sanitizeUiPrefs(state.uiPrefs||{}),{highResBackdropEnabled:!1!==e,loaded:!0}),applyUiPrefs(),window.fongmiBridge&&!window.fm&&await waitForNativeSdk(1200);try{await sdk().cache.set(cacheKey("uiPrefs"),JSON.stringify(sanitizeUiPrefs(state.uiPrefs)))}catch(e){}state.playbackArtworkPreloadKey="",preloadDetailPlaybackArtwork(),toast(isHighResBackdropEnabled()?"高清剧照:已开启":"高清剧照:已关闭"),scheduleUiSnapshotSave()}function refreshRatingLimitedRecommendations(){const e=captureHomePositionSnapshot();state.hot.items=buildHotItemsFromIndex(),"nostr"===state.recommendationSource?"all"===state.activeList&&renderActiveGrid():useNostrRecommendationsIfReady(),restoreHomePositionSnapshot(e),scheduleRender()}async function setRatingLimitEnabled(e){state.uiPrefs=Object.assign({},state.uiPrefs||{},sanitizeUiPrefs(state.uiPrefs||{}),{ratingLimitEnabled:!1!==e,loaded:!0}),applyUiPrefs(),window.fongmiBridge&&!window.fm&&await waitForNativeSdk(1200);try{await sdk().cache.set(cacheKey("uiPrefs"),JSON.stringify(sanitizeUiPrefs(state.uiPrefs)))}catch(e){}isRatingLimitEnabled()||resetAutoBlockScanQueue(),refreshRatingLimitedRecommendations(),isRatingLimitEnabled()&&scheduleAutoBlockViewportScan(80),toast(isRatingLimitEnabled()?"分级限制:已开启":"分级限制:已关闭"),scheduleUiSnapshotSave()}function sanitizeTmdbConfig(e){return{apiKey:String((e&&"object"==typeof e?e:{}).apiKey||"").trim()||DEFAULT_TMDB_API_KEY}}function tmdbApiKey(){return String(window.WEBHOME_CONFIG.tmdb.apiKey||"").trim()||DEFAULT_TMDB_API_KEY}async function initTmdbConfig(e){if(e=e||{},window.fongmiBridge&&!window.fm&&await waitForNativeSdk(null==e.timeout?1500:e.timeout),e.preserveDirty&&state.tmdb.configDirty)return;let t=null;try{t=safeJson(await sdk().cache.get(cacheKey("tmdb")),null)}catch(e){t=null}state.tmdb.config=sanitizeTmdbConfig(t),window.WEBHOME_CONFIG.tmdb.apiKey=state.tmdb.config.apiKey,state.tmdb.configDirty=!1,renderTmdbConfigControls()}function readTmdbConfigControls(){return{apiKey:$("tmdbKeyInput")?$("tmdbKeyInput").value:""}}function renderTmdbConfigControls(){const e=state.tmdb.config||sanitizeTmdbConfig(null);$("tmdbKeyInput")&&($("tmdbKeyInput").value=e.apiKey||DEFAULT_TMDB_API_KEY,disablePanelTextEditing($("tmdbKeyInput")))}function resetTmdbRuntimeAfterConfigChange(){state.catalog={},state.catalogPage={},state.fallback=[],state.fallbackPage={sourceIndex:0,page:0,loading:!1,loaded:!1,done:!1},state.searchItems=[],state.gridRender={},state.recommendationSource="pending",renderSearch(),renderAll({deferContent:!0}),loadCatalog()}function defaultPanConfig(){return{apiBase:window.WEBHOME_CONFIG.pan.apiBase||"https://so.252035.xyz",diskTypes:(window.WEBHOME_CONFIG.pan.diskTypes||[]).slice(),username:"",password:"",token:"",tokenExpiresAt:0,channels:[]}}function normalizePanBase(e){let t=String(e||"").trim()||defaultPanConfig().apiBase;return/^https?:\/\//i.test(t)||(t="https://"+t),t.replace(/\/+$/,"")}function normalizePanDiskType(e){const t=String(e||"").trim().toLowerCase();return"ali"===t||"alipan"===t?"aliyun":"123pan"===t?"123":"139"===t||"caiyun"===t?"mobile":"pikpakdrive"===t?"pikpak":"guangyapan"===t?"guangya":"magnetlink"===t||"magnet:?"===t||"bt"===t?"magnet":"ed2k:"===t?"ed2k":"other"===t?"others":t}function normalizePanChannels(e){const t=Array.isArray(e)?e:String(e||"").split(/[\n,,\s]+/);return Array.from(new Set(t.map(e=>String(e||"").trim()).filter(Boolean)))}function isPanCheckSupported(e){return!(!e||!PAN_CHECKABLE_DISK_TYPES.has(normalizePanDiskType(e.diskType)))}function canCheckPanLinks(){const e=sdk().pan||{};return!(!state.pan.checkEnabled||!e.check)}function sanitizePanConfig(e){const t=defaultPanConfig(),n=e&&"object"==typeof e?e:{},a=new Set(PAN_DISK_TYPES.map(e=>e.id)),i=Array.isArray(n.diskTypes)?n.diskTypes.map(normalizePanDiskType).filter(e=>a.has(e)):t.diskTypes;return{apiBase:normalizePanBase(n.apiBase||t.apiBase),diskTypes:Array.from(new Set(i.length?i:t.diskTypes)),username:String(n.username||"").trim(),password:String(n.password||""),token:String(n.token||""),tokenExpiresAt:Number(n.tokenExpiresAt||0),channels:normalizePanChannels(n.channels||n.tgChannels||n.channel)}}async function initPanConfig(e){if(e=e||{},window.fongmiBridge&&!window.fm&&await waitForNativeSdk(null==e.timeout?1500:e.timeout),e.preserveDirty&&state.pan.configDirty)return;let t=null;try{t=safeJson(await sdk().cache.get(cacheKey("pan")),null)}catch(e){t=null}state.pan.config=sanitizePanConfig(t),state.pan.configDirty=!1,renderPanConfigControls()}async function savePanConfig(){if(window.fongmiBridge&&!window.fm&&await waitForNativeSdk(1500),window.fongmiBridge&&!window.fm)throw new Error("App SDK 未就绪,请稍后再保存");const e=tmdbApiKey();state.tmdb.config=sanitizeTmdbConfig(readTmdbConfigControls()),window.WEBHOME_CONFIG.tmdb.apiKey=state.tmdb.config.apiKey,state.pan.config=sanitizePanConfig(readPanConfigControls()),await sdk().cache.set(cacheKey("tmdb"),JSON.stringify(state.tmdb.config)),await sdk().cache.set(cacheKey("pan"),JSON.stringify(state.pan.config)),renderTmdbConfigControls(),renderPanConfigControls(),state.tmdb.configDirty=!1,state.pan.configDirty=!1,setPanStatus("配置已保存"),closeConnectionPanel(),toast("配置已保存"),e!==tmdbApiKey()&&resetTmdbRuntimeAfterConfigChange()}function readPanConfigControls(){const e=Array.from(document.querySelectorAll("#panDiskGrid input:checked")).map(e=>e.value);return{apiBase:$("panBaseInput")?$("panBaseInput").value:"",username:$("panUserInput")?$("panUserInput").value:"",password:$("panPassInput")?$("panPassInput").value:"",token:state.pan.config&&state.pan.config.token||"",tokenExpiresAt:state.pan.config&&state.pan.config.tokenExpiresAt||0,diskTypes:e,channels:normalizePanChannels($("panChannelsInput")?$("panChannelsInput").value:"")}}function renderPanConfigControls(){const e=state.pan.config||defaultPanConfig();$("panBaseInput")&&($("panBaseInput").value=e.apiBase,disablePanelTextEditing($("panBaseInput"))),$("panChannelsInput")&&($("panChannelsInput").value=(e.channels||[]).join("\n"),disablePanelTextEditing($("panChannelsInput"))),$("panUserInput")&&($("panUserInput").value=e.username||"",disablePanelTextEditing($("panUserInput"))),$("panPassInput")&&($("panPassInput").value=e.password||"",disablePanelTextEditing($("panPassInput")));const t=$("panDiskGrid");if(!t)return;const n=new Set(e.diskTypes||[]);t.replaceChildren(...PAN_DISK_TYPES.map(e=>{const t=document.createElement("label");return t.innerHTML=`<input class="focusable" type="checkbox" value="${escapeAttr(e.id)}" ${n.has(e.id)?"checked":""}><span>${escapeHtml(e.name)}</span>`,t}))}function markPanConfigDirty(e){const t=e&&e.target;t&&"tmdbKeyInput"===t.id?state.tmdb.configDirty=!0:state.pan.configDirty=!0}function panDiskName(e){const t=normalizePanDiskType(e),n=PAN_DISK_TYPES.find(e=>e.id===t);return n?n.name:t||"网盘"}function panApi(e){const t=normalizePanBase((state.pan.config||defaultPanConfig()).apiBase);return t.endsWith("/api")&&e.startsWith("/api/")?t+e.slice(4):t+e}function panSearchDiskTypes(e){const t=(e&&e.diskTypes||[]).map(normalizePanDiskType).filter(Boolean);return Array.from(new Set(t))}function panSearchPayload(e,t){const n={kw:e,res:"merge",src:"all",cloud_types:panSearchDiskTypes(t)},a=normalizePanChannels(t&&t.channels||[]);return a.length&&(n.channels=a),n}async function persistPanConfigQuietly(){try{await sdk().cache.set(cacheKey("pan"),JSON.stringify(state.pan.config||defaultPanConfig()))}catch(e){}}async function ensurePanAuthHeaders(){const e=state.pan.config||defaultPanConfig();if(!e.username||!e.password)return{};if(e.token&&1e3*Number(e.tokenExpiresAt||0)>Date.now()+6e4)return{Authorization:"Bearer "+e.token};const t=await postJson(panApi("/api/auth/login"),{username:e.username,password:e.password},12,{}),n=t&&t.data?t.data:t,a=n&&n.token;if(!a)throw new Error(t&&(t.error||t.message)||"盘搜认证失败");return state.pan.config=sanitizePanConfig(Object.assign({},e,{token:a,tokenExpiresAt:n.expires_at||0})),await persistPanConfigQuietly(),{Authorization:"Bearer "+a}}function openHotDb(){return"indexedDB"in window?state.hot.db?Promise.resolve(state.hot.db):(state.hot.dbPromise||(state.hot.dbPromise=new Promise(e=>{const t=indexedDB.open(HOT_DB_NAME,1);t.onupgradeneeded=()=>{const e=t.result;e.createObjectStore("media",{keyPath:"m"});const n=e.createObjectStore("userVector",{keyPath:"u"});n.createIndex("u","u",{unique:!1}),n.createIndex("e","e",{unique:!1}),n.createIndex("x","x",{unique:!1}),e.createObjectStore("relayCursor",{keyPath:"relay"})},t.onsuccess=()=>{state.hot.db=t.result,state.hot.dbPromise=null,state.hot.idb=!0,e(state.hot.db)},t.onerror=()=>{state.hot.dbPromise=null,e(null)},t.onblocked=()=>setStatus("nostr","本地索引升级等待")})),state.hot.dbPromise):Promise.resolve(null)}function hotWindowStart(){return Math.floor((Date.now()-7776e6)/1e3)}function hotBackupWindowStart(){return Math.max(hotWindowStart(),hotNow()-604800)}function hotNow(){return Math.floor(Date.now()/1e3)}function hotToday(){return Math.floor(hotNow()/86400)}function hotExpiresAt(e){return Number(e||hotNow())+7776e3}function hotExpiresDay(e){return Math.ceil(Number(e||hotNow())/86400)}function hotUserKey(e){return String(e||"").slice(0,32)}function normalizeDeleteState(e){const t=Date.now(),n={};return Object.entries(e&&e.users||{}).forEach(([e,a])=>{const i=String(e||"").trim();if(!i||!a||"object"!=typeof a)return;const s=Number(a.expiresAt||0);s&&s<=t||(n[i]={cutoff:Math.max(0,Number(a.cutoff||0)),blockPublishUntil:Math.max(0,Number(a.blockPublishUntil||0)),expiresAt:s||t+78624e5,updatedAt:Math.max(0,Number(a.updatedAt||0))})}),{loaded:!0,users:n}}async function ensureDeleteStateLoaded(){if(state.deleteState.loaded)return state.deleteState;let e=null;try{e=safeJson(await sdk().cache.get(cacheKey("deleteState")),null)}catch(t){e=null}return state.deleteState=normalizeDeleteState(e),state.deleteState}async function persistDeleteState(){await sdk().cache.set(cacheKey("deleteState"),JSON.stringify({users:state.deleteState.users||{}}))}async function markIdentityDeletedLocally(e){if(!e||!e.pubkey)return null;await ensureDeleteStateLoaded();const t=Date.now(),n={cutoff:hotNow()+1,blockPublishUntil:t+864e5,expiresAt:t+78624e5,updatedAt:t};return state.deleteState.users[e.pubkey]=n,await persistDeleteState().catch(()=>{}),n}function localDeleteMarker(e){const t=state.deleteState.users&&state.deleteState.users[String(e||"")];return t?Number(t.expiresAt||0)&&Number(t.expiresAt||0)<=Date.now()?(delete state.deleteState.users[String(e||"")],persistDeleteState().catch(()=>{}),null):t:null}function isLocallyDeletedPreferenceEvent(e){const t=localDeleteMarker(eventUserKey(e));return!!t&&Number(e&&e.created_at||0)<=Number(t.cutoff||0)}async function isPreferencePublishBlocked(){await ensureDeleteStateLoaded();const e=localDeleteMarker(state.identity&&state.identity.pubkey);return!!(e&&Number(e.blockPublishUntil||0)>Date.now())}function eventExpiration(e){const t=(e&&e.tags||[]).find(e=>e&&"expiration"===e[0]),n=t?Number(t[1]):0;return Number.isFinite(n)?n:0}function eventExpired(e){const t=eventExpiration(e);return t>0&&t<=hotNow()}function idbRequest(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error)})}function idbDone(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onerror=()=>n(e.error),e.onabort=()=>n(e.error)})}async function hotStoreGet(e,t){const n=await openHotDb();return n?idbRequest(n.transaction(e,"readonly").objectStore(e).get(t)).catch(()=>null):null}async function hotLoadIndex(){const e=await openHotDb();if(e){try{const t=e.transaction("media","readonly"),n=await idbRequest(t.objectStore("media").getAll());state.hot.media=new Map((n||[]).filter(e=>e&&e.m).map(e=>[e.m,e])),state.hot.items=buildHotItemsFromIndex(),hotPruneExpired().catch(()=>{}),state.hot.ready=!0}catch(e){state.hot.ready=!0}useNostrRecommendationsIfReady(),scheduleRender()}else state.hot.ready=!0}async function hotIngestEvent(e){const t=await hotIngestEvents([e]);return t&&hotRefreshItems(),t}function hotIngestEvents(e){const t=Array.isArray(e)?e.slice():[],n=()=>hotIngestEventsNow(t).catch(()=>!1);return state.hot.ingestQueue=state.hot.ingestQueue.then(n,n),state.hot.ingestQueue}async function hotIngestEventsNow(e){await ensureDeleteStateLoaded();const t=new Map;for(const n of e||[]){const e=heatVectorFromEvent(n);if(!e)continue;const a=t.get(e.u);a&&!hotIsNewerVector(e,a)||t.set(e.u,e)}if(!t.size)return!1;const n=Array.from(t.values()),a=await openHotDb(),i=await hotGetVectors(n.map(e=>e.u),a),s=new Set,o=[];let r=!1;for(const e of n){const t=i.get(e.u)||(a?null:state.hot.users.get(e.u));if(t&&!hotIsNewerVector(e,t))continue;if(!t&&!e.i.length)continue;hotApplyVectorDiffToState(t,e).forEach(e=>s.add(e)),o.push(e),hotCacheVector(hotPersistVector(e),a),r=!0}if(!r)return!1;if(a){const e=a.transaction(["media","userVector"],"readwrite"),t=e.objectStore("media"),n=e.objectStore("userVector");s.forEach(e=>{const n=state.hot.media.get(e);n&&Number(n.c||0)>0?t.put(n):t.delete(e)}),o.forEach(e=>n.put(hotPersistVector(e))),await idbDone(e).catch(()=>{})}return!0}function heatVectorFromEvent(e){if(eventExpired(e)||getD(e)!==HOT_VECTOR_D)return null;if(isLocallyDeletedPreferenceEvent(e))return null;const t=eventContent(e);if(!t||5!==t.v)return null;const n=eventUserKey(e);if(!n||"local"===n)return null;const a=hotUserKey(n);if(!a)return null;const i=Number(e.created_at||0);if(!Number.isFinite(i)||i<=0)return null;const s=hotExpiresDay(eventExpiration(e)||hotExpiresAt(i));if(s<=hotToday())return null;const o=normalizeWireVectorItems(t.i||[],i),r=o.map(hotStoredVectorItem).filter(Boolean);return{u:a,ts:i,id:e.id||"",e:s,x:hotVectorNextPruneDay(r,s),i:r,meta:o}}function normalizeWireVectorItems(e,t){const n=new Map,a=Math.floor(Number(t||hotNow())/86400);return(Array.isArray(e)?e:[]).forEach(e=>{const t=hotNormalizeWireItem(e,a,!1);if(!t)return;const i=hotVectorItemMediaKey(t),s=n.get(i);(!s||hotVectorItemDay(t)>=hotVectorItemDay(s))&&n.set(i,t)}),Array.from(n.values()).sort((e,t)=>hotVectorItemDay(t)-hotVectorItemDay(e)||hotVectorItemMediaKey(e).localeCompare(hotVectorItemMediaKey(t))).slice(0,300)}function normalizeStoredVectorItems(e,t){const n=new Map,a=Math.floor(Number(t||hotNow())/86400);return(Array.isArray(e)?e:[]).forEach(e=>{const t=hotNormalizeStoredItem(e,a,!1);if(!t)return;const i=hotVectorItemMediaKey(t),s=n.get(i);(!s||hotVectorItemDay(t)>=hotVectorItemDay(s))&&n.set(i,t)}),Array.from(n.values()).sort((e,t)=>hotVectorItemDay(t)-hotVectorItemDay(e)||hotVectorItemMediaKey(e).localeCompare(hotVectorItemMediaKey(t))).slice(0,300)}function hotNormalizeWireItem(e,t,n){const a=hotNormalizeVectorParts(e,t,n);if(!a)return null;const i=String(a.title||"").trim().slice(0,60),s=hotCompactPoster(a.poster||"").slice(0,96);return i&&s?[a.typeCode,a.tmdbId,a.day,i,s]:null}function hotNormalizeStoredItem(e,t,n){const a=hotNormalizeVectorParts(e,t,n);return a?[a.typeCode,a.tmdbId,a.day]:null}function hotNormalizeVectorParts(e,t,n){let a="",i="",s=t,o="",r="";Array.isArray(e)?(a=String(e[0]||""),i=e[1],s=Number(e[2]||t),o=String(e[3]||""),r=String(e[4]||"")):e&&"object"==typeof e&&(a=String(e.mt||e.mediaType||e.c||""),i=e.tid||e.tmdbId||e.id||"",s=Number(e.d||e.day||t),o=String(e.t||e.title||""),r=String(e.p||e.pic||e.poster||""));const c=hotMediaTypeCode(a);if(!c||""===i||null==i||!Number.isFinite(s))return null;const l=Number(i);return i=Number.isInteger(l)&&l>0?l:String(i),s=Math.floor(s),!n&&s<hotMinItemDay()?null:(s>hotToday()&&(s=hotToday()),{typeCode:c,tmdbId:i,day:s,title:o,poster:r})}function hotStoredVectorItem(e){return hotNormalizeStoredItem(e,hotToday(),!0)}function hotPersistVector(e){return{u:e.u,ts:e.ts,id:e.id||"",e:e.e,x:e.x,i:normalizeStoredVectorItems(e.i||[],e.ts||hotNow())}}function hotMediaTypeCode(e){const t=String(e||"");return"t"===t||"tv"===t?"t":"m"===t||"movie"===t?"m":""}function hotMediaTypeFromCode(e){const t=String(e||"");return"t"===t?"tv":"m"===t?"movie":"tv"===t||"movie"===t?t:""}function hotCompactPoster(e){const t=String(e||"").trim();if(!t)return"";if(t.startsWith("/"))return t;const n=[window.WEBHOME_CONFIG.tmdb.imageBase,window.WEBHOME_CONFIG.tmdb.backdropBase].filter(Boolean);for(const e of n)if(t.startsWith(e))return t.slice(e.length)||"";try{const e=new URL(t);if("images.tmdb.org"===e.hostname)return e.pathname.replace(/^\/t\/p\/[^/]+/,"")||e.pathname}catch(e){}return t}function hotPosterUrl(e){const t=String(e||"").trim();return t?/^https?:\/\//i.test(t)?t:t.startsWith("/")?imageUrl(t,!1):t:""}function hotMinItemDay(){return hotToday()-90+1}function hotVectorNextPruneDay(e,t){let n=Number(t||hotToday()+90);return(e||[]).forEach(e=>{n=Math.min(n,hotVectorItemDay(e)+90)}),Math.max(1,Math.floor(n||hotToday()+90))}function hotVectorItemMediaKey(e){const t=hotMediaTypeFromCode(e&&e[0]||""),n=e&&void 0!==e[1]&&null!==e[1]?String(e[1]):"";return t&&n?`tmdb:${t}:${n}`:""}function hotVectorItemDay(e){return Math.floor(Number(e&&e[2]||0))}function hotVectorItemLatest(e){return 86400*hotVectorItemDay(e)}function hotVectorItemMedia(e){const t=hotMediaTypeFromCode(e&&e[0]||""),n=e&&void 0!==e[1]&&null!==e[1]?String(e[1]):"";return{m:hotVectorItemMediaKey(e),t:e&&e[3]||"",mt:t,tid:n,p:hotCompactPoster(e&&e[4]||"")}}function hotVectorItemMap(e){const t=new Map;return(Array.isArray(e)?e:[]).forEach(e=>{const n=hotVectorItemMediaKey(e);if(!n)return;const a=t.get(n);(!a||hotVectorItemDay(e)>=hotVectorItemDay(a))&&t.set(n,e)}),t}function hotActiveVectorItems(e){return normalizeStoredVectorItems(e&&e.i||[],e&&e.ts||hotNow())}function hotVectorHasMedia(e,t){return!(!e||!t)&&hotVectorItemMap(hotActiveVectorItems(e)).has(t)}function hotIsNewerVector(e,t){if(!t)return!0;const n=Number(e&&e.ts||0),a=Number(t&&t.ts||0);return n!==a?n>a:String(e&&e.id||"")>String(t&&t.id||"")}function hotIsLocalUserKey(e){return!(!state.identity||!e||hotUserKey(state.identity.pubkey)!==e)}function hotCacheVector(e,t){e&&e.u&&(!t||hotIsLocalUserKey(e.u)?state.hot.users.set(e.u,e):state.hot.users.delete(e.u))}function hotApplyVectorDiffToState(e,t){const n=hotVectorItemMap(e&&e.i||[]),a=hotVectorItemMap(t&&t.i||[]),i=hotVectorItemMap(t&&t.meta||[]),s=new Set;return n.forEach((e,t)=>{if(a.has(t))return;const n=state.hot.media.get(t);n&&(n.c=Math.max(0,Number(n.c||0)-1),n.c>0?state.hot.media.set(t,n):state.hot.media.delete(t),s.add(t))}),a.forEach((e,t)=>{const a=state.hot.media.get(t),o=n.has(t)&&a?0:1,r=mergeHotMedia(a,hotVectorItemMedia(i.get(t)||e),hotVectorItemLatest(e),o);r.c>0&&r.t&&r.p&&state.hot.media.set(t,r),s.add(t)}),s}function hotGetVectors(e,t){const n=Array.from(new Set((e||[]).filter(Boolean))),a=new Map;return n.length?t?new Promise(e=>{try{const i=t.transaction("userVector","readonly"),s=i.objectStore("userVector");n.forEach(e=>{const t=s.get(e);t.onsuccess=()=>{t.result&&a.set(e,t.result)}}),i.oncomplete=()=>e(a),i.onerror=()=>e(a),i.onabort=()=>e(a)}catch(t){e(a)}}):(n.forEach(e=>{const t=state.hot.users.get(e);t&&a.set(e,t)}),Promise.resolve(a)):Promise.resolve(a)}async function hotGetUserVector(e,t){if(!e)return null;return(await hotGetVectors([e],t||await openHotDb())).get(e)||state.hot.users.get(e)||null}async function hotGetMyVector(){const e=state.identity&&state.identity.pubkey;if(!e)return null;const t=hotUserKey(e),n=await hotGetUserVector(t);return n&&state.hot.users.set(t,n),n}async function hotLoadMyVector(){const e=await hotGetMyVector();return renderMetrics(),e}async function hotPruneExpired(){const e=await openHotDb();if(!e)return;let t=!1;for(;;){const n=await hotGetPrunableVectors(e,hotToday(),1e3);if(!n.length)break;const a=new Set,i=[],s=[];for(const o of n){const n=Number(o&&o.e||0),r=n>hotToday()?normalizeStoredVectorItems(o.i||[],o.ts||hotNow()):[],c=n>hotToday()?Object.assign({},o,{i:r,x:hotVectorNextPruneDay(r,n)}):null;c&&hotSameVectorItems(o.i||[],c.i||[])&&Number(o.x||0)===Number(c.x||0)||(hotApplyVectorDiffToState(o,c).forEach(e=>a.add(e)),c?(i.push(c),hotCacheVector(hotPersistVector(c),e)):(s.push(o.u),state.hot.users.delete(o.u)),t=!0)}if(a.size||i.length||s.length){const t=e.transaction(["media","userVector"],"readwrite"),n=t.objectStore("media"),o=t.objectStore("userVector");a.forEach(e=>{const t=state.hot.media.get(e);t&&Number(t.c||0)>0?n.put(t):n.delete(e)}),i.forEach(e=>o.put(hotPersistVector(e))),s.forEach(e=>o.delete(e)),await idbDone(t).catch(()=>{})}if(n.length<1e3)break}t&&scheduleHotRefresh()}function hotSameVectorItems(e,t){return JSON.stringify(e||[])===JSON.stringify(t||[])}function hotGetPrunableVectors(e,t,n){return new Promise(a=>{const i=[];try{const s=e.transaction("userVector","readonly"),o=s.objectStore("userVector").index("x").openCursor(IDBKeyRange.upperBound(t));o.onsuccess=()=>{const e=o.result;e&&(i.push(e.value),n&&i.length>=n||e.continue())},s.oncomplete=()=>a(i),s.onerror=()=>a(i),s.onabort=()=>a(i)}catch(e){a(i)}})}function hotRefreshItems(){clearTimeout(state.hot.refreshTimer),state.hot.refreshTimer=0,state.hot.items=buildHotItemsFromIndex(),useNostrRecommendationsIfReady(),isNostrRefreshActive()&&(updateNostrRefreshProgress({indexed:state.hot.items.length}),maybeFinishNostrRefresh())}function scheduleHotRefresh(e){clearTimeout(state.hot.refreshTimer);const t=Object.keys(state.relay.backfillBusy||{}).length>0,n=Number.isFinite(e)?e:t?900:260;state.hot.refreshTimer=setTimeout(()=>{state.hot.refreshTimer=0,hotRefreshItems(),scheduleRender()},n)}function mergeHotMedia(e,t,n,a){return{m:t&&t.m||e&&e.m||"",t:t&&t.t||e&&e.t||"",mt:t&&t.mt||e&&e.mt||"",tid:t&&t.tid||e&&e.tid||"",p:t&&hotCompactPoster(t.p)||e&&e.p||"",c:Math.max(0,Number(e&&e.c||0)+Number(a||0)),l:Math.max(Number(e&&e.l||0),Number(n||0))}}function buildHotItemsFromIndex(e){const t=(e||{}).includeBlocked||state.blocked&&state.blocked.selecting;return Array.from(state.hot.media.values()).map(e=>{const t=hotPosterUrl(e.p||""),n=Number(e.c||0);return{id:e.m,mediaKey:e.m,title:e.t||"",mediaType:e.mt||"",tmdbId:e.tid||"",source:"tmdb",pic:t,image:t,people:n,count:n,latest:e.l||0,lastEventAt:e.l||0,remark:""}}).filter(e=>e&&e.people>0&&hasPoster(e)).filter(e=>t||!isAutoBlockedMedia(e)).sort((e,t)=>t.people-e.people||t.lastEventAt-e.lastEventAt).slice(0,1e3)}async function hotClearIndex(e){const t=await openHotDb();if(!t)return state.hot.media.clear(),state.hot.users.clear(),void(state.hot.items=[]);if(!e){const e=t.transaction(["media","userVector","relayCursor"],"readwrite");return e.objectStore("media").clear(),e.objectStore("userVector").clear(),e.objectStore("relayCursor").clear(),await idbDone(e).catch(()=>{}),state.hot.media.clear(),state.hot.users.clear(),void(state.hot.items=[])}const n=state.identity&&state.identity.pubkey;if(!n)return;const a=await hotGetUserVector(hotUserKey(n),t);a&&await hotRemoveVectors([a])}async function hotClearRankingIndexForRefresh(){const e=await openHotDb(),t=state.identity?hotUserKey(state.identity.pubkey):"",n=t?await hotGetUserVector(t,e):null,a=[];if(hotActiveVectorItems(n).forEach(e=>{const t=hotVectorItemMediaKey(e),n=t?state.hot.media.get(t):null;n&&n.m&&a.push(Object.assign({},n,{c:1}))}),await hotClearIndex(!1),n&&n.u&&state.hot.users.set(n.u,n),a.forEach(e=>state.hot.media.set(e.m,e)),e&&(n&&n.u||a.length)){const t=e.transaction(["media","userVector"],"readwrite"),i=t.objectStore("media"),s=t.objectStore("userVector");n&&n.u&&s.put(n),a.forEach(e=>i.put(e)),await idbDone(t).catch(()=>{})}state.hot.items=buildHotItemsFromIndex()}async function hotRemoveVectors(e,t){const n=(e||[]).filter(e=>e&&e.u);if(!n.length)return;const a=await openHotDb(),i=new Set;if(n.forEach(e=>{hotApplyVectorDiffToState(e,null).forEach(e=>i.add(e)),state.hot.users.delete(e.u)}),a){const e=a.transaction(["media","userVector"],"readwrite"),t=e.objectStore("media"),s=e.objectStore("userVector");i.forEach(e=>{const n=state.hot.media.get(e);n&&Number(n.c||0)>0?t.put(n):t.delete(e)}),n.forEach(e=>s.delete(e.u)),await idbDone(e).catch(()=>{})}t&&!1===t.refresh||scheduleHotRefresh()}function setStatus(e,t){state.status[e]=t,renderConnection()}function setPanStatus(e){state.status.pan=e,renderConnection()}function setRefreshStatus(e){state.status.refresh=e||"未执行",renderConnection()}function updateNostrRefreshProgress(e){const t=state.relay.refresh||{};state.relay.refresh=Object.assign({active:!1,phase:"未执行",connected:0,subscribeDone:0,subEvents:0,recentPages:0,recentEvents:0,historyPages:0,historyEvents:0,indexed:0,relay:"",startedAt:0,finishedAt:0},t,e||{});const n=state.relay.refresh,a=window.WEBHOME_CONFIG.nostr.relays,i=n.phase||"刷新中",s=Number(n.connected||state.relay.connected||0),o=Number(n.subscribeDone||state.relay.subscribeDone||0),r=Number(n.subEvents||0),c=Number(n.recentPages||0),l=Number(n.recentEvents||0),d=Number(n.historyPages||0),u=Number(n.historyEvents||0),m=Object.keys(state.relay.backfillBusy||{}).length,p=Object.values(state.relay.backfillTimers||{}).filter(Boolean).length,h=[];"完成"===i?h.push("已完成"):n.active?h.push(`进行中:${i}`):h.push(i),"未执行"!==i&&(h.push(`连接 ${s}/${a.length},订阅完成 ${o}/${a.length}`),h.push(`订阅事件 ${r} 条`),h.push(`近7天回填 ${c} 页 / ${l} 条`),h.push(`历史回填 ${d} 页 / ${u} 条`),n.active&&(m||p)&&h.push(`回填队列 ${m} 个执行中 / ${p} 个等待`),n.active&&state.hot.refreshTimer&&h.push("榜单列表待更新"),n.relay&&h.push(`当前 relay:${n.relay}`)),h.push(`当前榜单 ${state.hot.items.length} 条`),setRefreshStatus(h.join("\n"))}function isNostrRefreshActive(e){const t=state.relay.refresh;return!(!t||!t.active||null!=e&&e!==state.relay.subscribeToken)}function maybeFinishNostrRefresh(e){if(!isNostrRefreshActive(e))return;const t=window.WEBHOME_CONFIG.nostr.relays,n=Object.keys(state.relay.backfillBusy||{}).length,a=Object.values(state.relay.backfillTimers||{}).filter(Boolean).length;state.relay.subscribeDone<t.length||n||a||state.hot.refreshTimer||(updateNostrRefreshProgress({active:!1,phase:"完成",finishedAt:Date.now(),indexed:state.hot.items.length}),toast(`榜单刷新完成:${state.hot.items.length}条`))}function setRelayStatus(e,t){state.relay.statuses[e]=t,renderConnection()}function relayFailedAll(){const e=window.WEBHOME_CONFIG.nostr.relays;return e.filter(e=>{const t=state.relay.statuses[e];return"失败"===t||"断开"===t}).length>=e.length}function nostrReadyForFallback(){const e=window.WEBHOME_CONFIG.nostr.relays;return"fallback"===state.recommendationSource||relayFailedAll()||state.relay.subscribeDone>=e.length||Date.now()>=PAGE_OPENED_AT+1500}function useFallbackRecommendations(){preferenceItems().length?useNostrRecommendationsIfReady():"fallback"!==state.recommendationSource&&(state.recommendationSource="fallback",ensureRecommendationFallback(),"all"===state.activeList&&renderActiveGrid())}function useNostrRecommendationsIfReady(){preferenceItems().length&&(state.recommendationSource="nostr",clearTimeout(state.relay.fallbackTimer),clearTimeout(state.relay.fallbackPrefetchTimer),"all"===state.activeList&&renderActiveGrid())}function finishRelaySubscribe(e,t){if(!state.relay.subscribeFinished[e]){if(state.relay.subscribeFinished[e]=!0,t&&setRelayStatus(e,t),state.relay.subscribeDone+=1,state.relay.subscribeDone>=window.WEBHOME_CONFIG.nostr.relays.length){const e=choosePrimaryBackfillRelay(!0);e&&scheduleRelayBackfill(e),0===preferenceItems().length&&(setStatus("nostr",relayFailedAll()?"连接失败":"无推荐数据"),useFallbackRecommendations())}"all"===state.activeList&&renderActiveGrid()}}function renderConnection(){if(!$("connectionDot"))return;const e=window.WEBHOME_CONFIG.nostr.relays,t=e.map(e=>`${shortRelay(e)} ${state.relay.statuses[e]||"等待"}`),n=Object.values(state.relay.statuses).filter(e=>"已连接"===e).length,a=Object.values(state.relay.statuses).filter(e=>"失败"===e||"断开"===e).length,i=(state.status.tmdb.includes("成功")||state.status.tmdb.includes("完成"),n>0),s=state.status.tmdb.includes("失败")||!i&&a===e.length;$("statusSdk").textContent=state.status.sdk,$("statusTmdb").textContent=state.status.tmdb,$("statusNostr").textContent=`${state.status.nostr} (${n}/${e.length})`,$("statusPan")&&($("statusPan").textContent=state.status.pan||"未搜索"),$("statusPublish").textContent=state.status.publish,$("statusIdentity").textContent=state.status.identity,$("statusRefresh")&&($("statusRefresh").textContent=state.status.refresh||"未执行"),$("statusRelays").textContent=t.join(" · "),$("refreshNostrBtn")&&($("refreshNostrBtn").textContent=state.relay.refresh&&state.relay.refresh.active?"刷新中":"刷新榜单"),renderUiPrefsControls(),$("connectionDot").className="dot "+(i?"ok":s?"bad":"warn"),fitConnectionPanel()}function fitConnectionPanel(){const e=$("connectionDock"),t=$("connectionBody");if(!e||!t)return;t.style.setProperty("--connection-shift","0px");const n=connectionPanelWidth();n&&(t.style.width=`${n}px`),e.classList.contains("open")&&requestAnimationFrame(()=>{const e=t.getBoundingClientRect();let n=0;e.left<8&&(n=8-e.left),e.right+n>window.innerWidth-8&&(n=window.innerWidth-8-e.right),t.style.setProperty("--connection-shift",`${Math.round(n)}px`)})}function connectionPanelWidth(){const e=Math.min(window.innerWidth||0,document.documentElement&&document.documentElement.clientWidth||0)||window.innerWidth||document.documentElement&&document.documentElement.clientWidth||0;return e?Math.round(Math.min(420,Math.max(220,e-28))):420}function setConnectionPanelOpen(e){const t=$("connectionDock"),n=$("connectionBody"),a=$("connectionToggle");t&&n&&(t.classList.toggle("open",!!e),n.classList.toggle("open",!!e),a&&a.setAttribute("aria-expanded",e?"true":"false"),n.setAttribute("aria-hidden",e?"false":"true"),e?disableConnectionTextEditing():n.contains(document.activeElement)&&a&&requestAnimationFrame(()=>focusRemoteTarget(a)),fitConnectionPanel(),scheduleUiSnapshotSave())}function toggleConnectionPanel(e){e&&(e.preventDefault(),e.stopPropagation()),setConnectionPanelOpen(!$("connectionDock").classList.contains("open"))}function clearRelayBackfillTimers(){Object.values(state.relay.backfillTimers).forEach(e=>clearTimeout(e)),state.relay.backfillTimers={},clearTimeout(state.hot.refreshTimer),state.hot.refreshTimer=0}function resetRelaySubscribeState(){return Object.values(state.relay.backfillTimers||{}).forEach(e=>clearTimeout(e)),state.relay.connected=0,state.relay.subscribeDone=0,state.relay.subscribeFinished={},state.relay.statuses={},state.relay.backfillBusy={},state.relay.backfillTimers={},state.relay.backfillCandidates={},state.relay.primaryBackfillRelay="",++state.relay.subscribeToken}function closeConnectionPanel(){setConnectionPanelOpen(!1)}function shortRelay(e){return String(e||"").replace(/^wss?:\/\//,"").replace(/\/$/,"")}async function browserRequest(e,t){const n=t||{};try{const t=await fetch(e,{method:n.method||"GET",headers:n.headers||{},body:n.method&&"GET"!==n.method&&"HEAD"!==n.method?n.body||"":void 0,credentials:"include"===n.credentials?"include":"same-origin"}),a={};t.headers.forEach((e,t)=>a[t]=e);const i="json"===n.responseType?await t.json():await t.text();return{ok:t.ok,status:t.status,url:t.url,headers:a,body:i}}catch(e){throw e}}async function requestJson(e,t){const n=await sdk().req(e,{responseType:"text",timeout:t||18});if(n&&n.error)throw new Error(n.error);const a=n&&n.body;return"string"==typeof a?JSON.parse(a||"{}"):a||{}}async function postJson(e,t,n,a){const i=await sdk().req(e,{method:"POST",responseType:"text",timeout:n||24,headers:Object.assign({"Content-Type":"application/json"},a||{}),body:JSON.stringify(t||{})});if(i&&i.error)throw new Error(i.error);if(i&&!1===i.ok)throw new Error("HTTP "+(i.status||0));const s=i&&i.body,o="string"==typeof s?JSON.parse(s||"{}"):s||{};if(o&&o.code&&0!==Number(o.code)&&200!==Number(o.code))throw new Error(o.message||o.error||"HTTP "+o.code);return o}function today(){const e=new Date;return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")}`}function tmdbUrl(e,t){const n=new URL(`${window.WEBHOME_CONFIG.tmdb.apiBase}/${e.endpoint}`);return n.searchParams.set("api_key",tmdbApiKey()),n.searchParams.set("language",window.WEBHOME_CONFIG.tmdb.language),Object.entries(e.params||{}).forEach(([e,t])=>{const a=e.replace(/_lte$/,".lte");n.searchParams.set(a,"today"===t?today():t)}),t&&n.searchParams.set("page",String(t)),n.toString()}function tmdbFallbackUrl(e,t){const n="airing"===e?"tv/airing_today":"trending/all/day",a=new URL(`${window.WEBHOME_CONFIG.tmdb.apiBase}/${n}`);return a.searchParams.set("api_key",tmdbApiKey()),a.searchParams.set("language",window.WEBHOME_CONFIG.tmdb.language),a.searchParams.set("page",String(t||1)),a.toString()}function tmdbSearchUrl(e){const t=new URL(`${window.WEBHOME_CONFIG.tmdb.apiBase}/search/multi`);return t.searchParams.set("api_key",tmdbApiKey()),t.searchParams.set("language",window.WEBHOME_CONFIG.tmdb.language),t.searchParams.set("query",e),t.searchParams.set("include_adult","false"),t.searchParams.set("page","1"),t.toString()}function suggestUrl(e){const t=new URL("https://suggest.video.iqiyi.com/");return t.searchParams.set("if","mobile"),t.searchParams.set("key",e),t.toString()}function tmdbDetailUrl(e){const t=new URL(`${window.WEBHOME_CONFIG.tmdb.apiBase}/${e.mediaType}/${e.tmdbId}`);return t.searchParams.set("api_key",tmdbApiKey()),t.searchParams.set("language",window.WEBHOME_CONFIG.tmdb.language),t.searchParams.set("append_to_response","tv"===e.mediaType?"credits,images,season/1":"credits,images"),t.searchParams.set("include_image_language","zh,null,en"),t.toString()}function tmdbAutoBlockUrl(e){const t=e&&"tv"===e.mediaType?"tv":"movie",n=new URL(`${window.WEBHOME_CONFIG.tmdb.apiBase}/${t}/${e.tmdbId}`);return n.searchParams.set("api_key",tmdbApiKey()),n.searchParams.set("language",window.WEBHOME_CONFIG.tmdb.language),n.searchParams.set("append_to_response","tv"===t?"content_ratings":"release_dates"),n.toString()}function tmdbRecommendationsUrl(e){const t=new URL(`${window.WEBHOME_CONFIG.tmdb.apiBase}/${e.mediaType}/${e.tmdbId}/recommendations`);return t.searchParams.set("api_key",tmdbApiKey()),t.searchParams.set("language",window.WEBHOME_CONFIG.tmdb.language),t.searchParams.set("page","1"),t.toString()}function tmdbSeasonUrl(e,t){const n=new URL(`${window.WEBHOME_CONFIG.tmdb.apiBase}/tv/${e.tmdbId}/season/${t}`);return n.searchParams.set("api_key",tmdbApiKey()),n.searchParams.set("language",window.WEBHOME_CONFIG.tmdb.language),n.toString()}function tmdbPersonUrl(e){const t=new URL(`${window.WEBHOME_CONFIG.tmdb.apiBase}/person/${e}/combined_credits`);return t.searchParams.set("api_key",tmdbApiKey()),t.searchParams.set("language",window.WEBHOME_CONFIG.tmdb.language),t.toString()}function tmdbPersonDetailUrl(e){const t=new URL(`${window.WEBHOME_CONFIG.tmdb.apiBase}/person/${e}`);return t.searchParams.set("api_key",tmdbApiKey()),t.searchParams.set("language",window.WEBHOME_CONFIG.tmdb.language),t.searchParams.set("append_to_response","combined_credits"),t.toString()}function imageUrl(e,t){return e?(t?window.WEBHOME_CONFIG.tmdb.backdropBase:window.WEBHOME_CONFIG.tmdb.imageBase)+e:""}function tmdbImageUrl(e,t){if(!e)return"";const n=String(e||"").trim(),a=n.startsWith("/")?n:tmdbImagePath(n);return a?`https://images.tmdb.org/t/p/${t||"w342"}${a}`:n}function tmdbImagePath(e){const t=String(e||"").trim();if(!t)return"";if(t.startsWith("/"))return t;try{const e=new URL(t);return"images.tmdb.org"!==e.hostname?"":e.pathname.replace(/^\/t\/p\/[^/]+/,"")||""}catch(e){return""}}function isTmdbImage(e){return!!tmdbImagePath(e)}function displayImage(e,t){if(!e)return"";const n=t||{},a=tmdbImagePath(e);return a?tmdbImageUrl(a,n.size||"w342"):nativeImage(e)}function playbackImage(e){const t=String(e||"").trim();if(!t)return"";const n=tmdbImagePath(t);return n?tmdbImageUrl(n,isHighResBackdropEnabled()?"original":"w780"):t}function nativeImage(e){if(!e)return"";if(isTmdbImage(e))return e;try{return sdk().res(e,{credentials:"include"})}catch(t){return e}}function imageAttrs(e,t){const n=t||{},a=n.loading||"lazy",i=n.fetchPriority?` fetchpriority="${escapeAttr(n.fetchPriority)}"`:"";return`src="${escapeAttr(e)}" loading="${escapeAttr(a)}" decoding="async"${i}`}function normalizeTmdb(e,t,n){const a=e.title||e.name||e.original_title||e.original_name||"未命名",i=e.release_date||e.first_air_date||"",s=t.mediaType||e.media_type||"movie";return{id:`tmdb:${s}:${e.id}`,source:"tmdb",tmdbId:String(e.id),mediaType:s,listId:t.id||"search",listTitle:t.title||"搜索",title:a,pic:imageUrl(e.poster_path,!1),landscape:imageUrl(e.backdrop_path,!0),image:imageUrl(e.backdrop_path,!0)||imageUrl(e.poster_path,!1),remark:"",desc:e.overview||`${t.title||"搜索"} · ${a}`,releaseDate:i,popularity:e.popularity||0,voteAverage:e.vote_average||0,baseRank:n+1}}function historyKeyParts(e){const t=String(e&&e.key||""),n=t.split("@@@");return{key:t,siteKey:e&&e.siteKey||n[0]||"",vodId:e&&e.vodId||n[1]||""}}function pushArtworkKey(e){let t=String(e||"").trim();return/^push:\/\//i.test(t)&&(t=t.replace(/^push:\/\//i,"")),t}function pushArtworkFor(e,t){const n=state.pushArtwork&&state.pushArtwork.items||{},a=pushArtworkKey(e),i=a&&n[a];if(i)return i;const s=normalizeTitle(t||"");return s&&Object.values(n).find(e=>e&&normalizeTitle(e.title||"")===s)||null}async function loadPushArtworkCache(){if(state.pushArtwork&&state.pushArtwork.loaded)return;let e=null;try{e=safeJson(await sdk().cache.get(cacheKey("pushArtwork")),null)}catch(t){e=null}state.pushArtwork={loaded:!0,items:e&&e.items&&"object"==typeof e.items?e.items:{}}}async function savePushArtwork(e){if(!e||!e.url)return;await loadPushArtworkCache();const t=pushArtworkKey(e.url);if(!t)return;const n=Object.assign({},state.pushArtwork.items||{});n[t]={title:e.title||"",pic:e.pic||"",wallPic:e.wallPic||"",at:Date.now()};const a=Object.keys(n).sort((e,t)=>Number(n[t]&&n[t].at||0)-Number(n[e]&&n[e].at||0)),i={};a.slice(0,120).forEach(e=>{i[e]=n[e]}),state.pushArtwork={loaded:!0,items:i};try{await sdk().cache.set(cacheKey("pushArtwork"),JSON.stringify({version:1,items:i}))}catch(e){}}function validHistoryMs(e){const t=Number(e||0);return Number.isFinite(t)&&t>0&&t<6048e5?t:0}function isRestorableHistory(e){const t=historyKeyParts(e),n=String(e&&(e.vodName||e.title||e.name)||"").trim(),a="push_agent"===t.siteKey?pushArtworkFor(t.vodId,n):null,i=String("push_agent"===t.siteKey?a&&a.pic||e&&(e.vodPic||e.pic||"")||"":e&&(e.vodPic||e.pic||"")||"").trim();return!!(t.siteKey&&t.vodId&&n)&&("push_agent"===t.siteKey?!!i&&!isExpiredPosterSource(i,t):!/^(push|https?|file|magnet|ed2k|thunder|video):/i.test(t.siteKey))}function isExpiredHistory(e){const t=historyKeyParts(e);if(!isRestorableHistory(e))return!0;if(isExpiredPosterSource(String(e&&(e.vodPic||e.pic||"")||"").trim(),t))return!0;const n=[e&&e.vodRemarks,e&&e.remark,e&&e.desc,e&&e.status,e&&e.summary,e&&e.episodeUrl].filter(Boolean).join(" ").toLowerCase();if(/(已过期|已失效|链接失效|资源失效|分享已取消|取消分享|文件不存在|内容不存在|资源不存在|不存在|被删除|已删除|违规|notfound|not found|expired|invalid|forbidden|cancelled|canceled|shareexpirederror|sharenotfound|shareinfonotfound|filenotfound|foldernotfound)/i.test(n))return!0;const a=String(e&&(e.vodName||e.title||e.name)||"").trim();return/^(已过期|已失效|链接失效|资源失效|文件不存在|内容不存在|资源不存在|不存在)$/.test(a)}function isExpiredPosterSource(e,t){const n=String(e||"").trim();if(!n)return!1;const a=n.slice(0,500).toLowerCase();return!!/(已过期|已失效|链接失效|资源失效|expired|notfound|not-found|invalid|forbidden)/i.test(a)||(!(!t||"push_agent"!==t.siteKey||!/^data:image\//i.test(n))||/^data:image\/jpeg;base64,\/9j\/4AAQSkZJRgABAQEAYABgAAD\/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQo/i.test(n))}function formatHistoryTime(e){const t=Math.max(0,Math.floor(Number(e||0)/1e3)),n=Math.floor(t/3600),a=Math.floor(t%3600/60),i=t%60;return n>0?n+":"+String(a).padStart(2,"0")+":"+String(i).padStart(2,"0"):a+":"+String(i).padStart(2,"0")}function historyProgressText(e){const t=validHistoryMs(e&&e.position),n=validHistoryMs(e&&e.duration);return n>0&&t>0?"已看 "+Math.min(99,Math.max(1,Math.round(t/n*100)))+"%":t>0?"看到 "+formatHistoryTime(t):""}function historyProgressPercent(e){const t=validHistoryMs(e&&e.position),n=validHistoryMs(e&&e.duration);return n<=0||t<=0?0:Math.min(100,Math.max(1,Math.round(t/n*100)))}function normalizeHistoryItem(e,t){const n=historyKeyParts(e),a=String(e&&(e.vodName||e.title||e.name)||"最近观看").trim(),i="push_agent"===n.siteKey?pushArtworkFor(n.vodId,a):null,s="push_agent"===n.siteKey?i&&i.pic||e&&(e.vodPic||e.pic||"")||"":e&&(e.vodPic||e.pic||"")||"",o=findMediaByContent({title:a,vodId:n.vodId})||null,r=i&&i.wallPic||playbackWallPic(Object.assign({},o||{},{title:a,pic:s})),c=String(e&&e.vodRemarks||"").trim(),l=historyProgressText(e);return{id:"history:"+(n.key||t),source:"history",historyKey:n.key,siteKey:n.siteKey,vodId:n.vodId,title:a,pic:s,image:s,landscape:r||o&&o.landscape||"",wallPic:r,remark:l||(c?"继续观看":""),badge:c,progress:historyProgressPercent(e),desc:[c,l].filter(Boolean).join(" · ")||a,releaseDate:"",voteAverage:0,popularity:Number(e&&e.createTime||0),baseRank:t+1,createTime:Number(e&&e.createTime||0)}}function normalizeHistoryList(e){const t=new Set;return(Array.isArray(e)?e:[]).slice().sort((e,t)=>Number(t&&t.createTime||0)-Number(e&&e.createTime||0)).filter(e=>!isExpiredHistory(e)).map(normalizeHistoryItem).filter(e=>{const n=e.historyKey||(e.siteKey&&e.vodId?e.siteKey+"@@@"+e.vodId:e.title);return!(!n||t.has(n))&&(t.add(n),!0)})}function detailHistoryTitleCandidates(e){return[e&&e.title,e&&e.name,e&&e.query,e&&e.originalTitle,e&&e.original_name,e&&e.original_title].map(normalizeTitle).filter(Boolean)}function detailHistoryVodIdMatchesTmdb(e,t){const n=String(e||"").trim(),a=String(t||"").trim();return!(!n||!a)&&(a===n||!(!/tmdb/i.test(a)||!a.split(/[^a-z0-9]+/i).includes(n)))}function detailHistoryMatches(e,t){if(!(e&&t&&"history"===t.source&&t.siteKey&&t.vodId))return!1;if(detailHistoryVodIdMatchesTmdb(e.tmdbId?String(e.tmdbId):e.id&&/^tmdb:/i.test(String(e.id))?String(e.id).split(":").pop():"",t.vodId))return!0;const n=normalizeTitle(t.title||"");return!!n&&detailHistoryTitleCandidates(e).some(e=>!!e&&(e===n||e.length>=4&&n.length>=4&&(e.includes(n)||n.includes(e))))}function findDetailContinueHistory(e){return(state.recent.items||[]).find(t=>detailHistoryMatches(e,t))||null}function updateDetailContinueButton(){const e=$("detailContinueBtn"),t=$("detailSearchText");if(!e)return;const n=findDetailContinueHistory(state.selected),a=e.closest(".actions");e.__historyItem=n||null,e.style.display=n?"":"none",e.setAttribute("aria-hidden",n?"false":"true"),a&&a.classList.toggle("has-continue",!!n),t&&(t.textContent=n?"搜索":"搜索播放"),preloadDetailPlaybackArtwork()}function shouldRefreshRecentList(){return!state.recent.loaded||Date.now()-Number(state.recent.refreshedAt||0)>3e4}async function loadRecentList(e){const t=e||{};if(!state.recent.loading&&(!state.recent.loaded||t.refresh)){state.recent.loading=!0,state.recent.error="",t.silent||setStatus("tmdb","读取最近观看"),"recent"===state.activeList&&renderActiveGrid();try{await loadPushArtworkCache();const e=await sdk().history();state.recent.items=normalizeHistoryList(e),state.recent.loaded=!0,state.recent.refreshedAt=Date.now(),t.silent||setStatus("tmdb","最近观看 "+state.recent.items.length+" 条")}catch(e){state.recent.items=[],state.recent.loaded=!0,state.recent.error=e.message||"unknown",t.silent||setStatus("tmdb","最近观看读取失败")}finally{state.recent.loading=!1,"recent"===state.activeList&&renderActiveGrid(),$("detailSheet")&&$("detailSheet").classList.contains("active")&&updateDetailContinueButton()}}}async function loadInfo(){try{await detectDeviceMode(),state.site=await sdk().site(),state.config=await sdk().config(),state.pan.checkEnabled=!(!state.config||!state.config.driveCheck),setStatus("sdk",window.fm?"App SDK 已连接":"浏览器预览模式"),setPanStatus(state.pan.checkEnabled?"检测已开启":"检测关闭"),state.pan.renderKeys="",renderPanResults()}catch(e){state.site={name:"推荐首页"},state.pan.checkEnabled=!1,setStatus("sdk","SDK 获取失败:"+(e.message||"unknown"))}}async function loadCatalog(){setStatus("tmdb","等待按需请求"),loadRecentList({silent:!0}).catch(()=>{}),renderAll({deferContent:!0})}function prefetchRecommendationFallback(){preferenceItems().length?useNostrRecommendationsIfReady():state.fallbackPage.loading||state.fallbackPage.loaded||state.fallbackPage.done||loadRecommendationFallback().catch(e=>{state.fallbackPage.loading=!1,state.fallbackPage.loaded=!0,state.fallbackPage.done=!0,setStatus("tmdb","推荐加载失败"),"fallback"===state.recommendationSource&&renderActiveGrid()})}function ensureRecommendationFallback(){nostrReadyForFallback()&&prefetchRecommendationFallback()}function armFallbackTimers(){clearTimeout(state.relay.fallbackTimer),clearTimeout(state.relay.fallbackPrefetchTimer);const e=Date.now()-PAGE_OPENED_AT;state.relay.fallbackPrefetchTimer=setTimeout(()=>{preferenceItems().length||prefetchRecommendationFallback()},Math.max(0,1e3-e)),state.relay.fallbackTimer=setTimeout(()=>{preferenceItems().length||useFallbackRecommendations()},Math.max(0,1500-e))}async function loadCatalogList(e){const t=getList(e),n=state.catalogPage[e];if(!(!t||n&&n.loading||n&&n.loaded)){state.catalogPage[e]={page:0,total:1,loading:!0,loaded:!1},setStatus("tmdb",`请求 ${t.title}`),state.activeList===e&&renderActiveGrid();try{const n=await requestJson(tmdbUrl(t,1),18),a=n.results||[];state.catalog[e]=uniqueMedia(a.map((e,n)=>normalizeTmdb(e,t,n)).filter(hasPoster)),state.catalogPage[e]={page:1,total:n.total_pages||1,loading:!1,loaded:!0},setStatus("tmdb",`${t.title} 已加载 ${state.catalog[e].length} 条`)}catch(n){state.catalog[e]=[],state.catalogPage[e]={page:1,total:1,loading:!1,loaded:!0,error:n.message||"unknown"},setStatus("tmdb",`${t.title} 加载失败`)}state.activeList===e&&renderActiveGrid()}}async function loadRecommendationFallback(){const e=[{type:"trending",id:"tmdb-trending",title:"今日趋势"},{type:"airing",id:"tv-airing-today",title:"今日播出",mediaType:"tv"}];if(preferenceItems().length)useNostrRecommendationsIfReady();else{state.fallback=[],state.fallbackPage={sourceIndex:0,page:0,loading:!0,loaded:!1,done:!1},setStatus("tmdb","请求推荐兜底"),"fallback"===state.recommendationSource&&renderActiveGrid();for(let t=0;t<e.length;t++){const n=e[t];try{const e=await requestJson(tmdbFallbackUrl(n.type,1),18),a=(e.results||[]).filter(e=>e.poster_path&&("movie"===e.media_type||"tv"===e.media_type||n.mediaType)).map((e,t)=>normalizeTmdb(e,n,t)).filter(hasPoster);if(preferenceItems().length)return void useNostrRecommendationsIfReady();if(a.length)return state.fallback=uniqueMedia(a),state.fallbackPage={sourceIndex:t,page:1,total:e.total_pages||1,loading:!1,loaded:!0,done:!1},setStatus("tmdb","推荐兜底已加载"),void("fallback"===state.recommendationSource&&renderActiveGrid())}catch(e){}}state.fallback=ranked(allItems()),state.fallbackPage.loaded=!0,state.fallbackPage.loading=!1,state.fallbackPage.done=!0,setStatus("tmdb",state.fallback.length?"本地兜底已加载":"推荐为空"),"fallback"===state.recommendationSource&&renderActiveGrid()}}async function loadMoreCatalog(e){const t=getList(e),n=state.catalogPage[e];if(!n||!n.loaded)return loadCatalogList(e);if(!(!t||n.loading||n.page>=n.total)){n.loading=!0,state.catalogPage[e]=n;try{const a=n.page+1,i=await requestJson(tmdbUrl(t,a),18),s=(i.results||[]).map((e,n)=>normalizeTmdb(e,t,20*(a-1)+n)).filter(hasPoster);state.catalog[e]=uniqueMedia((state.catalog[e]||[]).concat(s)),state.catalogPage[e]={page:a,total:i.total_pages||n.total||a,loading:!1,loaded:!0},renderActiveGrid()}catch(e){n.loading=!1}}}async function loadMoreFallback(){const e=[{type:"trending",id:"tmdb-trending",title:"今日趋势"},{type:"airing",id:"tv-airing-today",title:"今日播出",mediaType:"tv"}];if(preferenceItems().length)return void useNostrRecommendationsIfReady();const t=state.fallbackPage;if(t.loading||t.done)return;const n=e[t.sourceIndex]||e[0];if(t.total&&t.page>=t.total)t.done=!0;else{t.loading=!0;try{const e=t.page+1,a=await requestJson(tmdbFallbackUrl(n.type,e),18),i=(a.results||[]).filter(e=>e.poster_path&&("movie"===e.media_type||"tv"===e.media_type||n.mediaType)).map((t,a)=>normalizeTmdb(t,n,20*(e-1)+a)).filter(hasPoster);state.fallback=uniqueMedia(state.fallback.concat(i)),state.fallbackPage={sourceIndex:t.sourceIndex,page:e,total:a.total_pages||t.total||e,loading:!1,loaded:!0,done:!i.length},renderActiveGrid()}catch(e){t.loading=!1}}}function loadMoreVisible(){if(!appendActiveGridBatch()&&!state.loadingMore&&"recent"!==state.activeList&&"live"!==state.activeList){if("all"===state.activeList){if(preferenceItems().length)return void useNostrRecommendationsIfReady();if(!nostrReadyForFallback())return;state.recommendationSource="fallback"}state.infiniteObserver&&state.infiniteObserver.unobserve($("infiniteSentinel")),state.loadingMore=!0,Promise.resolve("all"===state.activeList?loadMoreFallback():loadMoreCatalog(state.activeList)).finally(()=>{state.loadingMore=!1,observeInfiniteScroll()})}}async function loadEvents(){try{await sdk().cache.del(cacheKey("events"))}catch(e){}scheduleRender()}async function clearLocalEvents(e){await sdk().cache.del(cacheKey("events")),await hotClearIndex(e),scheduleRender()}async function forceRefreshNostrRanking(){if(forceRefreshNostrRanking.busy)return;forceRefreshNostrRanking.busy=!0;const e=$("refreshNostrBtn");e&&e.textContent;e&&(e.textContent="刷新中");try{setStatus("nostr","刷新榜单中"),toast("开始刷新 Nostr 榜单"),updateNostrRefreshProgress({active:!0,phase:"清理索引",startedAt:Date.now(),finishedAt:0,connected:0,subscribeDone:0,subEvents:0,recentPages:0,recentEvents:0,historyPages:0,historyEvents:0,indexed:0,relay:""}),clearRelayBackfillTimers(),resetRelaySubscribeState(),await hotClearRankingIndexForRefresh(),state.recommendationSource="pending",renderMetrics(),"all"===state.activeList&&renderActiveGrid(),updateNostrRefreshProgress({phase:"连接 relay",indexed:state.hot.items.length}),subscribeNostr()}catch(e){setStatus("nostr","刷新榜单失败"),updateNostrRefreshProgress({active:!1,phase:"刷新失败",finishedAt:Date.now(),indexed:state.hot.items.length}),toast(e.message||"刷新榜单失败")}finally{forceRefreshNostrRanking.busy=!1,renderConnection()}}function allItems(){return Object.values(state.catalog).flat().filter(hasPoster)}function findItem(e){return allItems().concat(state.searchItems).find(t=>t.id===e)}function scoreItem(e){return Math.max(0,18-e.baseRank)+1.2*(e.voteAverage||0)+.04*Math.min(e.popularity||0,200)}function qualifiesHeat(e){return watchedTenMinutes(e)&&hasHeatIntent(e)}function watchedTenMinutes(e){if(!e||"watch"!==e.action)return!1;return Math.max(0,Number(e.watchMs||e.position||0))>=6e5}function hasHeatIntent(e){const t=String(e.intentAction||e.intent||"");return"view"===t||"search"===t||!0===e.clicked||!0===e.searched}function eventUserKey(e){return e.pubkey?e.pubkey:e.local&&state.identity&&state.identity.pubkey?state.identity.pubkey:"local"}function ranked(e){return e.filter(hasPoster).slice().sort((e,t)=>scoreItem(t)-scoreItem(e))}function uniqueMedia(e){const t=new Map;return e.filter(hasPoster).forEach(e=>{const n=mediaDomKey(e);n&&!t.has(n)&&t.set(n,e)}),Array.from(t.values())}async function loadAutoBlockedMedia(){try{const e=safeJson(await sdk().cache.get(cacheKey("autoBlockedMedia")),null),t=e&&e.items&&"object"==typeof e.items?e.items:{};state.autoBlocked.items=t;let n=!1;Object.keys(t).forEach(e=>{const a=t[e];a&&a.blocked&&!isUserAllowedBlockedKey(e)&&!isUserBlockedKey(e)&&(state.blocked.items[e]=normalizeBlockedEntry(Object.assign({},a,{mode:"auto",source:"auto-rating",blockedAt:a.checkedAt||Date.now()})),n=!0)}),n&&scheduleBlockedRecommendSave()}catch(e){state.autoBlocked.items={}}state.autoBlocked.loaded=!0}async function saveAutoBlockedMedia(){const e=state.autoBlocked.items||{};await sdk().cache.set(cacheKey("autoBlockedMedia"),JSON.stringify({version:1,items:e,updatedAt:Date.now()}))}function autoBlockMediaKey(e){return mediaHeatKey(e)||mediaDomKey(e)}function autoBlockEntry(e){const t=autoBlockMediaKey(e);return t&&state.autoBlocked.items?state.autoBlocked.items[t]:null}function isAutoBlockedMedia(e){return isBlockedByUnifiedState(e)}function isKnownSafeMedia(e){const t=autoBlockEntry(e);return!(!t||!t.checked||t.blocked)}function isRecentAutoBlockFailure(e){const t=autoBlockEntry(e);return!!(t&&!t.checked&&"check-failed"===t.reason&&Date.now()-Number(t.checkedAt||0)<216e5)}function isAdultCertification(e){const t=String(e||"").trim();if(!t)return!1;const n=t.toUpperCase(),a=n.replace(/[\s\-_/().·・::]+/g,"");return!(!["III","IIIA","NC17","X","XXX","R18","R18+","18+","18","19","19+","限制級","限制级","限","成人"].includes(n)&&!["NC17","R18","R18+","18+","18","19","19+"].includes(a))||(/청소년관람불가|청불|19세|19금|성인|제한상영가|제한관람가|成人|限制/.test(t)||/^(R)?(18|19)\+?$/.test(a))}function hasAdultCertification(e,t){if(!e||"object"!=typeof e)return!1;if(!0===e.adult)return!0;if("tv"===t){return(e.content_ratings&&Array.isArray(e.content_ratings.results)?e.content_ratings.results:[]).some(e=>isAdultCertification(e&&e.rating))}return(e.release_dates&&Array.isArray(e.release_dates.results)?e.release_dates.results:[]).some(e=>(e&&Array.isArray(e.release_dates)?e.release_dates:[]).some(e=>isAdultCertification(e&&e.certification)))}function hasAdultTitleFallback(e,t){const n=[e&&e.title,t&&t.title,t&&t.name,t&&t.original_title,t&&t.original_name].filter(Boolean).join(" ").toLowerCase(),a=n.replace(/[\s\-_/().·・::]+/g,"");return!!isRatingLimitEnabled()&&(!!/三级片|三級片|情色|色情|成人|伦理|倫理|强奸|強姦|限制级|限制級|A片|a片|朋友的妻子|softcore|erotic|porn|av\b/.test(n)||(!!/성인|에로|야동|19금|19세|정사|불륜|처제|형수|마사지/.test(n)||(adultExplicitTitleScore(n,a)>=2||/r18|r19|18\+|19\+/.test(a))))}function adultExplicitTitleScore(e,t){const n=String(e||""),a=String(t||"");let i=0;return(/\b[a-z]{2,8}[-_\s]?\d{2,6}\b/i.test(n)||/[a-z]{2,8}\d{2,6}/i.test(a))&&(i+=1),/(勃起|射精|精液|口交|性交|做愛|做爱|肛交|潮吹|中出|內射|内射|巨乳|乳交|陰道|阴道|陰莖|阴茎|肉棒|插入|高潮|性奴|姦|奸|痴漢|痴汉|素人|人妻|熟女|无码|無碼|有码|有碼)/i.test(n)&&(i+=1),/(勃起|射精|精液|口交|性交|做愛|做爱|肛交|潮吹|中出|內射|内射|巨乳|乳交|陰道|阴道|陰莖|阴茎|肉棒|插入|高潮|性奴|姦|奸|痴漢|痴汉|素人|人妻|熟女|无码|無碼|有码|有碼)/i.test(a)&&(i+=1),/(被.+操|操.+女人|射精.+次|勃起.+射精|性.+交|口.+交|中.+出|內.+射|内.+射)/i.test(n)&&(i+=1),i}function maybeAutoBlockByTitle(e){if(!(isRatingLimitEnabled()&&e&&e.tmdbId&&e.mediaType))return!1;const t=autoBlockMediaKey(e);return!(!t||isUserAllowedBlockedKey(t)||isUserBlockedKey(t)||blockedEntryForKey(t))&&(!!hasAdultTitleFallback(e,null)&&(setUnifiedBlockedEntry(e,"auto",{reason:"adult-title",checkedAt:Date.now()}),scheduleAutoBlockRefresh(),!0))}function captureHomePositionSnapshot(){return"home"!==uiSnapshotRoute()?null:{scrollY:homeScrollTop(),activeList:state.activeList||"all",mediaKey:"",focus:homeFocusSnapshot(document.activeElement,null),at:Date.now()}}function restoreHomePositionSnapshot(e){if(!e||"home"!==uiSnapshotRoute()||state.activeList!==e.activeList)return;const t=Math.max(0,Number(e.scrollY||0)),n=n=>{if("home"!==uiSnapshotRoute()||state.activeList!==e.activeList)return;const a=n?findHomeReturnTarget(e):null;a&&focusHomeReturnTarget(a),applyHomeScrollTop(t)};requestAnimationFrame(()=>n(!0)),setTimeout(()=>n(!0),80),setTimeout(()=>n(!1),240)}function scheduleAutoBlockRefresh(){clearTimeout(state.autoBlocked.refreshTimer);const e=Date.now()<state.scrollingUntil?1200:450;state.autoBlocked.refreshTimer=setTimeout(()=>{if(state.blocked.selecting)return state.autoBlocked.refreshTimer=0,void updateBlockSelectUi();if(Date.now()<state.scrollingUntil)return void scheduleAutoBlockRefresh();state.autoBlocked.refreshTimer=0;const e=blockSelectPositionSnapshot(recommendViewportAnchorCard())||captureHomePositionSnapshot();state.hot.items=buildHotItemsFromIndex(),"nostr"===state.recommendationSource?"all"===state.activeList&&renderActiveGrid():useNostrRecommendationsIfReady(),restoreBlockSelectPosition(e)},e)}async function checkAutoBlockedMedia(e){const t=autoBlockMediaKey(e);if(!(t&&e&&e.tmdbId&&e.mediaType))return null;if(state.autoBlocked.pending[t])return state.autoBlocked.pending[t];const n=state.autoBlocked.items&&state.autoBlocked.items[t];if(n&&n.checked&&Date.now()-Number(n.checkedAt||0)<2592e6)return n;if(n&&!n.checked&&"check-failed"===n.reason&&Date.now()-Number(n.checkedAt||0)<216e5)return n;const a=(async()=>{let n=null;try{const t=await requestJson(tmdbAutoBlockUrl(e),18),a=hasAdultCertification(t,e.mediaType)||hasAdultTitleFallback(e,t);n={checked:!0,blocked:a,reason:a?"adult-rating":"safe",title:e.title||t.title||t.name||"",mediaType:e.mediaType||"",tmdbId:e.tmdbId||"",checkedAt:Date.now()}}catch(t){n={checked:!1,blocked:!1,reason:"check-failed",title:e.title||"",mediaType:e.mediaType||"",tmdbId:e.tmdbId||"",checkedAt:Date.now()}}return state.autoBlocked.items[t]=n,await saveAutoBlockedMedia().catch(()=>{}),n.blocked&&isRatingLimitEnabled()&&!isUserAllowedBlockedKey(t)&&!isUserBlockedKey(t)&&(setUnifiedBlockedEntry(e,"auto",{reason:n.reason,checkedAt:n.checkedAt}),scheduleAutoBlockRefresh()),n})();return state.autoBlocked.pending[t]=a,a.finally(()=>{delete state.autoBlocked.pending[t]}),a}function resetAutoBlockScanQueue(){clearTimeout(state.autoBlocked.timer),clearTimeout(state.autoBlocked.viewportTimer),state.autoBlocked.timer=0,state.autoBlocked.viewportTimer=0,state.autoBlocked.queue=[],state.autoBlocked.queued={},state.autoBlocked.version=Number(state.autoBlocked.version||0)+1}function shouldAutoBlockScanItem(e){if(!state.autoBlocked.loaded||!isRatingLimitEnabled())return!1;if(!e||"tmdb"!==e.source||!e.tmdbId||!e.mediaType)return!1;const t=autoBlockMediaKey(e);return!!t&&(!(isUserAllowedBlockedKey(t)||isUserBlockedKey(t)||state.autoBlocked.pending[t]||state.autoBlocked.queued[t])&&(!blockedEntryForKey(t)&&(!isKnownSafeMedia(e)&&!isRecentAutoBlockFailure(e))))}function scheduleAutoBlockDrain(e){state.autoBlocked.loaded&&isRatingLimitEnabled()&&(clearTimeout(state.autoBlocked.timer),state.autoBlocked.timer=setTimeout(drainAutoBlockQueue,null==e?500:e))}function drainAutoBlockQueue(){if(state.autoBlocked.timer=0,!state.autoBlocked.loaded||!isRatingLimitEnabled())return void resetAutoBlockScanQueue();let e=0;const t=Number(state.autoBlocked.version||0);for(;state.autoBlocked.queue.length;){const n=state.autoBlocked.queue[0],a=!(!n||!n.viewport),i=a?32:10,s=a?32:10;if(state.autoBlocked.active>=i||e>=s)break;const o=state.autoBlocked.queue.shift();o&&o.key&&delete state.autoBlocked.queued[o.key],o&&shouldAutoBlockScanItem(o.item)&&(state.autoBlocked.active+=1,e+=1,checkAutoBlockedMedia(o.item).catch(()=>{}).finally(()=>{state.autoBlocked.active=Math.max(0,Number(state.autoBlocked.active||0)-1),t===Number(state.autoBlocked.version||0)&&state.autoBlocked.queue.length&&scheduleAutoBlockDrain(state.autoBlocked.queue[0]&&state.autoBlocked.queue[0].viewport?40:350)}))}state.autoBlocked.queue.length&&scheduleAutoBlockDrain(state.autoBlocked.queue[0]&&state.autoBlocked.queue[0].viewport?40:350)}function scheduleAutoBlockViewportScan(e){clearTimeout(state.autoBlocked.viewportTimer),state.autoBlocked.loaded&&isRatingLimitEnabled()&&(state.blocked.selecting||(state.autoBlocked.viewportTimer=setTimeout(()=>{state.autoBlocked.viewportTimer=0,scanAutoBlockNearViewport({deprioritizeDuringFastScroll:!0})},null==e?180:e)))}function scanAutoBlockNearViewport(e){if(state.blocked.selecting)return;if("all"!==state.activeList||"nostr"!==state.recommendationSource)return;const t=$("recommendRail");if(!t)return;const n=e||{},a=window.innerHeight||document.documentElement.clientHeight||0,i=-Math.max(3*a,900),s=a+Math.max(3*a,900);(!n.deprioritizeDuringFastScroll||Date.now()>=state.scrollingUntil)&&ensureAutoBlockLookaheadRendered(t,s);const o=[],r=[];Array.from(t.querySelectorAll(".card")).forEach(e=>{const t=e.__mediaItem,n=e.getBoundingClientRect(),c=n.bottom>=i&&n.top<=s,l=n.bottom>=0&&n.top<=a;c&&maybeAutoBlockByTitle(t)||shouldAutoBlockScanItem(t)&&(l?o.push(t):c&&r.push(t))}),o.length&&scheduleAutoBlockScan(o,{viewport:!0}),r.length&&scheduleAutoBlockScan(r,{lowPriority:n.deprioritizeDuringFastScroll&&Date.now()<state.scrollingUntil})}function ensureAutoBlockLookaheadRendered(e,t){if(!e)return;let n=0;for(;n<5&&canAppendActiveGrid();){const a=e.querySelectorAll(".card"),i=a[a.length-1];if(i&&i.getBoundingClientRect().bottom>=t)break;if(!appendGridBatch(e))break;n+=1}}function scheduleAutoBlockScan(e,t){if(!state.autoBlocked.loaded||!isRatingLimitEnabled())return void resetAutoBlockScanQueue();const n=state.autoBlocked.queue||(state.autoBlocked.queue=[]),a=state.autoBlocked.queued||(state.autoBlocked.queued={});(e||[]).forEach(e=>{if(n.length>=80||!shouldAutoBlockScanItem(e))return;const i=autoBlockMediaKey(e);a[i]=!0;const s={key:i,item:e,viewport:!(!t||!t.viewport)};s.viewport?n.unshift(s):t&&t.lowPriority?n.push(s):n.unshift(s)}),n.length&&scheduleAutoBlockDrain(t&&t.viewport?0:t&&t.lowPriority?900:Date.now()<state.scrollingUntil?700:240)}async function loadBlockedRecommend(){try{const e=safeJson(await sdk().cache.get(cacheKey("blockedRecommend")),null),t=e&&e.items&&"object"==typeof e.items?e.items:{};state.blocked.items=t}catch(e){state.blocked.items={}}state.blocked.loaded=!0}async function saveBlockedRecommend(){const e=state.blocked.items||{};await sdk().cache.set(cacheKey("blockedRecommend"),JSON.stringify({version:1,items:e}))}function scheduleBlockedRecommendSave(){clearTimeout(state.blocked.saveTimer),state.blocked.saveTimer=setTimeout(()=>{state.blocked.saveTimer=0,saveBlockedRecommend().catch(()=>{})},160)}function blockedKey(e){return mediaHeatKey(e)||mediaDomKey(e)}function normalizeBlockedEntry(e){const t=e&&"object"==typeof e?e:{};return{mode:"allow"===t.mode||"auto"===t.mode||"manual"===t.mode?t.mode:"manual",title:t.title||"",mediaType:t.mediaType||"",tmdbId:t.tmdbId||"",pic:t.pic||"",reason:t.reason||"",source:t.source||"",blockedAt:Number(t.blockedAt||t.checkedAt||t.allowedAt||Date.now()),checkedAt:Number(t.checkedAt||0),allowedAt:Number(t.allowedAt||0)}}function blockedEntryForKey(e){if(!e||!state.blocked.items)return null;const t=state.blocked.items[e];return t?"object"==typeof t&&t.mode?normalizeBlockedEntry(t):normalizeBlockedEntry(Object.assign({},t,{mode:"manual"})):null}function blockedEntry(e){return blockedEntryForKey(blockedKey(e))}function isUserAllowedBlockedKey(e){const t=blockedEntryForKey(e);return!(!t||"allow"!==t.mode)}function isUserBlockedKey(e){const t=blockedEntryForKey(e);return!(!t||"manual"!==t.mode)}function isBlockedByUnifiedState(e){const t=blockedEntry(e);return!!t&&("allow"!==t.mode&&("manual"===t.mode||"auto"===t.mode&&isRatingLimitEnabled()))}function setUnifiedBlockedEntry(e,t,n){const a=blockedKey(e);if(!a)return null;state.blocked.items||(state.blocked.items={});const i=n||{};return state.blocked.items[a]=normalizeBlockedEntry({mode:t,title:e&&e.title||i.title||"",mediaType:e&&e.mediaType||i.mediaType||"",tmdbId:e&&e.tmdbId||i.tmdbId||"",pic:e&&e.pic||i.pic||"",reason:i.reason||"",source:i.source||"",blockedAt:i.blockedAt||Date.now(),checkedAt:i.checkedAt||0,allowedAt:"allow"===t?Date.now():0}),scheduleBlockedRecommendSave(),state.blocked.items[a]}function isBlocked(e){return isBlockedByUnifiedState(e)}function filterBlocked(e){return state.blocked.selecting?e||[]:(e||[]).filter(e=>!isBlocked(e))}function filterBlockedForRecommendations(e){const t=Array.isArray(e)?e:[];return state.blocked.selecting?t:filterBlocked(t)}function blockableRecommendCard(e){if("all"!==state.activeList||"home"!==uiSnapshotRoute())return null;const t=e&&e.closest&&e.closest("#recommendRail .card");return t&&t.__mediaItem&&"history"!==t.__mediaItem.source?t:null}function updateBlockSelectUi(){if(document.body.classList.toggle("block-select-active",!!state.blocked.selecting),document.querySelectorAll("#recommendRail .card").forEach(e=>{const t=isBlocked(e.__mediaItem);e.classList.toggle("blocked",t)}),$("blockSelectHint")){const e=Object.keys(state.blocked.items||{}).filter(e=>{const t=blockedEntryForKey(e);return t&&"allow"!==t.mode}).length;$("blockSelectHint").textContent="屏蔽选择模式:按 OK 切换屏蔽,按返回退出"+(e?` · 已屏蔽 ${e} 个`:"")}}function blockSelectPositionSnapshot(e){const t=e&&e.__mediaItem||null,n=e&&e.closest?e.closest("#recommendRail"):null,a=n?Array.from(n.querySelectorAll(".card")):[],i=e?a.indexOf(e):-1,s=n?Math.max(1,gridColumns(n)):1,o=e&&e.getBoundingClientRect?e.getBoundingClientRect():null;return{scrollY:homeScrollTop(),activeList:state.activeList||"all",mediaKey:mediaDomKey(t),focus:homeFocusSnapshot(e||document.activeElement,t),cardTop:o?o.top:null,cardIndex:i,gridColumns:s,cardRow:i>=0?Math.floor(i/s):-1,cardColumn:i>=0?i%s:-1,mediaKeys:a.map(e=>e.dataset&&e.dataset.mediaKey||"").filter(Boolean),at:Date.now()}}function findRenderedRecommendCardByKey(e){return e&&Array.from(document.querySelectorAll("#recommendRail .card[data-media-key]")).find(t=>String(t.dataset.mediaKey||"")===String(e)&&isVisibleFocusable(t))||null}function recommendViewportAnchorCard(){const e=$("recommendRail");if(!e||"all"!==state.activeList||"home"!==uiSnapshotRoute())return null;const t=window.innerHeight||document.documentElement.clientHeight||0,n=Math.min(Math.max(Math.round(.38*t),120),Math.max(120,t-120));let a=null,i=1/0;return Array.from(e.querySelectorAll(".card")).forEach(e=>{if(!isVisibleFocusable(e))return;const s=e.getBoundingClientRect();if(s.bottom<0||s.top>t)return;const o=Math.abs(s.top-n);o<i&&(a=e,i=o)}),a}function currentBlockSelectCard(){const e=document.activeElement&&document.activeElement.closest?document.activeElement.closest("#recommendRail .card"):null;if(e)return e;const t=state.blocked.lastPosition;return t&&t.mediaKey?findRenderedRecommendCardByKey(t.mediaKey):null}function blockSelectRestoreKeys(e){if(!e)return[];const t=[],n=e=>{e&&!t.includes(e)&&t.push(e)};n(e.mediaKey);const a=Array.isArray(e.mediaKeys)?e.mediaKeys:[],i=Number(e.cardIndex);if(Number.isFinite(i)&&i>=0&&a.length){const t=Math.max(1,Number(e.gridColumns||0)||gridColumns($("recommendRail"))),s=Math.floor(i/t),o=i%t,r=s*t,c=Math.min(a.length-1,r+t-1);for(let e=1;e<t;e++){const t=i+e,s=i-e;t<=c&&n(a[t]),s>=r&&n(a[s])}const l=Math.ceil(a.length/t),d=e=>{if(e<0||e>=l)return;const i=e*t,s=Math.min(a.length-1,i+t-1);n(a[i+o]);for(let e=1;e<t;e++){const t=i+o+e,r=i+o-e;t<=s&&n(a[t]),r>=i&&n(a[r])}};for(let e=1;e<l;e++)d(s+e),d(s-e);for(let e=1;e<a.length;e++)n(a[i+e]),n(a[i-e])}return t}function findBlockSelectRestoreTarget(e){const t=blockSelectRestoreKeys(e);for(const e of t){const t=findRenderedRecommendCardByKey(e);if(t)return t}return null}function ensureBlockSelectTargetRendered(e){if(!e)return null;const t=$("recommendRail");if(!t)return null;let n=findBlockSelectRestoreTarget(e),a=0;for(;!n&&appendGridBatch(t)&&a<80;)a+=1,n=findBlockSelectRestoreTarget(e);return n}function restoreBlockSelectPosition(e){if(!e||"home"!==uiSnapshotRoute()||state.activeList!==e.activeList)return;state.blocked.lastPosition=e;const t=Number(state.blocked.restoreSeq||0)+1;state.blocked.restoreSeq=t;const n=n=>{if(t!==state.blocked.restoreSeq)return;if("home"!==uiSnapshotRoute()||state.activeList!==e.activeList)return;const a=ensureBlockSelectTargetRendered(e);if(!a)return void applyHomeScrollTop(Math.max(0,Number(e.scrollY||0)));n&&focusHomeReturnTarget(a);const i=a.getBoundingClientRect?a.getBoundingClientRect():null,s=Number(e.cardTop);i&&Number.isFinite(s)?applyHomeScrollTop(homeScrollTop()+i.top-s):applyHomeScrollTop(Math.max(0,Number(e.scrollY||0)))};state.blocked.restoring=!0,n(!0),requestAnimationFrame(()=>n(!0)),setTimeout(()=>n(!0),80),setTimeout(()=>n(!1),220),setTimeout(()=>{n(!1),t===state.blocked.restoreSeq&&(state.blocked.restoring=!1)},520)}function enterBlockSelectMode(e){if("all"!==state.activeList||"home"!==uiSnapshotRoute())return!1;const t=blockSelectPositionSnapshot(e);return state.blocked.selecting=!0,state.hot.items=buildHotItemsFromIndex({includeBlocked:!0}),state.blocked.lastPosition=t,updateBlockSelectUi(),state.blocked.restoring=!0,renderActiveGrid(),toast("屏蔽选择模式"),restoreBlockSelectPosition(t),!0}function exitBlockSelectMode(){if(!state.blocked.selecting)return!1;const e=blockSelectPositionSnapshot(currentBlockSelectCard());return state.blocked.selecting=!1,clearBlockLongPress(),state.hot.items=buildHotItemsFromIndex(),state.blocked.lastPosition=e,updateBlockSelectUi(),state.blocked.restoring=!0,renderActiveGrid(),toast("已退出屏蔽选择"),restoreBlockSelectPosition(e),!0}function clearBlockLongPress(){state.blocked.holdTimer&&clearTimeout(state.blocked.holdTimer),state.blocked.holdTimer=0,state.blocked.holdTarget=null,state.blocked.pointer=null}function armBlockLongPress(e){return!(!e||state.blocked.selecting||state.blocked.holdTimer)&&(state.blocked.holdTarget=e,state.blocked.longPressFired=!1,state.blocked.holdTimer=setTimeout(()=>{state.blocked.holdTimer=0,state.blocked.longPressFired=!0,enterBlockSelectMode(e)},650),!0)}function consumeBlockCardEnterDown(e,t){return!!e&&(t.preventDefault(),t.stopPropagation(),state.blocked.selecting?(toggleBlockedCard(e),!0):(armBlockLongPress(e),!0))}function handleBlockCardEnterUp(e){const t=state.blocked.holdTarget;if(!t)return!1;e.preventDefault(),e.stopPropagation();const n=state.blocked.longPressFired;return clearBlockLongPress(),n?(state.blocked.longPressFired=!1,!0):(state.blocked.selecting||t.click(),!0)}function handleBlockPointerDown(e,t){return!(!e||state.blocked.selecting)&&(("mouse"!==t.pointerType||0===t.button)&&(state.blocked.pointer={id:t.pointerId,x:t.clientX||0,y:t.clientY||0},armBlockLongPress(e),!0))}function handleBlockPointerMove(e){const t=state.blocked.pointer;if(!t||t.id!==e.pointerId)return;const n=Math.abs((e.clientX||0)-t.x),a=Math.abs((e.clientY||0)-t.y);(n>12||a>12)&&clearBlockLongPress()}function handleBlockPointerUp(e){const t=state.blocked.pointer;if(!t||t.id!==e.pointerId)return!1;const n=state.blocked.longPressFired;return clearBlockLongPress(),!!n&&(state.blocked.longPressFired=!1,state.blocked.suppressClickUntil=Date.now()+700,e.preventDefault(),e.stopPropagation(),!0)}async function toggleBlockedCard(e){const t=e&&e.__mediaItem,n=blockedKey(t);if(!t||!n)return;const a=blockSelectPositionSnapshot(e),i=blockedEntryForKey(n);i&&"manual"===i.mode?(delete state.blocked.items[n],toast("已解除屏蔽")):i&&"auto"===i.mode&&isRatingLimitEnabled()?(setUnifiedBlockedEntry(t,"allow",{reason:"user-allow"}),toast("已解除屏蔽")):(i&&i.mode,setUnifiedBlockedEntry(t,"manual",{reason:"user-block"}),toast("已屏蔽")),updateBlockSelectUi();try{await saveBlockedRecommend()}catch(e){toast("屏蔽保存失败")}restoreBlockSelectPosition(a),scheduleUiSnapshotSave()}function getList(e){return visibleTmdbLists().find(t=>t.id===e)}function visibleTmdbLists(){return(window.WEBHOME_CONFIG.tmdb.lists||[]).filter(e=>!(e.hidden||e.mobileHidden&&isPhoneViewport()))}function isPhoneViewport(){const e=Math.min(window.innerWidth||0,document.documentElement.clientWidth||0)||window.innerWidth||0,t=Math.min(window.innerHeight||0,document.documentElement.clientHeight||0)||window.innerHeight||0,n=!!window.matchMedia&&window.matchMedia("(pointer: coarse)").matches;return e>0&&e<720&&(n||t>e)}function isBrowserPhoneClient(){const e=Math.min(window.innerWidth||0,document.documentElement.clientWidth||0)||window.innerWidth||0,t=!!window.matchMedia&&window.matchMedia("(pointer: coarse)").matches,n=String(navigator.userAgent||""),a=/Android|iPhone|iPod|Mobile/i.test(n);return e>0&&e<720&&(t||a)}function useLargeDetailLayout(){return"mobile"!==state.deviceMode&&!isNativeMobileClient()&&(!("leanback"!==state.deviceMode&&!isNativeLeanbackClient())||!isBrowserPhoneClient())}function syncLegacyDetailLayout(e,t){const n=document.documentElement;n&&e&&(t?requestAnimationFrame(()=>{try{const t=window.getComputedStyle?getComputedStyle(e):null,a=t&&parseFloat(t.paddingLeft)||0,i=t&&parseFloat(t.paddingTop)||0;n.classList.toggle("legacy-detail-layout",a<32||i<32)}catch(e){n.classList.add("legacy-detail-layout")}}):n.classList.remove("legacy-detail-layout"))}function syncDetailLayout(){const e=$("detailSheet");if(!e)return!1;const t=e.classList.contains("detail-large"),n=useLargeDetailLayout();return e.classList.toggle("detail-large",n),syncDetailBackFocusability(n),syncLegacyDetailLayout(e,n),t!==n}function syncDetailBackFocusability(e){const t=document.documentElement,n=$("mobileDetailBackBtn"),a=t&&t.classList.contains("native-phone-app")&&!e;n&&(n.tabIndex=a?0:-1)}function isKnownList(e){return"all"===e||"recent"===e||"live"===e||!!getList(e)}function normalizeActiveListForViewport(){isKnownList(state.activeList)||(state.activeList="all")}function hasPoster(e){return!(!e||!e.pic)}function renderSearch(){$("searchSection").style.display=state.searchItems.length?"":"none",renderRail("searchRail",ranked(state.searchItems).slice(0,18))}function firstSearchResultCard(){return searchResultCardNear(null)}function visibleSearchResultCards(){const e=$("searchRail"),t=$("searchSection");return e&&t&&"none"!==t.style.display?Array.from(e.querySelectorAll(".card")).filter(isVisibleFocusable):[]}function searchClearButton(){const e=$("searchSection"),t=$("clearSearchBtn");return e&&"none"!==e.style.display&&isVisibleFocusable(t)?t:null}function searchResultCardNear(e){return focusableCardNear(visibleSearchResultCards(),e)}function searchReturnCard(e){const t=state.searchReturnCard;return t&&t.isConnected&&t.closest&&t.closest("#searchRail")&&isVisibleFocusable(t)?t:searchResultCardNear(e)}function activeGridCardNear(e){const t=activeMediaGrid();if(!t)return null;const n=Array.from(t.querySelectorAll(".card")).filter(isVisibleFocusable);if(!n.length)return null;const a=Math.max(1,gridColumns(t));return focusableCardNear(n.slice(0,a),e)||n[0]}function focusableCardNear(e,t){if(!e||!e.length)return null;if(!t||!t.getBoundingClientRect)return e[0];const n=center(t.getBoundingClientRect()).x;let a=e[0],i=1/0;return e.forEach(e=>{const t=Math.abs(center(e.getBoundingClientRect()).x-n);t<i&&(a=e,i=t)}),a}function focusSearchResultsAfterRender(){isTvMode()&&state.searchItems.length&&requestAnimationFrame(()=>{const e=firstSearchResultCard();e&&focusRemoteTarget(e)})}function clearSearchResults(){state.searchItems=[],state.searchReturnCard=null,$("searchInput")&&($("searchInput").value=""),hideSearchSuggest(),renderSearch(),scheduleUiSnapshotSave()}function renderAll(e){const t=e||{};clearTimeout(state.renderTimer),state.renderTimer=0,normalizeActiveListForViewport(),syncConnectionDockPlacement(),renderChips(),t.deferContent?scheduleHomeContentRender({afterPaint:!0}):renderHomeContent(),renderMetrics(),normalizeRails()}function syncConnectionDockPlacement(){const e=$("connectionDock"),t=$("searchForm"),n=$("homeSettingBtn"),a=$("recommendSection")&&$("recommendSection").querySelector(".section-head");e&&t&&n&&a&&(isTvMode()?e.parentElement===t&&e.previousElementSibling===n||t.insertBefore(e,n.nextSibling):e.parentElement!==a&&a.appendChild(e),fitConnectionPanel())}function renderHomeContent(){const e="all"===state.activeList;$("recommendSection").style.display=e?"":"none",$("listSection").style.display=e?"none":"",e?renderRecommendations():renderLists(),observeInfiniteScroll(),requestAnimationFrame(ensureScrollablePage)}function scheduleHomeContentRender(e){const t=e||{},n=++state.homeContentSeq;state.homeContentTimer&&(cancelAnimationFrame(state.homeContentTimer),state.homeContentTimer=0);const a=()=>{n===state.homeContentSeq&&(state.homeContentTimer=0,renderHomeContent(),"function"==typeof t.after&&t.after())};t.afterPaint?state.homeContentTimer=requestAnimationFrame(()=>{n===state.homeContentSeq&&(state.homeContentTimer=requestAnimationFrame(a))}):a()}function ensureActiveListData(e){e&&state.activeList===e&&("recent"===e?loadRecentList({refresh:shouldRefreshRecentList()}):"all"!==e&&"live"!==e&&loadCatalogList(e))}function scheduleRender(){clearTimeout(state.renderTimer);const e=Date.now()<state.scrollingUntil?700:160;state.renderTimer=setTimeout(()=>{Date.now()<state.scrollingUntil?scheduleRender():renderAll({deferContent:"home"===uiSnapshotRoute()})},e)}function renderChips(){const e=[{id:"live",title:"直播"},{id:"all",title:"推荐"},{id:"recent",title:"最近"}].concat(visibleTmdbLists().map(e=>({id:e.id,title:e.title}))),t=$("chips"),n=e.map(e=>e.id+":"+e.title).join("\n");t.dataset.renderKeys!==n&&(t.dataset.renderKeys=n,t.replaceChildren(...e.map(e=>{const t=document.createElement("button");return t.className="chip focusable",t.type="button",t.dataset.chipId=e.id,t.textContent=e.title,t.addEventListener("click",()=>selectChip(e.id)),t.addEventListener("focus",()=>{scheduleChipFocusSelect(e.id)}),t}))),Array.from(t.children).forEach(e=>e.classList.toggle("active",e.dataset.chipId===state.activeList))}function scheduleChipFocusSelect(e){clearTimeout(state.chipFocusTimer),e&&state.activeList!==e&&(state.chipFocusTimer=setTimeout(()=>selectChip(e,{keepFocus:!0,fromFocus:!0}),45))}function selectChip(e,t){const n=t||{};n.fromFocus||clearTimeout(state.chipFocusTimer),e&&state.activeList!==e&&("all"!==e&&exitBlockSelectMode(),state.activeList=e,renderChips(),scheduleHomeContentRender({afterPaint:!0,after:()=>ensureActiveListData(e)}),scheduleUiSnapshotSave(),n.keepFocus&&requestAnimationFrame(()=>{const t=findByDataset($("chips"),"chipId",e);t&&focusRemoteTarget(t)}))}function renderRecommendations(){const e=filterBlockedForRecommendations(preferenceItems());if(e.length)return state.recommendationSource="nostr",clearTimeout(state.relay.fallbackTimer),fillGrid($("recommendRail"),e),void updateBlockSelectUi();if("nostr"===state.recommendationSource&&(state.recommendationSource="pending"),"pending"!==state.recommendationSource||nostrReadyForFallback()){if(state.recommendationSource="fallback",ensureRecommendationFallback(),state.fallbackPage.loading&&!state.fallback.length)return void showGridStatus($("recommendRail"),"推荐兜底加载中...");fillGrid($("recommendRail"),filterBlockedForRecommendations(state.fallback.length?state.fallback:ranked(allItems()))),updateBlockSelectUi()}else showGridStatus($("recommendRail"),"Nostr 推荐同步中...")}function renderActiveGrid(){"all"===state.activeList?renderRecommendations():renderLists(),observeInfiniteScroll(),requestAnimationFrame(ensureScrollablePage)}function renderLists(){if("recent"===state.activeList)return void renderRecentList();if("live"===state.activeList)return void renderLiveEntry();const e=visibleTmdbLists().filter(e=>e.id===state.activeList);if(!e.length)return void activateListPanel("");const t=e[0],n=ensureListPanel(t.id,t.title,t.hint||"").querySelector(".media-grid");activateListPanel(t.id);const a=state.catalogPage[t.id];a&&a.loading?n.dataset.renderKeys||showGridStatus(n,"加载中..."):a&&a.error?showGridStatus(n,"加载失败"):a&&a.loaded?fillGrid(n,state.catalog[t.id]||[]):showGridStatus(n,"点击后加载片单")}function renderLiveEntry(){const e=ensureListPanel("live","直播","电视台与直播源",{grid:!1});if(activateListPanel("live"),"1"===e.dataset.liveReady)return;e.dataset.liveReady="1";const t=document.createElement("div"),n=document.createElement("button");n.className="live-entry-card focusable",n.type="button",n.innerHTML='\n <span class="live-icon" aria-hidden="true">\n <svg class="icon" viewBox="0 0 24 24"><rect x="3" y="6" width="18" height="13" rx="2"/><path d="M8 21h8"/><path d="M12 19v2"/><path d="m9 3 3 3 3-3"/></svg>\n </span>\n <div class="live-copy">\n <h5>观看直播</h5>\n <p>频道分组、节目单、收藏频道和多线路已接入。</p>\n <div class="live-tags"><span class="live-tag">频道分组</span><span class="live-tag">节目单</span><span class="live-tag">收藏</span></div>\n </div>\n <span class="live-action">继续观看</span>\n ',n.addEventListener("click",openLiveHome),t.appendChild(n),e.appendChild(t)}function renderRecentList(){const e=ensureListPanel("recent","最近","继续观看").querySelector(".media-grid");activateListPanel("recent"),state.recent.loading&&!state.recent.loaded?showGridStatus(e,"读取最近观看..."):state.recent.error?showGridStatus(e,"最近观看读取失败"):state.recent.loaded?fillGrid(e,state.recent.items||[]):showGridStatus(e,"点击后读取最近观看")}function ensureListPanel(e,t,n,a){const i=$("listStack");Array.from(i.children).forEach(e=>{e.classList&&e.classList.contains("list-panel")||e.remove()});let s=Array.from(i.querySelectorAll(".list-panel")).find(t=>t.dataset.listId===e);if(s)return s;if(s=document.createElement("div"),s.className="list-block list-panel",s.dataset.listId=e,s.hidden=!0,s.innerHTML=`\n <div class="subsection-head">\n <h4>${escapeHtml(t||"")}</h4>\n <span>${escapeHtml(n||"")}</span>\n </div>\n `,!a||!1!==a.grid){const t=document.createElement("div");t.className="media-grid",t.dataset.listId=e,s.appendChild(t)}return i.appendChild(s),s}function activateListPanel(e){const t=$("listStack");Array.from(t.querySelectorAll(".list-panel")).forEach(t=>{t.hidden=t.dataset.listId!==e})}function renderRail(e,t){fillRail($(e),t)}function fillRail(e,t){if(!(t=t.filter(hasPoster)).length){const t=document.createElement("div");return t.className="empty",t.textContent="暂无内容",void e.replaceChildren(t)}const n=e.dataset.railKey||e.id||"";n&&e.dataset.scrollBound&&(state.railScroll[n]=e.scrollLeft);const a=n&&state.railScroll[n]||0,i=!(!$("detailSheet")||!$("detailSheet").contains(e));e.replaceChildren(...t.map((e,t)=>mediaCard(e,t,{landscape:i&&useLargeDetailLayout()}))),a&&requestAnimationFrame(()=>e.scrollLeft=a),e.dataset.scrollBound||(e.dataset.scrollBound="1",e.addEventListener("scroll",()=>{state.scrollingUntil=Date.now()+900;const t=e.dataset.railKey||e.id||"";t&&(state.railScroll[t]=e.scrollLeft)},{passive:!0}))}function fillGrid(e,t){if(!e)return;const n=Array.isArray(t)?t:[],a=gridRenderId(e),i=state.gridRender[a];if(i&&i.source===n&&i.sourceLength===n.length&&Number(i.rendered||0)>0&&e.children.length>=Number(i.rendered||0)){const t=Math.min(Number(i.total||0),initialGridBatchSize(e));if(Number(i.rendered||0)>=t)return void ensureRemoteInitialFocus()}if(!(t=uniqueMedia(n).filter(hasPoster)).length)return void showGridStatus(e,"暂无内容");const s=t.map(mediaDomKey),o=t.map(mediaRenderKey),r=e.dataset.itemKeys?e.dataset.itemKeys.split("\n"):[],c=e.dataset.renderKeys?e.dataset.renderKeys.split("\n"):[],l=r.length>0&&r.every((e,t)=>e&&e===s[t]);let d=state.gridRender[a];const u=Number(d&&d.rendered||0),m=Number(d&&d.total||0),p=Math.min(u,c.length,o.length),h=l&&p>0&&c.slice(0,p).every((e,t)=>e===o[t]);d&&l&&h||(d=state.gridRender[a]={rendered:0,total:0,keys:"",items:[]},e.replaceChildren(),e.dataset.renderKeys=""),e.dataset.itemKeys=s.join("\n"),d.total=t.length,d.keys=e.dataset.itemKeys,d.items=t,d.source=n,d.sourceLength=n.length;let f=Math.min(t.length,Math.max(Number(d.rendered||0),u,initialGridBatchSize(e)));h&&t.length>m&&u>=m&&(f=Math.min(t.length,u+appendGridBatchSize(e))),appendGridItems(e,t,f),ensureRemoteInitialFocus()}function showGridStatus(e,t){if(!e)return;const n=gridRenderId(e);delete state.gridRender[n],e.dataset.renderKeys="",e.dataset.itemKeys="",e.replaceChildren(emptyNode(t))}function gridRenderId(e){return e&&(e.dataset.listId||e.id)||"grid"}function gridColumns(e){const t=window.innerWidth||0,n=isTvMode()?"tv":"web",a=gridRenderId(e),i=e?getComputedStyle(e).gridTemplateColumns:"",s=`${a}|${n}|${t}|${i}`,o=state.gridColumnCache[s];if(o)return o;const r=i&&"none"!==i?i.split(" ").filter(Boolean).length:0,c=r>0?r:isTvMode()?5:t>=1180?6:t>=720?4:3;return state.gridColumnCache[s]=c,c}function initialGridBatchSize(e){const t=gridColumns(e);return Math.max(3*t,isTvMode()?18:12)}function appendGridBatchSize(e){const t=gridColumns(e);return Math.max(2*t,isTvMode()?10:6)}function appendGridItems(e,t,n){const a=gridRenderId(e),i=state.gridRender[a]||(state.gridRender[a]={rendered:0,total:t.length,keys:"",items:[]}),s=Math.max(0,Number(i.rendered||0)),o=Math.max(s,Math.min(t.length,n));if(i.items=t,i.total=t.length,o<=s)return;const r=document.createDocumentFragment();for(let e=s;e<o;e++)r.appendChild(mediaCard(t[e],e));e.appendChild(r),i.rendered=o,e.dataset.renderKeys=t.slice(0,o).map(mediaRenderKey).join("\n"),updateBlockSelectUi(),"recommendRail"===a&&"all"===state.activeList&&"nostr"===state.recommendationSource&&scheduleAutoBlockViewportScan(Date.now()<state.scrollingUntil?700:80)}function appendGridBatch(e){if(!e||e.closest&&e.closest(".list-panel[hidden]"))return!1;const t=gridRenderId(e);if("recommendRail"===t&&"all"!==state.activeList)return!1;if(e.dataset.listId&&e.dataset.listId!==state.activeList)return!1;const n=state.gridRender[t];if(!n||!n.total||Number(n.rendered||0)>=Number(n.total||0))return!1;const a=Array.isArray(n.items)&&n.items.length?n.items:itemsForGrid(t);return!!a.length&&(appendGridItems(e,a,Math.min(a.length,Number(n.rendered||0)+appendGridBatchSize(e))),!0)}function appendActiveGridBatch(){return!!appendGridBatch(activeMediaGrid())&&(observeInfiniteScroll(),!0)}function canAppendActiveGrid(){const e=activeMediaGrid();if(!e)return!1;const t=state.gridRender[gridRenderId(e)];return!!(t&&Number(t.rendered||0)<Number(t.total||0))}function activeMediaGrid(){if("all"===state.activeList)return $("recommendRail");const e=Array.from($("listStack").querySelectorAll(".list-panel")).find(e=>!e.hidden&&e.dataset.listId===state.activeList);return e&&e.querySelector(".media-grid")}function itemsForGrid(e){if("recommendRail"===e||"all"===e){return uniqueMedia(filterBlocked(preferenceItems().length?preferenceItems():state.fallback.length?state.fallback:ranked(allItems()))).filter(hasPoster)}return"recent"===e?uniqueMedia(state.recent.items||[]).filter(hasPoster):uniqueMedia(state.catalog[e]||[]).filter(hasPoster)}function maybeAppendGridForFocus(e){const t=e&&e.closest&&e.closest(".media-grid");if(!t)return;const n=state.gridRender[gridRenderId(t)];if(!n||Number(n.rendered||0)>=Number(n.total||0))return;let a=Number(e.dataset.cardIndex||-1);if(!Number.isFinite(a)||a<0){a=Array.from(t.querySelectorAll(".card")).indexOf(e)}if(a<0)return;a>=Math.max(0,Number(n.rendered||0)-2*gridColumns(t))&&scheduleGridAppend(t)}function scheduleGridAppend(e){const t=gridRenderId(e);state.activeGridAppendTimer&&state.activeGridAppendId===t||(state.activeGridAppendTimer&&cancelAnimationFrame(state.activeGridAppendTimer),state.activeGridAppendId=t,state.activeGridAppendTimer=requestAnimationFrame(()=>{state.activeGridAppendTimer=0,state.activeGridAppendId="",appendGridBatch(e)&&observeInfiniteScroll()}))}function ensureRemoteInitialFocus(){if(state.blocked.restoring)return;if("home"===uiSnapshotRoute()&&homeScrollTop()>8)return;const e=document.activeElement;if(state.remoteInitialFocused&&isVisibleFocusable(e))return;const t=state.remoteInitialFocused?firstContentFocus():initialHomeFocus()||firstContentFocus();t&&(state.remoteInitialFocused=!0,requestAnimationFrame(()=>{state.blocked.restoring||focusRemoteTarget(t)}))}function ensureRemoteActiveFocus(){if(isVisibleFocusable(document.activeElement))return!1;if(restoreConnectionPanelFocus())return!0;const e="home"===uiSnapshotRoute()&&initialHomeFocus()||firstContentFocus();return!!e&&(focusRemoteTarget(e),!0)}function focusInitialHomeNow(e){const t=e||{};if(!t.force&&(state.blocked.restoring||homeScrollTop()>8))return;focusHomeTopTarget(initialHomeFocus(),t)}function focusCurrentHomeTop(e){focusHomeTopTarget(currentHomeFocus()||initialHomeFocus(),e)}function focusHomeTopTarget(e,t){if(!e)return;const n=t||{};if(n.force||!(state.blocked.restoring||homeScrollTop()>8))if(state.remoteInitialFocused=!0,n.preventScroll)try{e.focus({preventScroll:!0})}catch(t){e.focus()}else focusRemoteTarget(e)}function initialHomeFocus(){return focusScopeRoot()!==document?null:findByDataset($("chips"),"chipId","all")||$("chips").querySelector(".chip.active")||$("chips").querySelector(".chip")}function currentHomeFocus(){return focusScopeRoot()!==document?null:findByDataset($("chips"),"chipId",state.activeList)||$("chips").querySelector(".chip.active")||initialHomeFocus()}function activeHomeChip(){return currentHomeFocus()}function firstActiveGridCard(){const e=activeMediaGrid();return e&&Array.from(e.querySelectorAll(".card")).find(isVisibleFocusable)||null}function observeInfiniteScroll(){const e=$("infiniteSentinel");e&&"IntersectionObserver"in window&&(state.infiniteObserver||(state.infiniteObserver=new IntersectionObserver(e=>{e.some(e=>e.isIntersecting)&&loadMoreVisible()},{root:null,rootMargin:"900px 0px",threshold:0})),state.infiniteObserver.unobserve(e),(canAppendActiveGrid()||canLoadMore())&&state.infiniteObserver.observe(e))}function canLoadMore(){if(state.loadingMore)return!1;if("recent"===state.activeList)return!1;if("live"===state.activeList)return!1;if("all"===state.activeList)return!preferenceItems().length&&"fallback"===state.recommendationSource&&!state.fallbackPage.done;const e=state.catalogPage[state.activeList];return!!(e&&!e.loading&&e.page<e.total)}function ensureScrollablePage(){document.documentElement.scrollHeight>window.innerHeight+500||loadMoreVisible()}function normalizeRails(){document.querySelectorAll(".rail").forEach(e=>{const t=$("detailSheet");if(document.documentElement.classList.contains("native-mobile-app")&&t&&t.contains(e)&&!t.classList.contains("detail-large"))return e.style.removeProperty("width"),e.style.removeProperty("max-width"),void(e.style.minWidth="0");e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0"})}function mediaCard(e,t,n){const a=n||{},i=document.createElement("button"),s=Number(e.people||0),o=mediaDomKey(e),r=blockedKey(e),c="history"===e.source,l=!!a.landscape;i.className="card focusable"+(s>0?" has-people":"")+(c?" recent-card":"")+(l?" landscape-card":""),i.type="button",i.dataset.cardIndex=String(t||0),o&&(i.dataset.mediaKey=o),r&&(i.dataset.blockKey=r),i.__mediaItem=e,i.classList.toggle("blocked",isBlocked(e));const d=e.voteAverage?Number(e.voteAverage).toFixed(1):"",u=displayImage(l&&(e.landscape||e.image)||e.pic,{size:l?"w780":"w342"}),m={loading:t<initialGridBatchSize(null)?"eager":"lazy",fetchPriority:t<8?"high":""},p=Math.min(100,Math.max(0,Number(e.progress||0)));return i.innerHTML=c?`\n <img class="poster" alt="" ${imageAttrs(u,m)}>\n ${e.badge?`<span class="recent-badge">${escapeHtml(e.badge)}</span>`:""}\n <div class="card-body">\n <div class="card-title">${escapeHtml(e.title)}</div>\n <div class="card-meta">${escapeHtml(e.remark)}</div>\n </div>\n ${p>0?`<div class="recent-progress" aria-hidden="true"><span style="--recent-progress:${escapeAttr(p+"%")}"></span></div>`:""}\n `:`\n <div class="poster-wrap">\n <img class="poster" alt="" ${imageAttrs(u,m)}>\n ${s>0?`<span class="card-people">${escapeHtml(s)}人</span>`:""}\n </div>\n ${d?`<span class="rating-badge">${escapeHtml(d)}</span>`:""}\n <div class="card-body">\n <div class="card-title">${escapeHtml(e.title)}</div>\n <div class="card-meta">${escapeHtml(e.remark)}</div>\n </div>\n `,i.addEventListener("pointerdown",e=>handleBlockPointerDown(blockableRecommendCard(i),e)),i.addEventListener("pointermove",handleBlockPointerMove),i.addEventListener("pointerup",handleBlockPointerUp),i.addEventListener("pointercancel",clearBlockLongPress),i.addEventListener("contextmenu",e=>{Date.now()<Number(state.blocked.suppressClickUntil||0)&&e.preventDefault()}),i.addEventListener("click",()=>{Date.now()<Number(state.blocked.suppressClickUntil||0)||(state.blocked.selecting&&blockableRecommendCard(i)?toggleBlockedCard(i):"history"===e.source?openRecentItem(e):openDetail(e,{returnTarget:i}))}),i}async function openRecentItem(e){if(e&&e.siteKey&&e.vodId)try{rememberWatchIntent(e,"view"),await sdk().vod(e.siteKey,e.vodId,e.title,playbackPosterPic(e),vodPlaybackOptions(e)),startWatchTracking(e)}catch(e){toast("打开最近观看失败:"+(e.message||"unknown"))}else toast("最近观看缺少播放信息")}async function openDetailContinueHistory(){const e=$("detailContinueBtn"),t=e&&e.__historyItem||findDetailContinueHistory(state.selected);if(!(state.selected&&t&&t.siteKey&&t.vodId))return toast("没有可继续观看的记录"),void updateDetailContinueButton();try{rememberDetailReturn(e),rememberWatchIntent(state.selected,"view"),startWatchTracking(state.selected);const n=Object.assign({},state.selected||{},t||{},{title:t.title||state.selected.title,pic:state.selected.pic||t.pic||"",wallPic:t.wallPic||state.selected.wallPic||state.selected.landscape||""});await sdk().vod(t.siteKey,t.vodId,n.title,playbackPosterPic(n),vodPlaybackOptions(n))}catch(e){stopWatchTracking(!1),toast("继续观看失败:"+(e.message||"unknown"))}}function vodPlaybackOptions(e){const t=playbackWallPic(e);return t?{wallPic:t}:{}}function preloadDetailPlaybackArtwork(){if(!state.selected)return;const e=findDetailContinueHistory(state.selected);preloadPlaybackArtwork(e&&e.siteKey&&e.vodId?Object.assign({},state.selected||{},e||{},{title:e.title||state.selected.title,pic:e.pic||state.selected.pic}):state.selected)}function preloadPlaybackArtwork(e){const t=sdk();if(!t||!t.preloadArtwork)return;const n=playbackPosterPic(e),a=playbackWallPic(e);if(!n&&!a)return;const i=[mediaDomKey(e),n,a].join("\n");if(state.playbackArtworkPreloadKey!==i){state.playbackArtworkPreloadKey=i;try{const e=t.preloadArtwork(n,a);e&&e.catch&&e.catch(()=>{})}catch(e){}}}function playbackPosterPic(e){const t=e||{},n=findMediaByContent(t)||null,a=state.selected||null,i=a&&(samePlaybackMedia(t,a)||samePlaybackMedia(n,a));return playbackImage(firstPlaybackWallPic([t.pic,t.poster,t.vodPic,i&&a.pic,n&&n.pic]))}function playbackWallPic(e){const t=e||{},n=findMediaByContent(t)||null,a=state.selected||null,i=a&&(samePlaybackMedia(t,a)||samePlaybackMedia(n,a));return playbackImage(firstPlaybackWallPic([t.wallPic,i?currentDetailWallPic():"",t.landscape,n&&n.landscape,i&&a.landscape]))}function firstPlaybackWallPic(e){for(const t of e||[]){const e=String(t||"").trim();if(e)return e}return""}function currentDetailWallPic(){const e=$("detailSheet");if(!e||!e.classList.contains("active"))return"";const t=state.detailCover&&state.detailCover.images||[];if(!t.length)return"";return t[Math.max(0,Math.min(Number(state.detailCover.index||0),t.length-1))]||t[0]||""}function samePlaybackMedia(e,t){if(!e||!t)return!1;const n=playbackMediaKey(e),a=playbackMediaKey(t);if(n&&a&&n===a)return!0;const i=normalizeTitle(e.title||e.vodName||e.name||e.query||""),s=normalizeTitle(t.title||t.vodName||t.name||t.query||"");return!(!i||!s||i!==s)}function playbackMediaKey(e){if(!e)return"";if(e.tmdbId&&e.mediaType)return"tmdb:"+String(e.mediaType)+":"+String(e.tmdbId);const t=String(e.id||"");return/^tmdb:/i.test(t)?t.toLowerCase():""}function mediaDomKey(e){return e?e.id||(e.tmdbId&&e.mediaType?`tmdb:${e.mediaType}:${e.tmdbId}`:e.title||""):""}function mediaRenderKey(e){return e?[mediaDomKey(e),e.title,e.pic,e.remark,e.voteAverage,e.people,e.progress,e.badge].map(e=>String(null==e?"":e).replace(/[\r\n]+/g," ")).join("\t"):""}function mediaHeatKey(e){if(!e)return"";const t=e.mediaType||"",n=e.tmdbId||"";if(t&&n)return`tmdb:${t}:${n}`;const a=normalizeTitle(e.title||e.query||"");return a?`title:${a}`:""}function preferenceItems(){return state.hot.items}function normalizeSnapshot(e){return e&&"object"==typeof e?{id:e.id||(e.tmdbId&&e.mediaType?`tmdb:${e.mediaType}:${e.tmdbId}`:""),source:e.source||"tmdb",tmdbId:e.tmdbId?String(e.tmdbId):"",mediaType:e.mediaType||"",listId:e.listId||"",listTitle:e.listTitle||"",title:e.title||"",pic:e.pic||"",landscape:e.landscape||"",image:e.image||e.pic||"",desc:e.desc||"",releaseDate:e.releaseDate||"",voteAverage:e.voteAverage||0,popularity:e.popularity||0,baseRank:e.baseRank||99}:{}}function normalizeTitle(e){return String(e||"").toLowerCase().replace(/[第][一二三四五六七八九十0-9]+[季部]?/g,"").replace(/\s+/g,"").replace(/[·::,,.。!!??'"“”‘’《》<>【】()[\]{}_-]/g,"").trim()}function findMediaByContent(e){const t=normalizeTitle(e.title||e.query||"");return allItems().concat(state.searchItems).find(n=>!(!e.tmdbId||!n.tmdbId||String(e.tmdbId)!==String(n.tmdbId))||t&&normalizeTitle(n.title)===t)}function renderMetrics(){const e=state.identity?hotUserKey(state.identity.pubkey):"",t=e?state.hot.users.get(e):null,n=t?hotActiveVectorItems(t).length:0;$("identityText").textContent=state.identity?`npub: ${state.identity.npub}\nnsec: ${state.identity.nsec}`:"身份未就绪",$("relayText").textContent=`relay: ${window.WEBHOME_CONFIG.nostr.relays.join(", ")}`,setStatus("nostr",`已连接 ${state.relay.connected}/${window.WEBHOME_CONFIG.nostr.relays.length} · 本机 ${n} · 榜单 ${state.hot.items.length}`),state.identity&&(state.status.identity=shortKey(state.identity.npub)),renderConnection()}function scheduleSearchSuggest(){clearTimeout(state.suggestions.timer);const e=$("searchInput"),t=e?e.value.trim():"";if(!t)return void hideSearchSuggest();if(e&&e.readOnly)return hideSearchSuggest();const n=++state.suggestions.seq;state.suggestions.timer=setTimeout(()=>loadSearchSuggest(t,n),180)}async function loadSearchSuggest(e,t){const n=String(e||"").trim();if(!n)return hideSearchSuggest();if(t===state.suggestions.seq)if(state.suggestions.keyword===n&&state.suggestions.items.length)$("searchInput")&&$("searchInput").value.trim()===n&&!$("searchInput").readOnly&&renderSearchSuggest();else{state.suggestions.loading=!0;try{const e=await requestJson(suggestUrl(n),8);if(t!==state.suggestions.seq)return;if(!$("searchInput")||$("searchInput").value.trim()!==n||$("searchInput").readOnly)return;state.suggestions.keyword=n,state.suggestions.items=normalizeSuggestItems(e).slice(0,8),renderSearchSuggest()}catch(e){t===state.suggestions.seq&&$("searchInput")&&$("searchInput").value.trim()===n&&hideSearchSuggest()}finally{state.suggestions.loading=!1}}}function normalizeSuggestItems(e){const t=Array.isArray(e&&e.data)?e.data:Array.isArray(e)?e:[],n=new Set,a=[];return t.forEach(e=>{const t=String(e&&(e.name||e.title||e.keyword||e.word)||"").trim();if(!t||n.has(t))return;n.add(t);const i=String(e.cname||e.channel_name||e.type||"").trim(),s=e.year?String(e.year):"",o=Array.isArray(e.main_actor)?e.main_actor.slice(0,2).join("/"):"";a.push({title:t,meta:[i,s,o].filter(Boolean).join(" · ")})}),a}function renderSearchSuggest(){const e=$("suggestPanel");if(!e)return;const t=state.suggestions.items||[];if(!t.length)return hideSearchSuggest();closeConnectionPanel(),e.replaceChildren(...t.map(e=>{const t=document.createElement("button");return t.className="suggest-item focusable",t.type="button",t.setAttribute("role","option"),t.innerHTML=`<b>${escapeHtml(e.title)}</b><span>${escapeHtml(e.meta||"")}</span>`,t.addEventListener("click",()=>applySearchSuggest(e.title)),t})),e.classList.add("open"),$("searchForm")&&$("searchForm").classList.add("suggesting")}function hideSearchSuggest(){clearTimeout(state.suggestions.timer),state.suggestions.timer=0,state.suggestions.seq+=1;const e=$("suggestPanel");if(e&&(e.classList.remove("open"),e.replaceChildren()),$("searchForm")&&$("searchForm").classList.remove("suggesting"),state.suggestions.items=[],state.suggestions.keyword="",state.suggestions.controller){try{state.suggestions.controller.abort()}catch(e){}state.suggestions.controller=null}}function applySearchSuggest(e){const t=String(e||"").trim();t&&($("searchInput").value=t,hideSearchSuggest(),searchTmdb(t))}function enableSearchEditing(){$("searchInput")&&($("searchInput").readOnly=!1)}function disableSearchEditing(){$("searchInput")&&($("searchInput").readOnly=!0)}function submitSearchInput(){const e=$("searchInput");e&&(enableSearchEditing(),searchTmdb(e.value))}function currentSearchKeyword(){const e=$("searchInput");return String(e&&e.value||"").trim()}function clearSearchHold(){state.searchHold.timer&&clearTimeout(state.searchHold.timer),state.searchHold.timer=0,state.searchHold.pointer=null,state.searchHold.target=null}function handleSearchNativeHoldStart(e){const t=$("searchSubmitBtn");t&&(e&&"mouse"===e.pointerType&&0!==e.button||(clearSearchHold(),state.searchHold.fired=!1,state.searchHold.target=t,state.searchHold.pointer=e&&null!=e.pointerId?{id:e.pointerId,x:e.clientX||0,y:e.clientY||0}:null,state.searchHold.timer=setTimeout(()=>{state.searchHold.timer=0,state.searchHold.fired=!0,state.searchHold.suppressClickUntil=Date.now()+800;const e=currentSearchKeyword();hideSearchSuggest(),nativeHomeSearch(e)},650)))}function handleSearchNativeHoldMove(e){const t=state.searchHold.pointer;if(!t||!e||t.id!==e.pointerId)return;const n=Math.abs((e.clientX||0)-t.x),a=Math.abs((e.clientY||0)-t.y);(n>12||a>12)&&clearSearchHold()}function handleSearchNativeHoldEnd(){const e=state.searchHold.fired;return clearSearchHold(),e}function consumeSearchSubmitEnterDown(e,t){return e===$("searchSubmitBtn")&&(t.preventDefault(),t.stopPropagation(),state.searchHold.timer||state.searchHold.fired||handleSearchNativeHoldStart(),!0)}function handleSearchSubmitEnterUp(e){return"Enter"===normalizeRemoteKey(e)&&state.searchHold.target===$("searchSubmitBtn")&&(e.preventDefault(),e.stopPropagation(),handleSearchNativeHoldEnd()?(state.searchHold.fired=!1,!0):(Date.now()<Number(state.searchHold.suppressClickUntil||0)||(state.searchHold.suppressClickUntil=Date.now()+180,submitSearchInput()),!0))}function handleSearchSubmitClick(e){if(Date.now()<Number(state.searchHold.suppressClickUntil||0)||state.searchHold.fired)return e.preventDefault(),e.stopPropagation(),void(state.searchHold.fired=!1);e.preventDefault(),submitSearchInput()}async function searchTmdb(e){const t=e.trim();if(t){hideSearchSuggest();try{setStatus("tmdb",`搜索 ${t}`);const e=((await requestJson(tmdbSearchUrl(t),18)).results||[]).filter(e=>"movie"===e.media_type||"tv"===e.media_type);state.searchItems=e.map((e,t)=>normalizeTmdb(e,{id:"search",title:"搜索",mediaType:e.media_type},t)).filter(hasPoster).slice(0,18),setStatus("tmdb",`搜索成功 ${state.searchItems.length} 条`),renderSearch(),focusSearchResultsAfterRender(),scheduleUiSnapshotSave()}catch(e){setStatus("tmdb","搜索失败:"+(e.message||"unknown")),toast("搜索失败")}}}function homeScrollTop(){return Math.round(window.scrollY||document.documentElement.scrollTop||document.body.scrollTop||0)}function homeFocusSnapshot(e,t){const n=e&&e.closest?e:null,a=n&&n.closest(".card[data-media-key]");if(a){const e=a.closest(".media-grid,.rail");return{type:"media",key:a.dataset.mediaKey||mediaDomKey(t),cardIndex:Number(a.dataset.cardIndex||-1),gridId:e&&(e.dataset.listId||e.id||"")||""}}const i=n&&n.closest("#chips .chip[data-chip-id]");if(i)return{type:"chip",key:i.dataset.chipId||""};const s=mediaDomKey(t);return s?{type:"media",key:s,cardIndex:-1,gridId:""}:n&&n.id?{type:"id",key:n.id}:{type:"",key:""}}function rememberHomeReturn(e,t){const n=t&&t.isConnected?t:document.activeElement;state.homeReturn={scrollY:homeScrollTop(),activeList:state.activeList||"all",mediaKey:mediaDomKey(e),focus:homeFocusSnapshot(n,e),at:Date.now()}}function refreshHomeReturnTimestamp(){state.homeReturn&&(state.homeReturn.at=Date.now())}function findHomeReturnMediaTarget(e,t){const n=t.key||e.mediaKey||"",a=n?Array.from(document.querySelectorAll(".app .card[data-media-key]")).filter(e=>String(e.dataset.mediaKey||"")===String(n)&&isVisibleFocusable(e)):[];if(t.gridId){const e=a.find(e=>{const n=e.closest(".media-grid,.rail");return n&&String(n.dataset.listId||n.id||"")===String(t.gridId)});if(e)return e}if(a.length)return a[0];const i="searchRail"===t.gridId?$("searchRail"):activeMediaGrid(),s=Number(t.cardIndex);if(!i||!Number.isFinite(s)||s<0)return null;let o=0;for(;i.querySelectorAll(".card").length<=s&&appendGridBatch(i)&&o<60;)o+=1;const r=i.querySelectorAll(".card")[s]||null;return isVisibleFocusable(r)?r:null}function findHomeReturnTarget(e){if(!e)return null;const t=e.focus||{};return"media"===t.type?findHomeReturnMediaTarget(e,t):"chip"===t.type?findByDataset($("chips"),"chipId",t.key):"id"===t.type&&t.key?$(t.key):e.activeList?findByDataset($("chips"),"chipId",e.activeList):firstContentFocus()}function applyHomeScrollTop(e){window.scrollTo(0,e),document.documentElement.scrollTop=e,document.body.scrollTop=e,updateBackTopButton()}function focusHomeReturnTarget(e){if(!isVisibleFocusable(e))return!1;state.remoteInitialFocused=!0;try{e.focus({preventScroll:!0})}catch(t){e.focus()}return maybeAppendGridForFocus(e),!0}function restoreHomeReturn(){const e=state.homeReturn;if(!e)return!1;if(Date.now()-Number(e.at||0)>432e5)return state.homeReturn=null,!1;state.homeReturn=null,e.activeList&&isKnownList(e.activeList)&&state.activeList!==e.activeList&&(state.activeList=e.activeList,normalizeActiveListForViewport(),renderAll({deferContent:!1}));const t=Math.max(0,Number(e.scrollY||0)),n=n=>{if($("detailSheet")&&$("detailSheet").classList.contains("active"))return;const a=n?findHomeReturnTarget(e):null;a&&focusHomeReturnTarget(a),applyHomeScrollTop(t)};return requestAnimationFrame(()=>n(!0)),setTimeout(()=>n(!0),80),setTimeout(()=>n(!1),240),setTimeout(()=>{n(!1),scheduleUiSnapshotSave()},520),!0}function openDetail(e,t){const n=t||{},a=$("detailSheet")&&$("detailSheet").classList.contains("active");n.restore||a||rememberHomeReturn(e,n.returnTarget),state.selected=e,state.detail=null,n.keepPan||resetPanSearch(),ensureSheetViewport($("detailSheet")),syncDetailLayout(),document.body.classList.add("detail-active"),$("detailSheet").classList.add("active"),$("detailSheet").setAttribute("aria-hidden","false"),$("mobileDetailBackBtn").classList.remove("is-hidden"),updateMobileDetailBackButton(),isNativeLeanbackClient()&&setTvMode(!0);try{renderDetailBase(e),clearDetailExtras()}catch(t){$("detailTitle").textContent=e&&e.title||"详情",clearDetailTitleLogo(),setDetailTextContent("详情渲染失败:"+(t.message||"unknown"))}n.skipHistory||"#detail"===location.hash||history.pushState({sheet:"detail"},"","#detail"),n.restore||rememberWatchIntent(e,"view"),setNativeToolbarVisible(!1,isNativeLeanbackClient()||isNativeMobileClient()),shouldRefreshRecentList()&&loadRecentList({silent:!0}).catch(()=>{}),loadDetail(e),scheduleUiSnapshotSave(),n.restore||setTimeout(()=>focusRemoteTarget(detailPrimaryActionButton()),40)}function ensureSheetViewport(e,t){e&&(e.style.position="fixed",e.style.top="0",e.style.right="0",e.style.bottom="0",e.style.left="0",e.style.width="100%",e.style.height="100vh",e.style.display=t||"block",e.style.zIndex="imageViewer"===e.id?"100":"60")}function renderDetailBase(e){clearInlineEpisodePreview({restoreDetail:!1}),resetDetailTextClamp(),$("detailTitle").textContent=e.title,prepareDetailTitleLogo();setDetailTextContent(e.desc||e.remark||""||""),renderDetailMeta(e,state.detail),renderDetailTitleMeta(e,state.detail),setDetailCoverCarousel(e.landscape?[e.landscape]:[],"",{allowPoster:!1}),updateDetailContinueButton(),scheduleDetailTextClamp()}function renderDetailMeta(e,t){!isTvMode()||useLargeDetailLayout()?$("detailMeta").replaceChildren(...detailMeta(e,t).map(e=>{const t=document.createElement("span");return t.className="meta-pill"+(e.strong?" strong":""),t.textContent=e.text||e,t})):$("detailMeta").replaceChildren()}function renderDetailTitleMeta(e,t){const n=$("detailTitleMeta"),a=useLargeDetailLayout()?detailTitleMeta(e,t).filter(e=>"score"===e.type).slice(0,1):isTvMode()?uniqueMeta(detailTitleMeta(e,t).concat(detailMeta(e,t))):detailTitleMeta(e,t);n.replaceChildren(...a.flatMap((e,t)=>{const n=document.createElement("span");if(n.className=e.type||"",n.textContent=e.text||e,0===t)return[n];const a=document.createElement("span");return a.className="sep",a.textContent="·",[a,n]}))}function isMobileDetailLogoCandidate(){return!(!document.documentElement.classList.contains("native-mobile-app")||useLargeDetailLayout())}function prepareDetailTitleLogo(){if(clearDetailTitleLogo(),!isMobileDetailLogoCandidate())return;const e=$("detailTitleLogo"),t=e&&e.closest?e.closest(".detail-title-row"):null;t&&t.classList.add("logo-pending")}function clearDetailTitleLogo(e){const t=e||{},n=$("detailTitleLogo"),a=n&&n.closest?n.closest(".detail-title-row"):null;a&&(a.classList.remove("has-logo"),t.keepPending||a.classList.remove("logo-pending")),n&&(n.onload=null,n.onerror=null,n.dataset.logoSrc="",n.removeAttribute("src"),n.alt="")}function renderDetailTitleLogo(e,t){const n=$("detailTitleLogo"),a=n&&n.closest?n.closest(".detail-title-row"):null;if(!isMobileDetailLogoCandidate())return void clearDetailTitleLogo();const i=bestDetailLogo(t);if(!n||!a||!i)return void clearDetailTitleLogo();const s=displayImage(i,{size:"w500"});if(!s)return void clearDetailTitleLogo();clearDetailTitleLogo({keepPending:!0});const o=e&&e.title||$("detailTitle")&&$("detailTitle").textContent||"详情";n.dataset.logoSrc=s,n.alt=o,n.onload=()=>{n.dataset.logoSrc===s&&(a.classList.remove("logo-pending"),a.classList.add("has-logo"))},n.onerror=()=>{n.dataset.logoSrc===s&&clearDetailTitleLogo()},n.src=s}function bestDetailLogo(e){const t=e&&e.images&&Array.isArray(e.images.logos)?e.images.logos:[];if(!t.length)return"";const n=String(e&&e.original_language||"").toLowerCase(),a=t.filter(e=>e&&e.file_path).sort((e,t)=>detailLogoScore(t,n)-detailLogoScore(e,n));return a[0]&&a[0].file_path||""}function detailLogoScore(e,t){const n=String(e&&e.iso_639_1||"").toLowerCase();let a=1e3;"zh"===n||"cn"===n?a=6e3:"en"===n?a=5e3:n&&t&&n===t?a=4500:n||(a=3500);const i=Number(e&&e.vote_average||0),s=Number(e&&e.vote_count||0),o=Number(e&&e.width||0);return a+100*i+2*Math.min(s,500)+Math.min(o,1200)/4}function setDetailCoverCarousel(e,t,n){const a=uniqueCoverImages(Array.isArray(e)?e:[e]);if(pauseDetailCoverCarousel(),state.detailCover.images=a,state.detailCover.index=0,state.detailCover.token+=1,setDetailCoverImage(a[0]||"",t,n),updateDetailCoverControls(),a.length>1){const e=state.detailCover.token;state.detailCover.timer=setInterval(()=>{e===state.detailCover.token&&$("detailSheet").classList.contains("active")&&"hidden"!==document.visibilityState&&switchDetailCover(1,{allowPoster:!1,keepLoading:!1})},5200)}}function updateDetailCoverControls(){const e=$("detailImage")&&$("detailImage").parentElement;if(!e)return;const t=state.detailCover.images.length>1;e.classList.toggle("has-multiple",t)}function shiftDetailCover(e){(state.detailCover.images||[]).length<=1||(pauseDetailCoverCarousel(),switchDetailCover(e,{allowPoster:!1,keepLoading:!1}),updateDetailCoverControls())}function switchDetailCover(e,t){const n=state.detailCover.images||[];if(n.length<=1)return;tryPreloadDetailCover(Math.max(0,Math.min(Number(state.detailCover.index||0),n.length-1)),e<0?-1:1,0,state.detailCover.token,t||{})}function tryPreloadDetailCover(e,t,n,a,i){const s=state.detailCover.images||[];if(a!==state.detailCover.token||!$("detailSheet").classList.contains("active"))return;if(!s.length||n>=s.length-1)return;const o=(e+t+s.length)%s.length,r=displayImage(s[o],{size:"w1280"});if(!r)return tryPreloadDetailCover(o,t,n+1,a,i);preloadImage(r,()=>{a===state.detailCover.token&&$("detailSheet").classList.contains("active")&&(state.detailCover.index=o,setDetailCoverImage(s[o],"",Object.assign({},i,{preloadedSrc:r})))},()=>tryPreloadDetailCover(o,t,n+1,a,i))}function preloadImage(e,t,n){const a=new Image;a.onload=t,a.onerror=n,a.src=e}function restartDetailCoverCarousel(){if(!$("detailSheet").classList.contains("active")||state.detailCover.timer||state.detailCover.images.length<=1)return;const e=state.detailCover.images.slice(),t=Math.max(0,Math.min(state.detailCover.index,e.length-1));state.detailCover.images=[],setDetailCoverCarousel(e.slice(t).concat(e.slice(0,t)),"",{allowPoster:!1,keepLoading:!1})}function setDetailCoverImage(e,t,n){const a=n||{},i=$("detailImage").parentElement,s=$("detailImage"),o=String(e||"").trim(),r=String(t||"").trim(),c=!0===a.allowPoster&&(!o||isSameImageSource(o,r)),l=c&&r||o,d=l?displayImage(l,{size:c?"w780":"w1280"}):"";i.classList.toggle("loading",!l&&!1!==a.keepLoading),i.classList.toggle("poster-mode",!!c&&!!l),i.dataset.coverMode=c?"poster":"landscape",i.style.setProperty("--detail-cover-bg",d?`url("${cssUrl(d)}")`:"none");const u=$("detailSheet");if(u&&(u.style.setProperty("--detail-hero-bg",d?`url("${cssUrl(d)}")`:"none"),c?(u.style.setProperty("--detail-hero-size","cover"),u.style.setProperty("--detail-hero-position","center top")):(u.style.setProperty("--detail-hero-size","auto 62vh"),u.style.setProperty("--detail-hero-position","center top"))),l){const e=a.preloadedSrc||d,t=()=>{s.onload=null,s.onerror=null,s.src=e,resetDetailCoverFrame(i),s.classList.add("active")};if(a.preloadedSrc)return void t();if(s.getAttribute("src")===e&&s.classList.contains("active"))return;preloadImage(e,t,()=>{s.getAttribute("src")||s.classList.remove("active")})}else s.onload=null,s.onerror=null,s.classList.remove("active"),s.removeAttribute("src"),resetDetailCoverFrame(i)}function syncDetailCoverFrame(e){resetDetailCoverFrame(e&&e.parentElement)}function resetDetailCoverFrame(e){e&&(e.style.width="",e.style.height="",e.style.minHeight="",e.style.maxHeight="")}function pauseDetailCoverCarousel(){state.detailCover.timer&&clearInterval(state.detailCover.timer),state.detailCover.timer=0,state.detailCover.token+=1}function stopDetailCoverCarousel(e){if(pauseDetailCoverCarousel(),state.detailCover.images=[],state.detailCover.index=0,updateDetailCoverControls(),e){const e=$("detailImage"),t=e.parentElement;e.onload=null,e.classList.remove("active"),e.removeAttribute("src"),t.classList.remove("loading","poster-mode"),delete t.dataset.coverMode,t.style.setProperty("--detail-cover-bg","none"),$("detailSheet")&&$("detailSheet").style.setProperty("--detail-hero-bg","none"),resetDetailCoverFrame(t)}}function uniqueCoverImages(e){const t=new Set;return(e||[]).map(e=>String(e||"").trim()).filter(e=>{const n=tmdbImagePath(e)||e;return!(!n||t.has(n))&&(t.add(n),!0)})}function isSameImageSource(e,t){const n=tmdbImagePath(e)||String(e||"").trim(),a=tmdbImagePath(t)||String(t||"").trim();return!!n&&!!a&&n===a}function cssUrl(e){return String(e||"").replace(/["\\\n\r]/g,"")}function detailMeta(e,t){const n=t||{},a="tv"===e.mediaType?"剧集":"电影",i=n.first_air_date||n.release_date||e.releaseDate||"",s=(n.genres||[]).map(e=>e&&e.name).filter(Boolean).slice(0,2),o=detailRuntime(n,e),r="tv"===e.mediaType&&n.number_of_seasons?`${n.number_of_seasons}季`:"";if(useLargeDetailLayout()){const t=String(i||"").slice(0,4),r=s.length?s.slice(0,3).join(" / "):a,c="tv"===e.mediaType?detailLargeEpisodeLabel(n):o,l=detailStatus(n.status||"");return uniqueMeta([t,r,c,l&&"已完结"!==l?l:"",o&&"tv"===e.mediaType?o:""]).slice(0,6).map(e=>"string"==typeof e?{text:e}:e)}const c=[detailDateLabel(e,i),r,o].filter(Boolean);return s.forEach(e=>c.push(e)),uniqueMeta(c).slice(0,8).map(e=>"string"==typeof e?{text:e}:e)}function detailTitleMeta(e,t){const n=t||{},a="tv"===e.mediaType?"剧集":"电影",i=Number(n.vote_average||e.voteAverage||0),s="tv"===e.mediaType?detailEpisodeProgress(n):"",o=detailStatus(n.status||"");return[i>0?{text:`${i.toFixed(1)}分`,type:"score"}:null,{text:a},s?{text:s}:null,o?{text:o}:null].filter(Boolean)}function detailRuntime(e,t){const n=("tv"===t.mediaType?e.episode_run_time||[]:e.runtime?[e.runtime]:[]).find(e=>Number(e)>0);return n?"tv"===t.mediaType?`每集${Number(n)}分钟`:`${Number(n)}分钟`:""}function detailEpisodeProgress(e){const t=Number(e.number_of_episodes||0),n=Math.max(Number(e.last_episode_to_air&&e.last_episode_to_air.episode_number||0),airedEpisodeFromSeason(e));return n&&t?`${n}/${t}集`:t?`共${t}集`:n?`更新至${n}集`:""}function detailLargeEpisodeLabel(e){const t=Number(e&&e.number_of_episodes||0),n=Math.max(Number(e&&e.last_episode_to_air&&e.last_episode_to_air.episode_number||0),airedEpisodeFromSeason(e)),a=detailStatus(e&&e.status||"");return t&&("已完结"===a||n>=t)?`${t}集全`:n&&t?`${n}/${t}集`:n?`更新至${n}集`:t?`${t}集`:""}function airedEpisodeFromSeason(e){const t=e&&(e["season/1"]||e.season_1),n=t&&Array.isArray(t.episodes)?t.episodes:[];if(!n.length)return 0;const a=dateOnlyMs(today());return n.reduce((e,t)=>{const n=dateOnlyMs(t&&t.air_date);return!n||n>a?e:Math.max(e,Number(t.episode_number||0))},0)}function detailStatus(e){return{"Returning Series":"更新中",Ended:"已完结",Canceled:"已取消",Cancelled:"已取消","In Production":"制作中",Planned:"计划中",Released:"已上映","Post Production":"后期制作"}[e]||e||""}function detailDateLabel(e,t){return t?`${"tv"===e.mediaType?"首播":"上映"} ${formatDateCn(t)}`:""}function formatDateCn(e){const t=String(e||"").match(/^(\d{4})-(\d{2})-(\d{2})$/);return t?`${t[1]}年${Number(t[2])}月${Number(t[3])}日`:e||""}function dateOnlyMs(e){const t=String(e||"").match(/^(\d{4})-(\d{2})-(\d{2})$/);return t?new Date(Number(t[1]),Number(t[2])-1,Number(t[3])).getTime():0}function uniqueMeta(e){const t=new Set;return e.filter(e=>{const n="string"==typeof e?e:e&&e.text,a=String(n||"").trim();return!(!a||t.has(a))&&(t.add(a),!0)})}function clearDetailExtras(){["seasonBlock","castBlock","personWorkBlock","recommendBlock"].forEach(e=>$(e).style.display="none"),["seasonTabs","episodeRail","castRail","personInfo","personWorkRail","recommendWorkRail"].forEach(e=>$(e).replaceChildren())}async function loadDetail(e){try{const t=await requestJson(tmdbDetailUrl(e),18);if(!t||state.selected!==e)return;state.detail=t,renderDetailExtras(e,t)}catch(e){clearDetailTitleLogo(),setDetailTextContent(`详情加载失败:${e.message||"unknown"}`),scheduleDetailTextClamp(),toast("详情加载失败")}}function renderDetailExtras(e,t){const n=t.overview||e.desc||e.remark;n&&setDetailTextContent(n),renderDetailMeta(e,t),renderDetailTitleMeta(e,t),renderDetailTitleLogo(e,t),scheduleDetailTextClamp(),renderDetailCoverFromDetail(e,t),renderCast(t.credits&&t.credits.cast||[]),"tv"===e.mediaType&&renderSeasons(e,t),loadRecommendations(e),normalizeRails(),updateDetailContinueButton(),updatePostPanFocusState()}function detailPrimaryActionButton(){return isVisibleFocusable($("detailContinueBtn"))?$("detailContinueBtn"):$("detailSearchBtn")}function scheduleDetailTextClamp(){requestAnimationFrame(()=>requestAnimationFrame(updateDetailTextClamp))}function isMobileDetailSheetActive(e){const t=e||$("detailSheet");return!(!(document.documentElement.classList.contains("native-mobile-app")&&t&&t.classList.contains("active"))||t.classList.contains("detail-large"))}function detailTextPlain(e){return String(e&&e.textContent||"").replace(/\s+/g,"").trim()}function setDetailTextContent(e){const t=$("detailText");t&&(t.dataset.fullText=String(e||""),t.textContent=t.dataset.fullText,t.removeAttribute("data-detail-toggle"),t.removeAttribute("data-more-label"))}function renderMobileDetailText(e,t){const n=$("detailText"),a=$("detailMoreBtn");if(!n||!a)return!1;const i=String(n.dataset.fullText||n.textContent||""),s=i.replace(/\s+/g,"").trim(),o=t||{};n.textContent!==i&&(n.textContent=i),n.removeAttribute("data-more-label");const r=parseFloat(getComputedStyle(n).lineHeight||"21")||21,c=Math.round(4*r+Math.max(4,.16*r));if(!s)return n.textContent=i,n.removeAttribute("data-detail-toggle"),n.classList.remove("clamped"),a.style.display="none",!1;n.style.setProperty("--detail-text-max",`${c}px`);return o.forceToggle||n.scrollHeight>c+1?(n.dataset.detailToggle=e?"collapse":"expand",n.classList.toggle("clamped",!e),a.dataset.expanded=e?"1":"",a.textContent=e?"收起":"更多",a.style.display="inline-flex",a.style.visibility="",!0):(n.removeAttribute("data-detail-toggle"),n.classList.remove("clamped"),a.style.display="none",!1)}function resetDetailTextClamp(){const e=$("detailText"),t=$("detailMoreBtn");e&&(e.classList.remove("clamped"),e.removeAttribute("data-detail-toggle"),e.removeAttribute("data-more-label"),e.style.removeProperty("--detail-text-max"),e.style.removeProperty("--episode-preview-text-max")),t&&(t.dataset.expanded="",t.style.display="none",t.style.visibility="",t.textContent="更多")}function measureDetailMoreHeight(e){const t=e.style.display,n=e.style.visibility;e.style.display="inline-flex",e.style.visibility="hidden";const a=e.offsetHeight||30;return e.style.display=t,e.style.visibility=n,a}function detailTextClampLimit(){return useLargeDetailLayout()?210:150}function detailTextShouldClampByLength(e){return detailTextPlain(e).length>detailTextClampLimit()}function updateDetailTextClamp(){const e=$("detailSheet"),t=$("detailText"),n=$("detailMoreBtn"),a=n&&n.closest(".detail-info")&&n.closest(".detail-info").nextElementSibling;if(!(e&&t&&n&&a&&e.classList.contains("active")))return;if(state.episodePreview&&state.episodePreview.active)return void updateInlineEpisodePreviewClamp();const i=isMobileDetailSheetActive(e);if("1"===n.dataset.expanded)return i?void renderMobileDetailText(!0,{forceToggle:!0}):(t.classList.remove("clamped"),t.removeAttribute("data-more-label"),t.style.removeProperty("--detail-text-max"),n.style.display=i?"none":"inline-flex",n.style.visibility="",void(n.textContent="收起"));if(t.classList.remove("clamped"),t.removeAttribute("data-more-label"),t.style.removeProperty("--detail-text-max"),n.style.display="none",n.style.visibility="",n.textContent="更多",i)return void renderMobileDetailText(!1);const s=e.getBoundingClientRect(),o=a.getBoundingClientRect(),r=t.getBoundingClientRect(),c=Math.min(s.bottom,s.top+(e.clientHeight||window.innerHeight||0))-Math.max(58,.06*(window.innerHeight||0)),l=o.bottom-c,d=t.scrollHeight,u=parseFloat(getComputedStyle(t).lineHeight||"21")||21,m=Math.max(44,2.05*u),p=detailTextShouldClampByLength(t);if(l<=0&&!p)return;if(d<=m+1)return;const h=u*(useLargeDetailLayout()?4.2:3.15),f=l>0?r.height-l-measureDetailMoreHeight(n)-6:d;let y=Math.max(m,Math.min(p?h:d,f));y>=d-2||(t.style.setProperty("--detail-text-max",`${Math.round(y)}px`),t.classList.add("clamped"),t.setAttribute("data-more-label","更多"),n.style.display=i?"none":"inline-flex",n.style.visibility="")}function toggleDetailTextMore(){if(state.episodePreview&&state.episodePreview.active)return toggleInlineEpisodePreviewExpanded(),void scheduleUiSnapshotSave();const e=$("detailMoreBtn");e&&(e.dataset.expanded="1"===e.dataset.expanded?"":"1",updateDetailTextClamp(),scheduleUiSnapshotSave())}function handleDetailTextClick(){const e=$("detailSheet"),t=$("detailText"),n=$("detailMoreBtn");if(!e||!t||!n)return;isMobileDetailSheetActive(e)&&t.getAttribute("data-detail-toggle")&&(n.dataset.expanded="1"===n.dataset.expanded?"":"1",updateDetailTextClamp(),scheduleUiSnapshotSave())}function useInlineEpisodePreview(){const e=$("detailSheet");return!!(e&&e.classList.contains("active")&&e.classList.contains("detail-large")&&useLargeDetailLayout())}function episodePreviewTitle(e){const t=e&&e.episode_number?`第${e.episode_number}集`:"分集剧情",n=String(e&&e.name||"").trim();return n?`${t} ${n}`:t}function episodePreviewMeta(e){return[e&&e.air_date?formatDateCn(e.air_date):"",state.selected&&state.selected.title||""].filter(Boolean).join(" · ")}function renderEpisodePreviewTitleMeta(e){const t=$("detailTitleMeta");if(!t)return;if(t.replaceChildren(),!e)return;const n=document.createElement("span");n.textContent=e,t.appendChild(n)}function applyInlineEpisodePreview(e,t){if(!useInlineEpisodePreview())return!1;const n=(state.episodeViewer.episodes||[])[e];if(!n)return!1;const a=t||{},i=$("detailSheet"),s=$("detailText"),o=s&&s.closest(".detail-info"),r=currentEpisodePreviewAnchor(),c=r?r.getBoundingClientRect().top:0,l=state.episodePreview.infoHeight||measureEpisodePreviewInfoHeight(o);state.episodePreview.active=!0,state.episodePreview.expanded=!!a.expanded,state.episodePreview.index=e,state.episodePreview.episodeNumber=String(n.episode_number||""),state.episodePreview.lastEpisodeNumber=String(n.episode_number||"")||state.episodePreview.lastEpisodeNumber||"",state.episodePreview.infoHeight=l,state.episodeViewer.index=e,state.episodeViewer.episodeNumber=String(n.episode_number||""),i.classList.add("episode-preview-active"),i.classList.toggle("episode-preview-expanded",state.episodePreview.expanded),o&&l&&setEpisodePreviewInfoHeight(o,l),$("detailTitle").textContent=episodePreviewTitle(n),renderEpisodePreviewTitleMeta(episodePreviewMeta(n)),$("detailMeta").replaceChildren();const d=n.overview||"暂无剧情概要";s.textContent=d,pauseDetailCoverCarousel();const u=episodeFullStill(n),m=state.detailCover.images&&state.detailCover.images[state.detailCover.index]||state.selected&&state.selected.landscape||"";return setDetailCoverImage(u||m,"",{allowPoster:!1,keepLoading:!1}),preserveEpisodePreviewAnchor(r,c),syncEpisodePreviewLayout(o),!0}function measureEpisodePreviewInfoHeight(e){if(!e)return 0;const t=e.getBoundingClientRect?e.getBoundingClientRect():null,n=t&&t.height||e.offsetHeight||0;return Math.max(0,Math.round(n))}function useLegacyEpisodePreviewLayout(){const e=document.documentElement;return!(!e||!e.classList.contains("no-css-functions")&&!e.classList.contains("legacy-detail-layout"))}function setEpisodePreviewInfoHeight(e,t){if(e){if(useLegacyEpisodePreviewLayout()){const n=Math.max(180,Math.min(240,Number(t||0)||220));return e.style.height=`${n}px`,void(e.style.maxHeight=`${n}px`)}e.style.setProperty("--episode-preview-info-height",`${t}px`)}}function updateEpisodePreviewPosition(e){if(!e||!e.getBoundingClientRect)return;const t=$("detailSheet");if(!t||!t.getBoundingClientRect)return void(e.style.transform="");e.style.transform="";const n=e.getBoundingClientRect(),a=t.getBoundingClientRect?t.getBoundingClientRect():{top:0},i=window.getComputedStyle?getComputedStyle(t):null,s=i&&parseFloat(i.paddingTop||"0")||0,o=a.top+s,r=Math.round(o-n.top);e.style.transform=Math.abs(r)>1?`translateY(${r}px)`:""}function syncEpisodePreviewLayout(e){state.episodePreview&&state.episodePreview.active&&(updateEpisodePreviewPosition(e),updateInlineEpisodePreviewClamp(),e&&requestAnimationFrame(()=>{state.episodePreview&&state.episodePreview.active&&e.isConnected&&(updateEpisodePreviewPosition(e),updateInlineEpisodePreviewClamp(),requestAnimationFrame(()=>{state.episodePreview&&state.episodePreview.active&&e.isConnected&&(updateEpisodePreviewPosition(e),updateInlineEpisodePreviewClamp())}))}))}function currentEpisodePreviewAnchor(){const e=document.activeElement,t=$("episodeRail");return e&&t&&t.contains(e)&&e.getBoundingClientRect?e:null}function lastEpisodeFocusTarget(){const e=$("episodeRail");if(!e)return null;const t=state.episodePreview&&state.episodePreview.lastEpisodeNumber||state.episodeViewer&&state.episodeViewer.episodeNumber||"",n=t?findByDataset(e,"episodeNumber",t):null;return isVisibleFocusable(n)?n:e.querySelector(".episode-card.focusable")}function preserveEpisodePreviewAnchor(e,t){const n=$("detailSheet");if(!(n&&e&&e.isConnected&&n.contains(e)&&Number.isFinite(t)))return;const a=e.getBoundingClientRect().top-t;Math.abs(a)>.5&&(n.scrollTop+=a)}function updateInlineEpisodePreviewClamp(){const e=$("detailSheet"),t=$("detailText"),n=$("detailMoreBtn");if(!e||!t||!n)return;if(n.dataset.expanded="",n.style.display="inline-flex",n.style.visibility="",!state.episodePreview||!state.episodePreview.active)return;const a=parseFloat(getComputedStyle(t).lineHeight||"28")||28,i=t.getBoundingClientRect?t.getBoundingClientRect():null,s=t.closest(".detail-info"),o=s&&s.getBoundingClientRect?s.getBoundingClientRect():null,r=s&&s.nextElementSibling,c=r&&r.getBoundingClientRect?r.getBoundingClientRect():null,l=$("seasonBlock"),d=l&&"none"!==l.style.display&&l.getBoundingClientRect?l.getBoundingClientRect():null,u=d&&d.top||c&&c.bottom||o&&o.bottom||0,m=i&&o?u-i.top-(state.episodePreview&&state.episodePreview.expanded?18:22):5.25*a,p=useLegacyEpisodePreviewLayout()?4:Math.max(3,Math.floor(Math.max(3*a,m)/a)),h=Math.round(p*a);if(useLegacyEpisodePreviewLayout()?t.style.maxHeight=`${h}px`:t.style.setProperty("--episode-preview-text-max",`${h}px`),state.episodePreview.expanded)return t.classList.remove("clamped"),t.removeAttribute("data-more-label"),t.style.removeProperty("--episode-preview-text-max"),t.style.maxHeight="",void(n.textContent="收起");const f=t.scrollHeight>h+2||detailTextShouldClampByLength(t);t.classList.toggle("clamped",f),f?t.setAttribute("data-more-label","更多"):t.removeAttribute("data-more-label"),n.textContent=f?"更多":"",n.style.display=f?"inline-flex":"none"}function toggleInlineEpisodePreviewExpanded(){if(!state.episodePreview||!state.episodePreview.active)return!1;const e=Number(state.episodePreview.index);return!(!Number.isFinite(e)||e<0)&&applyInlineEpisodePreview(e,{expanded:!state.episodePreview.expanded})}function collapseInlineEpisodePreview(e){return!!(state.episodePreview&&state.episodePreview.active&&state.episodePreview.expanded)&&(e&&(e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation&&e.stopImmediatePropagation()),applyInlineEpisodePreview(Number(state.episodePreview.index),{expanded:!1}),!0)}function clearInlineEpisodePreview(e){const t=e||{},n=$("detailSheet");n&&n.classList.remove("episode-preview-active","episode-preview-expanded"),state.episodePreview.active=!1,state.episodePreview.expanded=!1,state.episodePreview.index=-1,state.episodePreview.episodeNumber="",state.episodePreview.infoHeight=0;const a=$("detailText");if(a){a.style.removeProperty("--episode-preview-text-max"),a.style.maxHeight="",a.classList.remove("clamped"),a.removeAttribute("data-more-label");const e=a.closest(".detail-info");e&&(e.style.removeProperty("--episode-preview-info-height"),e.style.height="",e.style.maxHeight="",e.style.transform="")}t.restoreDetail&&restoreBaseDetailView()}function restoreBaseDetailView(){const e=state.selected;if(!e)return;resetDetailTextClamp(),$("detailTitle").textContent=e.title||"详情";const t=state.detail;setDetailTextContent(t&&t.overview||e.desc||e.remark||""),renderDetailMeta(e,t),renderDetailTitleMeta(e,t),t?renderDetailCoverFromDetail(e,t):setDetailCoverCarousel(e.landscape?[e.landscape]:[],"",{allowPoster:!1}),scheduleDetailTextClamp()}function renderDetailCoverFromDetail(e,t){const n=bestDetailBackdrops(t,8),a=n[0]||"",i=imageUrl(t.poster_path,!1)||e.pic||e.pic||"";n.length?(e.landscape=a,e.pic=e.pic||i,setDetailCoverCarousel(n,i,{allowPoster:!1})):(e.landscape="",e.pic=e.pic||i,setDetailCoverCarousel([],i,{allowPoster:!0,keepLoading:!1})),preloadDetailPlaybackArtwork()}function bestDetailBackdrops(e,t){const n=[];return e&&e.backdrop_path&&n.push({file_path:e.backdrop_path,vote_average:11,vote_count:Number.MAX_SAFE_INTEGER,width:1280,height:720}),(e&&e.images&&e.images.backdrops||[]).forEach(e=>{e&&e.file_path&&n.push(e)}),n.filter(e=>e&&e.file_path).sort((e,t)=>backdropScore(t)-backdropScore(e)).slice(0,t||8).map(e=>imageUrl(e.file_path,!0))}function backdropScore(e){const t=Number(e&&e.vote_average||0),n=Number(e&&e.vote_count||0),a=Number(e&&e.width||0),i=Number(e&&e.height||0),s=a>0&&i>0?a/i:16/9,o=1.4*Math.abs(s-16/9);return 1e3*t+2*Math.min(n,1e3)+Math.min(a,3840)/20-100*o}function renderCast(e){const t=e.filter(e=>e.profile_path).slice(0,18);t.length&&($("castBlock").style.display="",$("castRail").replaceChildren(...t.map(e=>{const t=document.createElement("button");t.className="person-card focusable",t.type="button";const n=displayImage(imageUrl(e.profile_path,!1),{size:"w185"});return t.innerHTML=`\n <img alt="" ${imageAttrs(n)}>\n <div><b>${escapeHtml(e.name)}</b><span>${escapeHtml(e.character||e.known_for_department||"")}</span></div>\n `,t.addEventListener("click",()=>loadPersonWorks(e)),t})))}function renderSeasons(e,t){const n=(t.seasons||[]).filter(e=>e.season_number>0);if(!n.length)return;$("seasonBlock").style.display="";const a=document.activeElement,i=a&&$("seasonTabs").contains(a)&&a.dataset.seasonNumber||"",s=1===n.length;s?$("seasonTabs").replaceChildren():$("seasonTabs").replaceChildren(...n.map((t,n)=>{const a=document.createElement("button");return a.className="chip focusable"+(0===n?" active":""),a.type="button",a.dataset.seasonNumber=String(t.season_number),a.textContent=t.name||"第 "+t.season_number+" 季",a.addEventListener("click",()=>{document.querySelectorAll("#seasonTabs .chip").forEach(e=>e.classList.remove("active")),a.classList.add("active"),loadSeason(e,t.season_number)}),a})),i&&!s&&requestAnimationFrame(()=>focusRemoteTarget(findByDataset($("seasonTabs"),"seasonNumber",i)||$("seasonTabs").querySelector(".chip.active")||$("seasonTabs").querySelector(".chip")));const o=t["season/1"]||null;o&&o.episodes?renderEpisodes(o.episodes):loadSeason(e,n[0].season_number)}async function loadSeason(e,t){try{renderEpisodes((await requestJson(tmdbSeasonUrl(e,t),18)).episodes||[])}catch(e){$("episodeRail").replaceChildren(emptyNode("分集加载失败"))}updatePostPanFocusState()}function renderEpisodes(e){state.episodePreview&&state.episodePreview.active&&clearInlineEpisodePreview({restoreDetail:!0});const t=document.activeElement,n=t&&$("episodeRail").contains(t)&&t.dataset.episodeNumber||"",a=$("imageViewer")&&$("imageViewer").classList.contains("active")&&$("imageViewer").classList.contains("episode-mode")?String(state.episodeViewer.episodeNumber||""):"";if(state.episodeViewer.episodes=Array.isArray(e)?e.slice():[],state.episodeViewer.effectiveIndexes=episodeEffectiveIndexes(state.episodeViewer.episodes),a){const e=state.episodeViewer.episodes.findIndex(e=>String(e&&e.episode_number||"")===a);state.episodeViewer.index=e,state.episodeViewer.episodeNumber=e>=0?a:""}else{const e=state.episodePreview&&state.episodePreview.lastEpisodeNumber||"",t=e?state.episodeViewer.episodes.findIndex(t=>String(t&&t.episode_number||"")===e):-1;state.episodeViewer.index=t,state.episodeViewer.episodeNumber=t>=0?e:""}e.length?($("episodeRail").replaceChildren(...e.map((e,t)=>{const n=e.still_path?imageUrl(e.still_path,!0):"",a=n?displayImage(n,{size:"w300"}):"",i=document.createElement("button");return i.className="episode-card focusable"+(a?" has-still":""),i.type="button",i.dataset.episodeNumber=String(e.episode_number||""),i.innerHTML=`\n <span class="episode-badge">第${escapeHtml(e.episode_number||"?")}集</span>\n ${a?`<div class="episode-still-wrap"><img class="episode-still" alt="" ${imageAttrs(a)}></div>`:""}\n <div class="episode-body">\n <b>${e.episode_number}. ${escapeHtml(e.name||"未命名")}</b>\n <span>${escapeHtml(e.air_date||"")}</span>\n <p>${escapeHtml(e.overview||"暂无剧情")}</p>\n </div>\n `,i.addEventListener("focus",()=>{applyInlineEpisodePreview(t,{expanded:!1})}),i.addEventListener("blur",()=>{setTimeout(()=>{const e=$("episodeRail");state.episodePreview&&state.episodePreview.active&&e&&!e.contains(document.activeElement)&&clearInlineEpisodePreview({restoreDetail:!0})},0)}),i.addEventListener("click",e=>{if(useInlineEpisodePreview())return e.preventDefault(),e.stopPropagation(),void(state.episodePreview.active&&Number(state.episodePreview.index)===t?toggleInlineEpisodePreviewExpanded():applyInlineEpisodePreview(t,{expanded:!1}));openEpisodeViewer(t)}),i})),n&&requestAnimationFrame(()=>focusRemoteTarget(findByDataset($("episodeRail"),"episodeNumber",n)||$("episodeRail").querySelector(".episode-card"))),updatePostPanFocusState()):$("episodeRail").replaceChildren(emptyNode("暂无分集信息"))}function isEffectiveEpisode(e,t){if(!e)return!1;const n=String(e.air_date||"").trim();if(n){const e=dateOnlyMs(n),t=dateOnlyMs(today());if(e)return e<=t}return t>0?Number(e.episode_number||0)>0&&Number(e.episode_number||0)<=t:!(!e.still_path&&!String(e.overview||"").trim())}function episodeEffectiveIndexes(e){const t=dateOnlyMs(today()),n=(Array.isArray(e)?e:[]).reduce((e,n)=>{const a=dateOnlyMs(n&&n.air_date);return!a||a>t?e:Math.max(e,Number(n&&n.episode_number||0))},0),a=[];return(Array.isArray(e)?e:[]).forEach((e,t)=>{isEffectiveEpisode(e,n)&&a.push(t)}),a.length?a:(e||[]).map((e,t)=>t)}function episodeFullStill(e){const t=e&&e.still_path?imageUrl(e.still_path,!0):"";return t?displayImage(t,{size:"w780"}):""}function episodeViewerPayload(e){const t=episodeFullStill(e);return{title:`${e.episode_number||""}${e.episode_number?". ":""}${e.name||"未命名"}`,meta:[e.air_date||"",state.selected&&state.selected.title||""].filter(Boolean).join(" · "),overview:e.overview||"暂无剧情概要",still:t}}function openEpisodeViewer(e){const t=(state.episodeViewer.episodes||[])[e];if(!t)return;state.episodeViewer.index=e,state.episodeViewer.episodeNumber=String(t.episode_number||"");const n=episodeViewerPayload(t);openImage(n.still||"",{episode:n})}function currentEpisodeViewerIndex(){const e=state.episodeViewer.episodes||[],t=String(state.episodeViewer.episodeNumber||"");if(t){const n=e.findIndex(e=>String(e&&e.episode_number||"")===t);if(n>=0)return n}const n=Number(state.episodeViewer.index);return Number.isFinite(n)&&n>=0?n:0}function renderEpisodeViewerContent(e){const t=$("episodeViewer");if(!t)return;const n=e&&e.still||"";t.style.display="grid",t.classList.toggle("no-still",!n),t.innerHTML=`\n ${n?`<img alt="" ${imageAttrs(n)}>`:""}\n <div>\n <h3>${escapeHtml(e&&e.title||"分集剧情")}</h3>\n ${e&&e.meta?`<span>${escapeHtml(e.meta)}</span>`:""}\n </div>\n <p>${escapeHtml(e&&e.overview||"暂无剧情概要")}</p>\n `}function switchEpisodeViewer(e){const t=$("imageViewer");if(!t||!t.classList.contains("active")||!t.classList.contains("episode-mode"))return!1;const n=state.episodeViewer.episodes||[];if(n.length<=1)return!1;const a=currentEpisodeViewerIndex(),i=(state.episodeViewer.effectiveIndexes||[]).filter(e=>e>=0&&e<n.length),s=i.length?i:n.map((e,t)=>t);if(s.length<=1)return!1;let o=s.indexOf(a);o<0&&(o=e>0?s.findIndex(e=>e>a)-1:s.findIndex(e=>e>=a),o<0&&(o=e>0?s.length-1:0));const r=s[(o+e+s.length)%s.length];state.episodeViewer.index=r,state.episodeViewer.episodeNumber=String(n[r].episode_number||""),renderEpisodeViewerContent(episodeViewerPayload(n[r]));const c=$("imageContent");c&&(c.scrollTop=0);const l=findByDataset($("episodeRail"),"episodeNumber",String(n[r].episode_number||""));return l&&(state.focusReturnEl=l),scheduleUiSnapshotSave(),!0}async function loadPersonWorks(e){try{$("personWorkTitle").textContent="简介",$("personWorkBlock").style.display="",renderPersonInfo(e,null),$("personWorkRail").replaceChildren(emptyNode("加载中..."));const t=await requestJson(tmdbPersonDetailUrl(e.id),18);renderPersonInfo(e,t);const n=((t.combined_credits||t).cast||[]).filter(e=>("movie"===e.media_type||"tv"===e.media_type)&&e.poster_path).slice(0,18).map((e,t)=>normalizeTmdb(e,{id:"person",title:"关联作品",mediaType:e.media_type},t));fillRail($("personWorkRail"),n),updatePostPanFocusState()}catch(t){renderPersonInfo(e,null),$("personWorkRail").replaceChildren(emptyNode("关联作品加载失败")),updatePostPanFocusState()}}async function loadRecommendations(e){const t=$("recommendBlock"),n=$("recommendWorkRail");if(t&&n&&e&&e.tmdbId&&e.mediaType)try{const a=await requestJson(tmdbRecommendationsUrl(e),18);if(state.selected!==e)return;const i=(a.results||[]).map((t,n)=>{const a=t.media_type||e.mediaType;return"movie"!==a&&"tv"!==a||!t.poster_path?null:normalizeTmdb(t,{id:"recommend",title:"相关推荐",mediaType:a},n)}).filter(Boolean).slice(0,18);if(!i.length)return t.style.display="none",void n.replaceChildren();t.style.display="",fillRail(n,i),updatePostPanFocusState()}catch(a){state.selected===e&&(t.style.display="none",n.replaceChildren())}}function renderPersonInfo(e,t){const n=$("personInfo");if(!n)return;const a=t&&t.biography||"暂无人物简介";n.innerHTML=`\n <div class="person-info" aria-live="polite">\n <div class="person-info-body">\n <p>${escapeHtml(a)}</p>\n </div>\n </div>\n `}function resetPanSearch(){resetPanSearchState(!0)}function resetPanSearchState(e){state.pan.observer&&(state.pan.observer.disconnect(),state.pan.observer=null),clearTimeout(state.pan.flushTimer),state.pan.flushTimer=0,state.pan.pollTimers.forEach(e=>clearTimeout(e)),state.pan.pollTimers=[],state.pan.pollRound=0,state.pan.loading=!1,state.pan.results=[],state.pan.activeType="",state.pan.health={},state.pan.pending={},state.pan.queued.clear(),state.pan.inFlight.clear(),state.pan.keyword="",state.pan.viewToken="",state.pan.renderKeys="",state.pan.tabKeys="",state.pan.focusKey="",state.pan.focusMode="",state.pan.lastTypeSelect=null,state.pan.keepBlockPositionUntil=0,state.pan.playbackReturn=null,e&&$("panSearchBlock")&&($("panSearchBlock").classList.remove("active"),$("panSearchBlock").style.display="none"),e&&updatePostPanFocusState(),e&&($("panSearchHint")&&($("panSearchHint").textContent=""),$("panTabs")&&$("panTabs").replaceChildren(),$("panResultList")&&$("panResultList").replaceChildren())}function panKeyword(e){return String(e&&e.title||"").trim()}async function searchPanResources(e){if(!e||state.pan.loading)return;const t=panKeyword(e);if(!t)return toast("缺少搜索标题");const n=state.pan.results.length>0&&$("panSearchBlock")&&$("panSearchBlock").classList.contains("active");resetPanSearchState(!1),state.pan.loading=!0,state.pan.keyword=t;const a=`pan-${Date.now()}`;state.pan.viewToken=a,state.pan.results=[],state.pan.activeType="",state.pan.health={},state.pan.pending={},state.pan.queued.clear(),state.pan.inFlight.clear(),state.pan.focusMode="tabs",state.pan.pollTimers.forEach(e=>clearTimeout(e)),state.pan.pollTimers=[],state.pan.pollRound=0,$("panSearchBlock")&&($("panSearchBlock").classList.add("active"),$("panSearchBlock").style.display=""),updatePostPanFocusState(),centerPanSearchBlock(),!n&&$("panTabs")&&$("panTabs").replaceChildren(),!n&&$("panResultList")&&$("panResultList").replaceChildren(emptyNode("正在搜索盘搜资源...")),$("panSearchHint").textContent=`${t} · 搜索中`,setPanStatus(`搜索 ${t}`);try{const n=panSearchPayload(t,state.pan.config||defaultPanConfig()),i=await ensurePanAuthHeaders(),s=await postJson(panApi("/api/search"),n,28,i);if(state.pan.viewToken!==a||state.selected!==e)return;const o=applyPanSearchBody(s,t);setPanStatus(o.length?`找到 ${o.length} 条`:"无资源"),renderPanResults(),focusFirstPanTab(),scheduleUiSnapshotSave(),schedulePanPolling(a,e)}catch(t){if(state.pan.viewToken!==a||state.selected!==e)return;String(t.message||"").includes("401")&&state.pan.config&&(state.pan.config.token="",state.pan.config.tokenExpiresAt=0,await persistPanConfigQuietly()),state.pan.results=[],$("panResultList").replaceChildren(emptyNode("盘搜失败:"+(t.message||"unknown"))),setPanStatus("搜索失败")}finally{state.pan.viewToken===a&&(state.pan.loading=!1)}}function focusFirstPanResult(){const e=$("panResultList")&&$("panResultList").querySelector(".pan-result-item");e&&requestAnimationFrame(()=>focusRemoteTarget(e))}function applyPanSearchBody(e,t){const n=e&&e.data?e.data:e,a=normalizePanResults(n&&n.merged_by_type||{},t),i=new Map(state.pan.results.map(e=>[e.key,e]));return a.forEach(e=>{const t=i.get(e.key);t?Object.assign(t,e):i.set(e.key,e)}),state.pan.results=Array.from(i.values()),ensureActivePanType(),scheduleUiSnapshotSave(),state.pan.results}function schedulePanPolling(e,t){(window.WEBHOME_CONFIG.pan.pollIntervals||[]).forEach((n,a)=>{const i=setTimeout(()=>pollPanResources(e,t,a+1),n);state.pan.pollTimers.push(i)})}async function pollPanResources(e,t,n){if(state.pan.viewToken===e&&state.selected===t&&state.pan.keyword)try{state.pan.pollRound=n,setPanStatus(`更新中 ${n}`);const a=state.pan.config||defaultPanConfig(),i=await ensurePanAuthHeaders(),s=await postJson(panApi("/api/search"),panSearchPayload(state.pan.keyword,a),28,i);if(state.pan.viewToken!==e||state.selected!==t)return;const o=state.pan.results.length,r=applyPanSearchBody(s,state.pan.keyword),c=r.length-o;setPanStatus(c>0?`新增 ${c} 条,共 ${r.length}`:`已更新 ${r.length} 条`),renderPanResults(),scheduleUiSnapshotSave()}catch(t){String(t.message||"").includes("401")&&state.pan.config&&(state.pan.config.token="",state.pan.config.tokenExpiresAt=0,await persistPanConfigQuietly()),state.pan.viewToken===e&&setPanStatus("更新失败")}}function normalizePanResults(e,t){const n=state.pan.config||defaultPanConfig(),a=new Set((n.diskTypes||[]).map(normalizePanDiskType)),i=new Set,s=[];return Object.entries(e||{}).forEach(([e,n])=>{const o=normalizePanDiskType(e);a.has(o)&&Array.isArray(n)&&n.forEach((e,n)=>{const a=String(e&&(e.url||e.link||e.href)||"").trim();if(!a)return;const r=`${o}|${normalizePanUrl(a)}`;i.has(r)||(i.add(r),s.push({key:r,diskType:o,url:a,password:String(e.password||e.pwd||e.passcode||e.code||"").trim(),title:String(e.note||e.name||e.title||e.work_title||t||"盘搜资源").trim(),source:String(e.source||e.channel||e.plugin||"").trim(),datetime:String(e.datetime||e.time||e.created_at||"").trim(),normalizedUrl:String(e.normalized_url||e.normalizedUrl||"").trim(),index:s.length+n/1e3}))})}),s}function normalizePanUrl(e){try{const t=new URL(e);return t.hash="",t.hostname=t.hostname.toLowerCase(),t.toString()}catch(t){return String(e||"").trim()}}function panHealthKey(e){return e?`${e.diskType}|${normalizePanUrl(e.url)}`:""}function getPanHealth(e){const t=panHealthKey(e);return state.pan.pending[t]?{state:"pending",summary:"检测中"}:state.pan.health[t]||{state:"idle",summary:"未检测"}}function panHealthPriority(e){const t=getPanHealth(e),n=t&&t.state||"idle";return null==PAN_HEALTH_PRIORITY[n]?PAN_HEALTH_PRIORITY.idle:PAN_HEALTH_PRIORITY[n]}function panAvailableTypes(){const e=new Map;state.pan.results.forEach(t=>{const n=normalizePanDiskType(t.diskType);n&&e.set(n,(e.get(n)||0)+1)});const t=new Set(PAN_DISK_TYPES.map(e=>e.id)),n=PAN_DISK_TYPES.filter(t=>e.has(t.id)).map(t=>({id:t.id,name:t.name,count:e.get(t.id)||0})),a=Array.from(e.entries()).filter(([e])=>!t.has(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>({id:e,name:panDiskName(e),count:t}));return n.concat(a)}function ensureActivePanType(){const e=panAvailableTypes();return e.length?(state.pan.activeType&&e.some(e=>e.id===state.pan.activeType)||(state.pan.activeType=e[0].id),state.pan.activeType):(state.pan.activeType="","")}function rankedPanResults(e){const t=e||"",n=state.pan.results.filter(e=>!t||normalizePanDiskType(e.diskType)===t);return canCheckPanLinks()&&t&&PAN_CHECKABLE_DISK_TYPES.has(normalizePanDiskType(t))?n.map((e,t)=>({item:e,index:t,priority:panHealthPriority(e)})).sort((e,t)=>e.priority-t.priority||Number(e.item.index||e.index)-Number(t.item.index||t.index)||e.index-t.index).map(({item:e})=>e):n}function renderPanTabs(){const e=$("panTabs");if(!e)return;const t=panAvailableTypes(),n=ensureActivePanType(),a=document.activeElement,i=a&&e.contains(a)&&getPanTypeFromElement(a)||"",s=t.map(e=>`${e.id}:${e.count}`).join("\n");if(!t.length)return state.pan.tabKeys="",void e.replaceChildren();if(s===state.pan.tabKeys&&e.children.length===t.length)return Array.from(e.children).forEach(e=>{const a=getPanTypeFromElement(e),i=a===n;e.classList.toggle("active",i);const s=t.find(e=>e.id===a);s&&(e.textContent=`${s.name} ${s.count}`)}),void("tabs"===state.pan.focusMode&&lockPanFocus(findByDataset(e,"panType",n)||e.querySelector(".chip.active")||e.querySelector(".chip"),"tabs"));state.pan.tabKeys=s,e.replaceChildren(...t.map(e=>{const t=document.createElement("button");return t.className="chip focusable"+(e.id===n?" active":""),t.type="button",t.dataset.panType=e.id,t.setAttribute("data-pan-type",e.id),t.textContent=`${e.name} ${e.count}`,t.addEventListener("focus",()=>{state.pan.focusMode="tabs"}),t}));const o=i?findByDataset(e,"panType",i):"tabs"===state.pan.focusMode?e.querySelector(".chip.active")||e.querySelector(".chip"):null;o&&lockPanFocus(o,"tabs")}function getPanTypeFromElement(e){return e?String(e.getAttribute("data-pan-type")||e.dataset&&e.dataset.panType||""):""}function handlePanTabEvent(e){const t=$("panTabs");if(!t)return!1;const n=e&&e.target&&closestPanTab(e.target);if(!n||!t.contains(n))return!1;const a=getPanTypeFromElement(n);return!!a&&(e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation&&e.stopImmediatePropagation(),selectPanType(a),!0)}function closestPanTab(e){for(;e&&e!==document&&e!==$("panTabs");){if(e.getAttribute&&e.getAttribute("data-pan-type"))return e;e=e.parentNode}return null}function selectPanType(e){if(!e)return;const t=Date.now();if(state.pan.lastTypeSelect&&state.pan.lastTypeSelect.type===e&&t-state.pan.lastTypeSelect.at<520)return;if(state.pan.lastTypeSelect={type:e,at:t},state.pan.activeType===e)return state.pan.focusMode="results",void focusFirstPanResult();const n=$("detailSheet")?$("detailSheet").scrollTop:0;state.pan.keepBlockPositionUntil=t+600,state.pan.activeType=e,state.pan.renderKeys="",state.pan.focusMode="tabs";const a=$("panResultList");a&&(a.scrollTop=0),updatePanTabActive(e),renderPanResults(),$("detailSheet")&&($("detailSheet").scrollTop=n),requestAnimationFrame(()=>{$("detailSheet")&&($("detailSheet").scrollTop=n)}),lockPanFocus(findByDataset($("panTabs"),"panType",e)||$("panTabs").querySelector(".chip.active"),"tabs",{keepBlockPosition:!0}),scheduleUiSnapshotSave()}function updatePanTabActive(e){const t=$("panTabs");t&&Array.from(t.querySelectorAll("[data-pan-type]")).forEach(t=>{t.classList.toggle("active",getPanTypeFromElement(t)===e)})}function focusFirstPanTab(){const e=$("panTabs")&&($("panTabs").querySelector(".chip.active")||$("panTabs").querySelector(".chip"));e&&(centerPanSearchBlock(),lockPanFocus(e,"tabs"))}function isPanSearchActive(){const e=$("panSearchBlock");return!(!e||!e.classList.contains("active")||"none"===e.style.display)}function updatePostPanFocusState(){const e=isPanSearchActive();["seasonBlock","castBlock","personWorkBlock","recommendBlock"].forEach(t=>{const n=$(t);n&&(n.setAttribute("aria-hidden",e?"true":"false"),n.querySelectorAll(".focusable,button,input,textarea").forEach(t=>{if(e)t.dataset.panFocusLocked||(t.dataset.panFocusLocked="1",t.dataset.panPrevTabindex=t.hasAttribute("tabindex")?t.getAttribute("tabindex")||"":"__none__"),t.setAttribute("tabindex","-1");else if(t.dataset.panFocusLocked){const e=t.dataset.panPrevTabindex;e&&"__none__"!==e?t.setAttribute("tabindex",e):t.removeAttribute("tabindex"),delete t.dataset.panFocusLocked,delete t.dataset.panPrevTabindex}}))})}function renderPanResults(){const e=$("panResultList");if(!e)return;renderPanTabs();const t=ensureActivePanType(),n=rankedPanResults(t),a=state.pan.results.length,i=t?panDiskName(t):"";if($("panSearchHint").textContent=state.pan.keyword?`${state.pan.keyword} · 共 ${a} 条${i?" · "+i+" "+n.length:""}`:"",!a)return state.pan.renderKeys="",void e.replaceChildren(emptyNode("暂无盘搜资源,后台仍会继续更新"));if(!n.length)return state.pan.renderKeys="",void e.replaceChildren(emptyNode("当前网盘暂无资源"));const s=`${t}\n`+n.map(e=>`${e.key}:${getPanHealth(e).state}:${e.normalizedUrl||""}`).join("\n"),o=document.activeElement,r=!(!o||!e.contains(o))||"results"===state.pan.focusMode,c=r&&o.dataset.panKey||state.pan.focusKey||"";e.setAttribute("tabindex","-1"),e.setAttribute("role","listbox"),patchPanResultList(e,n,t,r,c)||(s!==state.pan.renderKeys||e.children.length!==n.length?(state.pan.renderKeys=s,e.replaceChildren(...n.map(panResultNode)),observePanVisibleItems(),restorePanResultFocus(e,c,r)):restorePanResultFocus(e,c,r))}function patchPanResultList(e,t,n,a,i){const s=Array.from(e.querySelectorAll(".pan-result-item"));if(!s.length||s.some(e=>!t.some(t=>t.key===e.dataset.panKey)))return!1;const o=new Map(s.map(e=>[e.dataset.panKey,e])),r=t.map(e=>{const t=o.get(e.key);return t?(updatePanResultNode(t,e),t):panResultNode(e)});let c=e.firstChild;return r.forEach(t=>{t!==c?e.insertBefore(t,c):c=c.nextSibling}),state.pan.renderKeys=`${n}\n`+t.map(e=>`${e.key}:${getPanHealth(e).state}:${e.normalizedUrl||""}`).join("\n"),observePanVisibleItems(),restorePanResultFocus(e,i,a),!0}function updatePanResultNode(e,t){const n=getPanHealth(t);e.className="pan-result-item focusable"+("bad"===n.state?" is-bad":""),e.dataset.panKey=t.key,e.innerHTML=panResultHtml(t,n)}function restorePanResultFocus(e,t,n){if(!n||!e)return;const a=t?findByDataset(e,"panKey",t):null,i=e.querySelector(".pan-result-item");lockPanFocus(a||i,"results",{keepBlockPosition:!0,once:!0})}function lockPanFocus(e,t,n){if(!e)return;const a=n||{},i=()=>{if(!$("panSearchBlock")||"none"===$("panSearchBlock").style.display)return;if(t&&state.pan.focusMode&&state.pan.focusMode!==t)return;const n=document.activeElement,i=n&&($("panTabs").contains(n)||$("panResultList").contains(n));i&&t&&state.pan.focusMode!==t||i&&n===e||isVisibleFocusable(e)&&(state.pan.focusMode=t||state.pan.focusMode,focusPanTarget(e,a))};requestAnimationFrame(i),a.once||(setTimeout(i,80),setTimeout(i,220))}function focusPanTarget(e,t){if(!e)return;const n=t||{},a=$("panResultList"),i=$("panTabs"),s=n.keepBlockPosition||Date.now()<Number(state.pan.keepBlockPositionUntil||0);i&&i.contains(e)&&!s&¢erPanSearchBlock();try{e.focus({preventScroll:!0})}catch(t){e.focus()}if(a&&a.contains(e))return keepPanResultItemVisible(e,a),void(n.keepBlockPosition||ensurePanListViewport());if(i&&i.contains(e))return;const o=e.getBoundingClientRect(),r=window.innerHeight||document.documentElement.clientHeight||0;if(r&&(o.top<48||o.bottom>r-48))try{e.scrollIntoView({block:"nearest",inline:"nearest"})}catch(t){e.scrollIntoView(!1)}}function centerPanSearchBlock(){const e=$("panSearchBlock"),t=$("detailSheet");if(e&&t&&t.classList.contains("active"))try{e.scrollIntoView({block:"center",inline:"nearest"})}catch(n){const a=e.getBoundingClientRect(),i=t.getBoundingClientRect(),s=t.clientHeight||window.innerHeight||0;if(!s)return;t.scrollTop+=a.top-i.top-Math.round((s-Math.min(a.height,.72*s))/2)}}function ensurePanListViewport(){const e=$("panResultList"),t=$("detailSheet");if(!e||!t||!t.classList.contains("active"))return;const n=e.getBoundingClientRect(),a=t.getBoundingClientRect(),i=t.clientHeight||window.innerHeight||0;if(!i)return;const s=a.top+Math.max(34,.1*i),o=a.top+i-Math.max(50,.1*i);n.top<s?t.scrollTop+=n.top-s:n.bottom>o&&n.top>s&&(t.scrollTop+=Math.min(n.top-s,n.bottom-o))}function keepPanResultItemVisible(e,t){const n=e.getBoundingClientRect(),a=t.getBoundingClientRect(),i=n.top-a.top,s=n.bottom-a.bottom;i<0?t.scrollTop+=i:s>0&&(t.scrollTop+=s)}function findByDataset(e,t,n){return e&&Array.from(e.querySelectorAll("[data-"+t.replace(/[A-Z]/g,e=>"-"+e.toLowerCase())+"]")).find(e=>String(e.dataset[t]||"")===String(n||""))||null}function panResultNode(e){const t=getPanHealth(e),n=document.createElement("button");return n.className="pan-result-item focusable"+("bad"===t.state?" is-bad":""),n.type="button",n.dataset.panKey=e.key,n.innerHTML=panResultHtml(e,t),n.addEventListener("focus",()=>{state.pan.focusKey=e.key,state.pan.focusMode="results"}),n.addEventListener("click",()=>playPanResult(e)),n}function panResultHtml(e,t){return`\n <div class="pan-result-title">\n <span>${escapeHtml(e.title||state.pan.keyword||"盘搜资源")}</span>\n ${panHealthIndicatorHtml(e,t)}\n </div>\n <div class="pan-result-meta">${escapeHtml(panDiskName(e.diskType))}${e.password?" · 提取码 "+escapeHtml(e.password):""}${e.source?" · "+escapeHtml(e.source):""}</div>\n <div class="pan-result-url">${escapeHtml(e.normalizedUrl||e.url)}</div>\n `}async function rememberPanPlaybackReturn(e){const t=$("detailSheet"),n=$("panResultList"),a=e&&e.key||state.pan.focusKey||"";refreshHomeReturnTimestamp(),state.pan.playbackReturn={key:a,activeType:state.pan.activeType||"",detailScrollTop:t?Math.round(t.scrollTop||0):0,listScrollTop:n?Math.round(n.scrollTop||0):0,at:Date.now()},state.pan.focusKey=a,state.pan.focusMode="results",await saveUiSnapshotNow()}function restorePanPlaybackReturn(e){const t=e||{},n=state.pan.playbackReturn;if(!n)return!1;if(Date.now()-Number(n.at||0)>432e5)return state.pan.playbackReturn=null,!1;const a=$("detailSheet"),i=$("panSearchBlock");if(!(a&&a.classList.contains("active")&&i&&i.classList.contains("active")))return!1;n.activeType&&(state.pan.activeType=n.activeType),state.pan.focusKey=n.key||state.pan.focusKey||"",state.pan.focusMode="results",t.skipRender||renderPanResults();const s=()=>{const e=$("detailSheet"),t=$("panResultList");e&&(e.scrollTop=Number(n.detailScrollTop||0)),t&&(t.scrollTop=Number(n.listScrollTop||0));const a=n.key?findByDataset(t,"panKey",n.key):null,i=t&&t.querySelector(".pan-result-item");(a||i)&&lockPanFocus(a||i,"results")};return requestAnimationFrame(s),setTimeout(s,80),setTimeout(s,240),state.pan.playbackReturn=null,scheduleUiSnapshotSave(),!0}function panHealthLabel(e){return{ok:"链接有效",bad:"链接失效",locked:"需要提取码",unsupported:"暂不支持检测",uncertain:"检测结果不确定",pending:"检测中",idle:"未检测"}[e]||"未检测"}function panHealthIndicatorHtml(e,t){if(!canCheckPanLinks()||!isPanCheckSupported(e))return"";const n=t&&t.state||"idle",a=t&&t.summary?`${panHealthLabel(n)}:${t.summary}`:panHealthLabel(n);return`<span class="pan-health ${escapeAttr(n)}" title="${escapeAttr(a)}" aria-label="${escapeAttr(a)}"></span>`}function observePanVisibleItems(){const e=$("panResultList");state.pan.observer&&state.pan.observer.disconnect(),canCheckPanLinks()&&(e&&rankedPanResults(state.pan.activeType).some(isPanCheckSupported)&&"IntersectionObserver"in window?(state.pan.observer=new IntersectionObserver(e=>{e.forEach(e=>{if(!e.isIntersecting||e.intersectionRatio<.25)return;const t=e.target.dataset.panKey;queuePanCheck(state.pan.results.find(e=>e.key===t))})},{root:e,threshold:[.25,.6]}),e.querySelectorAll(".pan-result-item").forEach(e=>state.pan.observer.observe(e)),scheduleVisiblePanCheck()):queueAllVisiblePanFallback())}function scheduleVisiblePanCheck(){clearTimeout(scheduleVisiblePanCheck.timer),scheduleVisiblePanCheck.timer=setTimeout(queueVisiblePanChecks,90)}function queueVisiblePanChecks(){if(!canCheckPanLinks())return;const e=$("panResultList");if(!e)return;const t=e.getBoundingClientRect(),n=t.bottom+Math.max(80,.35*t.height);Array.from(e.querySelectorAll(".pan-result-item")).some(e=>{const a=e.getBoundingClientRect();if(a.bottom<t.top||a.top>n)return!1;return queuePanCheck(state.pan.results.find(t=>t.key===e.dataset.panKey)),state.pan.queued.size+state.pan.inFlight.size>=10})}function queueAllVisiblePanFallback(){canCheckPanLinks()&&queueVisiblePanChecks()}function queuePanCheck(e){if(!e||!canCheckPanLinks()||!isPanCheckSupported(e))return;const t=panHealthKey(e);!t||state.pan.health[t]||state.pan.pending[t]||state.pan.queued.has(t)||state.pan.inFlight.has(t)||(state.pan.queued.set(t,e),schedulePanCheckFlush())}function schedulePanCheckFlush(){state.pan.flushTimer||(state.pan.flushTimer=setTimeout(()=>{state.pan.flushTimer=0,flushPanCheckQueue()},180))}async function flushPanCheckQueue(){if(!canCheckPanLinks())return void state.pan.queued.clear();if(!state.pan.queued.size)return;const e=Array.from(state.pan.queued.entries()).slice(0,10);e.forEach(([e])=>state.pan.queued.delete(e)),e.forEach(([e])=>{state.pan.pending[e]=!0,state.pan.inFlight.add(e)}),renderPanResults();try{const t=await sdk().pan.check(e.map(([,e])=>({type:e.diskType,url:e.url,password:e.password}))),n=t&&Array.isArray(t.results)?t.results:[];e.forEach(([e,t],a)=>{const i=n[a]||{},s=String(i.normalized_url||i.normalizedUrl||"").trim();s&&(t.normalizedUrl=s);const o={state:i.state||"uncertain",summary:i.summary||"",checkedAt:i.checked_at||Date.now(),expiresAt:i.expires_at||Date.now()+3e5};state.pan.health[e]=o;const r=panHealthKey({diskType:normalizePanDiskType(i.type||t.diskType),url:i.url||t.url});r&&r!==e&&(state.pan.health[r]=o)}),setPanStatus(`已检测 ${checkedPanCount()}/${checkablePanCount()}`)}catch(t){e.forEach(([,e])=>{state.pan.health[panHealthKey(e)]={state:"uncertain",summary:t.message||"检测失败",checkedAt:Date.now(),expiresAt:Date.now()+3e5}}),setPanStatus("检测不可用")}finally{e.forEach(([e])=>{delete state.pan.pending[e],state.pan.inFlight.delete(e)}),renderPanResults(),scheduleVisiblePanCheck(),state.pan.queued.size&&schedulePanCheckFlush()}}function checkedPanCount(){return state.pan.results.filter(e=>isPanCheckSupported(e)&&!!state.pan.health[panHealthKey(e)]).length}function checkablePanCount(){return state.pan.results.filter(isPanCheckSupported).length}function panPasswordParam(e,t){const n=normalizePanDiskType(e&&e.diskType),a=String(t||"").toLowerCase();return"115"===n||/(^|\/\/)([^/]*\.)?(115|115cdn|anxia)\./i.test(a)?"password":"pwd"}function hasPanPassword(e){return/(?:[?&#])(pwd|password|passcode|code)=/i.test(String(e||""))}function addPanPassword(e,t,n){let a=String(e||"").trim();const i=String(t||"").trim();if(!a||!i||hasPanPassword(a))return a;if(/^(magnet:|ed2k:\/\/)/i.test(a))return a;const s=panPasswordParam(n,a);try{const e=new URL(a);return e.searchParams.set(s,i),e.toString()}catch(e){const t=a.indexOf("#"),n=t>=0?a.slice(0,t):a,o=t>=0?a.slice(t):"",r=n.includes("?")?n.endsWith("?")||n.endsWith("&")?"":"&":"?";return n+r+s+"="+encodeURIComponent(i)+o}}function buildPanPlayPayload(e){let t=String(e&&(e.normalizedUrl||e.normalized_url||e.url)||"").trim();if(!t)return null;/^push:\/\//i.test(t)&&(t=t.replace(/^push:\/\//i,""));const n=Object.assign({},e||{},state.selected||{}),a=n.title||state.pan.keyword||e&&e.title||e&&e.url||t;return{type:normalizePanDiskType(e&&e.diskType),url:t,password:e&&e.password||"",title:a,pic:playbackPosterPic(n),wallPic:playbackWallPic(n)}}async function playPanResult(e){const t=buildPanPlayPayload(e);if(t){await rememberPanPlaybackReturn(e),state.selected&&(rememberWatchIntent(state.selected,"search"),startWatchTracking(state.selected));try{const e=sdk().pan||{};if(!e.play)throw new Error("当前 App 不支持 pan.play");try{await savePushArtwork(t)}catch(e){}await e.play(t),toast("已交给原生播放")}catch(e){toast("播放失败:"+(e.message||"unknown"))}}}function emptyNode(e){const t=document.createElement("div");return t.className="empty",t.textContent=e,t}function closeDetail(e){const t=$("detailSheet");clearInlineEpisodePreview({restoreDetail:!1}),document.body.classList.remove("detail-active"),document.body.classList.remove("episode-active"),$("mobileDetailBackBtn").classList.remove("is-hidden"),t.classList.remove("active"),t.classList.remove("detail-large"),t.style.display="",t.setAttribute("aria-hidden","true"),state.detailReturn=null,stopDetailCoverCarousel(!0),resetPanSearch(),setNativeToolbarVisible(!0),restoreHomeReturn(),scheduleUiSnapshotSave(),e||"#detail"!==location.hash||history.back()}function openSync(e){const t=e||{};ensureSheetViewport($("syncSheet")),$("syncSheet").classList.add("active"),$("syncSheet").setAttribute("aria-hidden","false"),$("nsecInput").value=state.identity?state.identity.nsec:"",t.skipHistory||"#sync"===location.hash||history.pushState({sheet:"sync"},"","#sync"),scheduleUiSnapshotSave(),t.restore||setTimeout(()=>focusRemoteTarget($("saveNsecBtn")),40)}function closeSync(e){const t=$("syncSheet");t.classList.remove("active"),t.style.display="",t.setAttribute("aria-hidden","true"),scheduleUiSnapshotSave(),e||"#sync"!==location.hash||history.back()}function openImage(e,t){const n=t||{},a=n.episode||null;if(!e&&!a)return;n.restore||rememberFocusReturn();const i=$("viewerImage"),s=$("episodeViewer");a?(document.body.classList.add("episode-active"),$("imageViewer").classList.add("episode-mode"),i.style.display="none",i.removeAttribute("src"),renderEpisodeViewerContent(Object.assign({},a,{still:a.still||e||""}))):(document.body.classList.remove("episode-active"),$("imageViewer").classList.remove("episode-mode"),s.style.display="none",s.classList.remove("no-still"),s.replaceChildren(),i.style.display="",i.src=e),ensureSheetViewport($("imageViewer"),"grid"),$("imageViewer").classList.add("active"),$("imageViewer").setAttribute("aria-hidden","false"),a&&$("mobileImageBackBtn").classList.remove("is-hidden"),n.skipHistory||history.pushState({sheet:"image"},"","#image"),scheduleUiSnapshotSave(),n.restore||setTimeout(()=>focusRemoteTarget($(a?"imageContent":"closeImageBtn")),40)}function closeImage(e){const t=$("imageViewer");document.body.classList.remove("episode-active"),t.classList.remove("active"),t.classList.remove("episode-mode"),t.style.display="",t.setAttribute("aria-hidden","true"),$("viewerImage").removeAttribute("src"),$("viewerImage").style.display="",$("episodeViewer").style.display="none",$("episodeViewer").classList.remove("no-still"),$("episodeViewer").replaceChildren(),state.episodeViewer.swipe=null,$("mobileImageBackBtn").classList.remove("is-hidden"),e||"#image"!==location.hash||history.back(),scheduleUiSnapshotSave(),restoreFocusReturn($("detailSheet")&&$("detailSheet").classList.contains("active")?detailPrimaryActionButton():null)}async function nativeSearch(e){if(!e)return;rememberDetailReturn($("detailSearchBtn"));const t=state.selected||{},n=playbackWallPic(t);await sdk().search(e,{direct:!0,pic:t.pic||"",wallPic:n}),toast("已发起原生搜索")}async function nativeHomeSearch(e){await sdk().search(String(e||"").trim(),{direct:!1}),toast("已打开原生搜索")}async function openLiveHome(){try{const e=sdk();window.fm&&e.openLive?(await e.openLive(),toast("已打开直播")):e.openLive?await e.openLive():window.fongmi&&window.fongmi.app&&window.fongmi.app.openLive?(await window.fongmi.app.openLive(),toast("已打开直播")):toast("当前环境不支持打开直播")}catch(e){toast("打开直播失败:"+(e.message||"unknown"))}}async function openSettingHome(){try{const e=sdk();window.fm&&e.openSetting?(await e.openSetting(),toast("已打开设置")):e.openSetting?await e.openSetting():window.fongmi&&window.fongmi.app&&window.fongmi.app.openSetting?(await window.fongmi.app.openSetting(),toast("已打开设置")):toast("当前环境不支持打开设置")}catch(e){toast("打开设置失败:"+(e.message||"unknown"))}}function rememberDetailReturn(e){const t=$("detailSheet");t&&t.classList.contains("active")&&(refreshHomeReturnTimestamp(),state.detailReturn={scrollTop:Math.round(t.scrollTop||0),targetId:e&&e.id||document.activeElement&&document.activeElement.id||"detailSearchBtn",at:Date.now()},saveUiSnapshotNow())}function restoreDetailReturn(){const e=state.detailReturn;if(!e)return!1;if(Date.now()-Number(e.at||0)>432e5)return state.detailReturn=null,!1;const t=$("detailSheet");if(!t||!t.classList.contains("active"))return!1;const n=()=>{$("detailSheet")&&($("detailSheet").scrollTop=Number(e.scrollTop||0));const t=e.targetId&&$(e.targetId),n=isVisibleFocusable(t)?t:detailPrimaryActionButton();n&&focusRemoteTarget(n)};return requestAnimationFrame(n),setTimeout(n,80),setTimeout(n,220),state.detailReturn=null,scheduleUiSnapshotSave(),!0}function rememberWatchIntent(e,t){e&&(state.watch={item:normalizeSnapshot(e),timer:state.watch.timer,bestMs:state.watch.bestMs||0,durationMs:state.watch.durationMs||0,lastAt:Date.now(),published:!1,intentAction:t||"view"},savePendingWatch())}function startWatchTracking(e){e&&window.fm&&(state.watch={item:normalizeSnapshot(e),timer:state.watch.timer,bestMs:0,durationMs:0,lastAt:Date.now(),published:!1,intentAction:state.watch.intentAction||""},savePendingWatch(),state.watch.timer||(state.watch.timer=setInterval(sampleWatchStatus,12e3)),sampleWatchStatus())}async function savePendingWatch(){const e=state.watch;if(e&&e.item)try{await sdk().cache.set(cacheKey("pendingWatch"),JSON.stringify({item:e.item,intentAction:e.intentAction,startedAt:e.lastAt||Date.now(),published:!!e.published}))}catch(e){}}async function loadPendingWatch(){if(state.watch&&state.watch.item)return state.watch;try{const e=await sdk().cache.get(cacheKey("pendingWatch")),t=e?JSON.parse(e):null;return t&&t.item?(state.watch={item:normalizeSnapshot(t.item),timer:state.watch.timer,bestMs:0,durationMs:0,lastAt:t.startedAt||Date.now(),published:!!t.published,intentAction:t.intentAction||"search"},state.watch):null}catch(e){return null}}async function clearPendingWatch(){try{await sdk().cache.del(cacheKey("pendingWatch"))}catch(e){}}async function sampleWatchStatus(){const e=state.watch;if(e&&e.item&&window.fm)try{const t=await fm.stat(),n=Math.max(0,Number(t&&t.position||0)),a=Math.max(0,Number(t&&t.duration||0));a>0&&(e.durationMs=a),n>e.bestMs&&(e.bestMs=n);const i=e.durationMs>0?e.bestMs/e.durationMs:0;if(e.bestMs>=6e5&&hasHeatIntent(e)&&!e.published){if(await hasPublishedHeat(e.item))return e.published=!0,await savePendingWatch(),void await clearPendingWatch();e.published=!0,savePendingWatch(),await recordPreference(e.item,"watch",{watchMs:Math.round(e.bestMs),durationMs:Math.round(e.durationMs),completion:Number(Math.min(1,i).toFixed(3)),intentAction:e.intentAction,playState:t&&t.state,playTitle:t&&t.title||""}),await clearPendingWatch()}i>=.92&&e.bestMs>0&&stopWatchTracking(!1)}catch(e){}}async function settleWatchFromHistory(){const e=await loadPendingWatch();if(e&&e.item&&!e.published){if(await hasPublishedHeat(e.item))return e.published=!0,await savePendingWatch(),void await clearPendingWatch();try{const t=await sdk().history(),n=findWatchHistory(e.item,Array.isArray(t)?t:[]);if(!n)return;const a=Math.max(0,Number(n.position||0)),i=Math.max(0,Number(n.duration||0));if(a<6e5||!hasHeatIntent(e))return;if(await hasPublishedHeat(e.item))return void await clearPendingWatch();e.bestMs=a,e.durationMs=i,e.published=!0,await savePendingWatch(),await recordPreference(e.item,"watch",{watchMs:Math.round(a),durationMs:Math.round(i),completion:i>0?Number(Math.min(1,a/i).toFixed(3)):0,intentAction:e.intentAction,historyKey:n.key||"",siteKey:n.siteKey||"",vodId:n.vodId||"",playTitle:n.vodName||""}),await clearPendingWatch(),toast("已同步观看偏好")}catch(e){}}}function scheduleHistorySettlement(){settleWatchFromHistory(),setTimeout(settleWatchFromHistory,1200),setTimeout(settleWatchFromHistory,4e3)}function findWatchHistory(e,t){const n=normalizeTitle(e.title||""),a=e.tmdbId?String(e.tmdbId):"";return t.filter(e=>e&&Number(e.position||0)>0).filter(e=>!state.watch.lastAt||Number(e.createTime||0)>=state.watch.lastAt-3e4).sort((e,t)=>Number(t.createTime||0)-Number(e.createTime||0)).find(e=>{const t=normalizeTitle(e.vodName||"");return!(!n||!t||n!==t&&!n.includes(t)&&!t.includes(n))||!(!a||!String(e.vodId||"").includes(a))})}async function hasPublishedHeat(e){if(!(state.identity&&state.identity.pubkey)||!e)return!1;const t=mediaHeatKey(e);if(!t)return!1;return hotVectorHasMedia(await hotGetMyVector(),t)}function stopWatchTracking(e){const t=state.watch;if(e&&t&&t.item&&t.bestMs>=6e5&&hasHeatIntent(t)&&!t.published){const e=t.durationMs>0?t.bestMs/t.durationMs:0;trackPreference(t.item,"watch",{watchMs:Math.round(t.bestMs),durationMs:Math.round(t.durationMs),completion:Number(Math.min(1,e).toFixed(3)),intentAction:t.intentAction})}t&&t.timer&&clearInterval(t.timer),state.watch={item:null,timer:0,bestMs:0,durationMs:0,lastAt:0,published:!1,intentAction:""}}function trackPreference(e,t,n){recordPreference(e,t,n).catch(()=>{})}async function recordPreference(e,t,n){if("watch"!==t)return;if(await isPreferencePublishBlocked())return void setStatus("publish","删除保护中,暂停发布");if("watch"===t&&await hasPublishedHeat(e))return;const a=await createPreferenceEvent(e,t,n||{});a&&(a.local=!0,await hotIngestEvent(a),scheduleRender(),publishEvent(a))}async function createPreferenceEvent(e,t,n){const a=await ensureIdentity();if(!a)return null;if("watch"===t&&Math.max(0,Number(n.watchMs||n.position||0))<6e5)return null;const i=hotVectorItemFromSnapshot(normalizeSnapshot(e),hotToday());if(!i)return null;const s=await hotGetMyVector(),o=Math.max(hotNow(),Number(s&&s.ts||0)+1),r=hotExpiresAt(o),c={v:5,i:hotWireItemsForPublish(s,i,o)},l=[["d",HOT_VECTOR_D],["t",window.WEBHOME_CONFIG.nostr.tag],["app","fongmi-webhome"],["expiration",String(r)]],d={kind:window.WEBHOME_CONFIG.nostr.kind,created_at:o,tags:l,content:JSON.stringify(c)};return a&&a.secret&&window.NostrTools?window.NostrTools.finalizeEvent(d,a.secret):window.nostr&&window.nostr.signEvent?await window.nostr.signEvent(d):Object.assign({id:HOT_VECTOR_D,pubkey:""},d)}function hotVectorItemFromSnapshot(e,t){return!e||"movie"!==e.mediaType&&"tv"!==e.mediaType||!e.tmdbId?null:hotNormalizeWireItem([hotMediaTypeCode(e.mediaType),Number(e.tmdbId)||String(e.tmdbId),t,e.title||"",e.pic||e.image||""],t,!1)}function hotWireItemsForPublish(e,t,n){const a=new Map;return(e&&e.i||[]).forEach(e=>{const t=hotWireItemFromStored(e);t&&a.set(hotVectorItemMediaKey(t),t)}),a.set(hotVectorItemMediaKey(t),t),normalizeWireVectorItems(Array.from(a.values()),n)}function hotWireItemFromStored(e){const t=hotVectorItemMediaKey(e),n=t?state.hot.media.get(t):null;return n&&n.t&&n.p?hotNormalizeWireItem([hotMediaTypeCode(n.mt),Number(n.tid)||n.tid,hotVectorItemDay(e),n.t,n.p],hotToday(),!1):null}async function ensureIdentity(){if(state.identity)return state.identity;if(await waitForNostrTools(),!window.NostrTools)return null;let e=await sdk().cache.get(cacheKey("nsec"));return e||(e=window.NostrTools.nip19.nsecEncode(window.NostrTools.generateSecretKey()),await sdk().cache.set(cacheKey("nsec"),e)),setIdentity(e)}async function setIdentity(e){if(await waitForNostrTools(),!window.NostrTools)throw new Error("nostr-tools 加载失败");const t=window.NostrTools.nip19.decode(e.trim());if("nsec"!==t.type)throw new Error("请输入 nsec 私钥");const n=t.data,a=window.NostrTools.getPublicKey(n),i=window.NostrTools.nip19.npubEncode(a);return state.identity={nsec:e.trim(),secret:n,pubkey:a,npub:i},await sdk().cache.set(cacheKey("nsec"),state.identity.nsec),await hotLoadMyVector().catch(()=>null),setStatus("identity",shortKey(i)),renderMetrics(),state.identity}function waitForNostrTools(){return window.NostrTools?Promise.resolve():new Promise(e=>{let t=0;const n=setInterval(()=>{(window.NostrTools||t++>40)&&(clearInterval(n),window.NostrTools||setStatus("identity","nostr-tools 加载失败"),e())},100)})}function subscribeNostr(){const e=window.WEBHOME_CONFIG.nostr.relays,t=resetRelaySubscribeState();state.relay.subscribeStarted=!0,setStatus("nostr","连接中"),e.forEach((e,n)=>{try{setRelayStatus(e,"连接中");const a=new WebSocket(e),i="fongmi_pref_"+n+"_"+Date.now();let s=!1,o=0,r=[],c=0;const l=()=>t===state.relay.subscribeToken,d=()=>{if(clearTimeout(c),c=0,!l())return r=[],void maybeFinishNostrRefresh(t);const e=r;r=[],e.length?hotIngestEvents(e).then(e=>{e&&l()&&(scheduleHotRefresh(260),isNostrRefreshActive(t)&&updateNostrRefreshProgress({phase:"写入索引",indexed:state.hot.items.length})),maybeFinishNostrRefresh(t)}):maybeFinishNostrRefresh(t)},u=()=>{l()&&!s&&(s=!0,state.relay.backfillCandidates[e]=Math.max(Number(state.relay.backfillCandidates[e]||0),o),choosePrimaryBackfillRelay(!1),syncRelayBackfill(e,t).catch(()=>{}))},m=setTimeout(()=>{if(l()){"已连接"===state.relay.statuses[e]&&u(),finishRelaySubscribe(e,"已连接"===state.relay.statuses[e]?"":"失败"),maybeFinishNostrRefresh(t);try{a.close()}catch(e){}}},8e3);a.onopen=()=>{if(l())state.relay.connected+=1,isNostrRefreshActive(t)&&updateNostrRefreshProgress({phase:"订阅近7天",connected:state.relay.connected,relay:shortRelay(e)}),setRelayStatus(e,"已连接"),setStatus("nostr","已连接"),renderMetrics(),a.send(JSON.stringify(["REQ",i,{kinds:[window.WEBHOME_CONFIG.nostr.kind],"#t":[window.WEBHOME_CONFIG.nostr.tag],"#d":[HOT_VECTOR_D],since:hotBackupWindowStart(),limit:500}]));else try{a.close()}catch(e){}},a.onmessage=async n=>{if(!l())return;const s=safeJson(n.data,[]);if("EOSE"!==s[0])"EVENT"===s[0]&&s[2]&&(o+=1,isNostrRefreshActive(t)&&updateNostrRefreshProgress({phase:"接收订阅",subEvents:Number(state.relay.refresh&&state.relay.refresh.subEvents||0)+1,relay:shortRelay(e)}),r.push(s[2]),c||(c=setTimeout(d,100)));else{clearTimeout(m),d(),finishRelaySubscribe(e,""),isNostrRefreshActive(t)&&updateNostrRefreshProgress({subscribeDone:state.relay.subscribeDone,indexed:state.hot.items.length}),u(),maybeFinishNostrRefresh(t);try{a.send(JSON.stringify(["CLOSE",i])),a.close()}catch(e){}}},a.onclose=()=>{clearTimeout(m),d(),l()&&("已连接"!==state.relay.statuses[e]&&finishRelaySubscribe(e,"断开"),maybeFinishNostrRefresh(t))},a.onerror=()=>{clearTimeout(m),d(),l()&&(finishRelaySubscribe(e,"失败"),Object.values(state.relay.statuses).includes("已连接")||setStatus("nostr","连接失败"),maybeFinishNostrRefresh(t))}}catch(n){if(t!==state.relay.subscribeToken)return;finishRelaySubscribe(e,"失败"),maybeFinishNostrRefresh(t)}})}function queryRelayHotPage(e,t,n){return new Promise(a=>{const i=[];let s=!1;const o=e=>{s||(s=!0,i.complete=!!e,a(i))};try{const a=new WebSocket(e),s="fongmi_hot_"+Date.now()+"_"+Math.random().toString(16).slice(2),r=setTimeout(()=>{try{a.close()}catch(e){}o(!1)},n||9e3);a.onopen=()=>a.send(JSON.stringify(["REQ",s,t])),a.onmessage=e=>{const t=safeJson(e.data,[]);if("EVENT"===t[0]&&t[2]&&i.push(t[2]),"EOSE"===t[0]){clearTimeout(r);try{a.send(JSON.stringify(["CLOSE",s])),a.close()}catch(e){}o(!0)}},a.onclose=()=>{clearTimeout(r),o(!1)},a.onerror=()=>{clearTimeout(r),o(!1)}}catch(e){o(!1)}})}const RELAY_MIRROR_PAGE_LIMIT=1e3,RELAY_MIRROR_MAX_PAGES_PER_SOURCE=120;function normalizeRelayUrl(e){const t=String(e||"").trim();if(!t)return"";try{const e=new URL(t);return"wss:"!==e.protocol&&"ws:"!==e.protocol?"":(e.hash="",e.toString().replace(/\/$/,""))}catch(e){return""}}function parseRelayList(e){return Array.from(new Set(String(e||"").split(/[\s,,]+/).map(normalizeRelayUrl).filter(Boolean)))}function setupRelayMirrorDefaults(){const e=$("mirrorSourceInput"),t=$("mirrorTargetInput");e&&!e.value.trim()&&(e.value=window.WEBHOME_CONFIG.nostr.relays.join("\n")),t&&(t.value=t.value||""),disablePanelTextEditing(e),disablePanelTextEditing(t)}function setMirrorProgress(e){const t=$("mirrorProgress");t&&(t.textContent=Array.isArray(e)?e.filter(Boolean).join("\n"):String(e||"镜像未执行"))}function isMirrorableHotEvent(e){return!(!(e&&e.id&&e.pubkey&&e.sig&&e.kind===window.WEBHOME_CONFIG.nostr.kind&&getD(e)===HOT_VECTOR_D)||eventExpired(e))}function mirrorEventKey(e){return eventAddress(e)||String(e&&e.id||"")}function mirrorEventIsNewer(e,t){if(!t)return!0;const n=Number(e&&e.created_at||0),a=Number(t&&t.created_at||0);return n!==a?n>a:String(e&&e.id||"")>String(t&&t.id||"")}async function queryMirrorEventsFromRelay(e,t,n){const a=new Map;let i=hotNow(),s=0;for(;i>t&&s<120;){s+=1,setMirrorProgress([`拉取中:${shortRelay(e)}`,`第 ${s} 页,已收到 ${a.size} 条`,n]);const o=await queryRelayHotPage(e,{kinds:[window.WEBHOME_CONFIG.nostr.kind],"#t":[window.WEBHOME_CONFIG.nostr.tag],"#d":[HOT_VECTOR_D],since:t,until:i,limit:1e3},12e3);if(o.filter(isMirrorableHotEvent).forEach(e=>a.set(e.id,e)),!o.length||!o.complete)break;let r=i;for(const e of o)r=Math.min(r,Number(e.created_at||r));if(o.length<1e3||r>=i)break;i=r-1}return Array.from(a.values())}async function publishMirrorEventToRelay(e,t,n){return new Promise(a=>{let i=!1;const s=(e,t)=>{i||(i=!0,a({ok:e,text:t||""}))};try{const a=new WebSocket(e),i=setTimeout(()=>{try{a.close()}catch(e){}s(!1,"超时")},n||9e3);a.onopen=()=>a.send(JSON.stringify(["EVENT",stripLocal(t)])),a.onmessage=e=>{const t=safeJson(e.data,[]);if("OK"===t[0]){clearTimeout(i);try{a.close()}catch(e){}s(!!t[2],t[2]?"OK":t[3]||"拒绝")}},a.onerror=()=>{clearTimeout(i),s(!1,"失败")},a.onclose=()=>s(!1,"断开")}catch(e){s(!1,e.message||"失败")}})}async function mirrorHotEventsToRelays(){if(mirrorHotEventsToRelays.busy)return;const e=parseRelayList($("mirrorSourceInput")&&$("mirrorSourceInput").value||window.WEBHOME_CONFIG.nostr.relays.join("\n")),t=parseRelayList($("mirrorTargetInput")&&$("mirrorTargetInput").value||"");if(!e.length)return toast("请填写源 relay");if(!t.length)return toast("请填写目标 relay");mirrorHotEventsToRelays.busy=!0;const n=$("mirrorRelayBtn");n&&(n.textContent="镜像中");try{const n=hotWindowStart(),a=new Map;for(const t of e){const i=await queryMirrorEventsFromRelay(t,n,`源 ${e.indexOf(t)+1}/${e.length} · 用户 ${a.size} 个`);i.forEach(e=>{const t=mirrorEventKey(e);t&&mirrorEventIsNewer(e,a.get(t))&&a.set(t,e)}),setMirrorProgress([`源完成:${shortRelay(t)}`,`本源有效 ${i.length} 条`,`按用户去重后 ${a.size} 条`])}const i=Array.from(a.values()).sort((e,t)=>Number(t.created_at||0)-Number(e.created_at||0));if(!i.length)return setMirrorProgress(["镜像完成","没有从源 relay 拉到可镜像的榜单事件"]),void toast("没有可镜像事件");let s=0,o=0,r=0,c=0;for(const e of t){let n=0,a=0,l=0;for(const d of i){c+=1,setMirrorProgress([`发布中:${shortRelay(e)}`,`事件 ${c}/${i.length*t.length}`,`总计 OK ${s} · 拒绝 ${o} · 失败 ${r}`]);const u=await publishMirrorEventToRelay(e,d,9e3);u.ok||/duplicate|exists|already|newer|older|replace/i.test(u.text||"")?(s+=1,n+=1):(u.text||"").includes("拒绝")?(o+=1,a+=1):(r+=1,l+=1)}setMirrorProgress([`目标完成:${shortRelay(e)}`,`OK ${n} · 拒绝 ${a} · 失败 ${l}`,`总计 OK ${s} · 拒绝 ${o} · 失败 ${r}`])}setMirrorProgress(["镜像完成",`源 relay ${e.length} 个,目标 relay ${t.length} 个`,`最新用户事件 ${i.length} 条`,`发布 OK ${s} · 拒绝 ${o} · 失败 ${r}`]),toast(`镜像完成:${i.length} 条事件`)}finally{mirrorHotEventsToRelays.busy=!1,n&&(n.textContent="镜像榜单")}}async function syncRelayBackfill(e,t){const n=null==t?state.relay.subscribeToken:t;if(n!==state.relay.subscribeToken)return;if(state.relay.backfillBusy[e])return;state.relay.backfillBusy[e]=!0;let a=null;try{const t=await openHotDb();if(n!==state.relay.subscribeToken)return;if(!t)return void(isNostrRefreshActive(n)&&updateNostrRefreshProgress({active:!1,phase:"本地索引不可用",finishedAt:Date.now()}));const i=selectPrimaryBackfillRelay(e,n)===e;isNostrRefreshActive(n)&&updateNostrRefreshProgress({phase:i?"回填历史":"回填近7天",relay:shortRelay(e)});const s=i?hotWindowStart():hotBackupWindowStart(),o=hotNow();if(a=normalizeRelayCursor(await hotStoreGet("relayCursor",e),e,s,o),n!==state.relay.subscribeToken)return;if(a.nextRetryAt&&a.nextRetryAt>o)return;let r=!1;if(r=await syncRelayRecent(e,a,s,o,n)||r,i&&!a.recentUntil&&(r=await syncRelayHistory(e,a,s,o,n)||r),n!==state.relay.subscribeToken)return;i||(a.historyDone=!0,a.historyUntil=s-1),a.updatedAt=hotNow(),a.primary=i;const c=t.transaction("relayCursor","readwrite");c.objectStore("relayCursor").put(a),await idbDone(c).catch(()=>{}),r&&(scheduleHotRefresh(900),setStatus("nostr",`已同步 ${shortRelay(e)}${i?" 主":" 近7天"}`),isNostrRefreshActive(n)&&updateNostrRefreshProgress({phase:"写入索引",indexed:state.hot.items.length,relay:shortRelay(e)}))}finally{n===state.relay.subscribeToken&&(delete state.relay.backfillBusy[e],a&&!relayBackfillDone(a)&&scheduleRelayBackfill(e,relayBackfillDelay(a),n),maybeFinishNostrRefresh(n))}}function selectPrimaryBackfillRelay(e,t){const n=choosePrimaryBackfillRelay(state.relay.subscribeDone>=window.WEBHOME_CONFIG.nostr.relays.length);return n&&n!==e&&!state.relay.backfillBusy[n]&&scheduleRelayBackfill(n,void 0,t),n}function choosePrimaryBackfillRelay(e){if(state.relay.primaryBackfillRelay)return state.relay.primaryBackfillRelay;if(!e)return"";const t=window.WEBHOME_CONFIG.nostr.relays;let n="",a=-1;return t.forEach(e=>{const t="已连接"===state.relay.statuses[e],i=Number(state.relay.backfillCandidates[e]||0);(t||i)&&i>a&&(n=e,a=i)}),n&&(state.relay.primaryBackfillRelay=n),state.relay.primaryBackfillRelay}function relayBackfillDone(e){return!e.recentUntil&&e.historyDone}function relayBackfillDelay(e){const t=Number(e&&e.nextRetryAt||0);return t>hotNow()?Math.max(650,1e3*(t-hotNow())):650}function markRelayBackfillRetry(e){e.failures=Math.min(12,Number(e.failures||0)+1);const t=Math.min(3e5,3e4*Math.pow(2,e.failures-1));e.nextRetryAt=hotNow()+Math.ceil(t/1e3)}function clearRelayBackfillRetry(e){e.failures=0,e.nextRetryAt=0}function scheduleRelayBackfill(e,t,n){clearTimeout(state.relay.backfillTimers[e]);const a=null==n?state.relay.subscribeToken:n;state.relay.backfillTimers[e]=setTimeout(()=>{delete state.relay.backfillTimers[e],isNostrRefreshActive(a)&&updateNostrRefreshProgress({phase:"回填排队完成",relay:shortRelay(e)}),syncRelayBackfill(e,a).catch(()=>{})},Number.isFinite(t)?t:650),isNostrRefreshActive(a)&&updateNostrRefreshProgress({phase:"等待回填",relay:shortRelay(e)})}function normalizeRelayCursor(e,t,n,a){if(!e)return{relay:t,since:n,newest:a,recentHigh:0,recentUntil:0,recentTarget:0,historyUntil:a,historyDone:!1,updatedAt:0,failures:0,nextRetryAt:0};const i=e||{},s=Number(i.since||0),o=s>n,r=Math.max(Number(i.newest||0),n-1);let c=Number(i.historyUntil||i.until||0);o&&(c=Math.max(n,s-1)),(!c||c<n)&&(c=Math.max(r,a));const l=!o&&(!0===i.historyDone||!0===i.done&&c<=n);return{relay:t,since:n,newest:r,recentHigh:Math.max(Number(i.recentHigh||0),0),recentUntil:Math.max(Number(i.recentUntil||0),0),recentTarget:Math.max(Number(i.recentTarget||0),0),historyUntil:c,historyDone:l,updatedAt:Number(i.updatedAt||0),failures:Number(i.failures||0),nextRetryAt:Number(i.nextRetryAt||0)}}async function syncRelayRecent(e,t,n,a,i){if(!t.recentUntil&&a>t.newest&&(t.recentHigh=a,t.recentUntil=a,t.recentTarget=Math.max(n,Number(t.newest||0)+1)),!t.recentUntil)return!1;let s=!1;for(let n=0;n<6&&!(t.recentUntil<t.recentTarget);n++){const n=await queryRelayHotPage(e,{kinds:[window.WEBHOME_CONFIG.nostr.kind],"#t":[window.WEBHOME_CONFIG.nostr.tag],"#d":[HOT_VECTOR_D],since:t.recentTarget,until:t.recentUntil,limit:1e3},9e3);if(null!=i&&i!==state.relay.subscribeToken)break;if(isNostrRefreshActive(i)&&updateNostrRefreshProgress({phase:"回填近7天",relay:shortRelay(e),recentPages:Number(state.relay.refresh&&state.relay.refresh.recentPages||0)+1,recentEvents:Number(state.relay.refresh&&state.relay.refresh.recentEvents||0)+n.length}),!n.length){if(!n.complete){markRelayBackfillRetry(t);break}clearRelayBackfillRetry(t),finishRelayRecent(t);break}clearRelayBackfillRetry(t);let a=t.recentUntil;for(const e of n)a=Math.min(a,Number(e.created_at||a));if(await hotIngestEvents(n)&&(s=!0,isNostrRefreshActive(i)&&updateNostrRefreshProgress({phase:"写入索引",indexed:state.hot.items.length,relay:shortRelay(e)})),t.recentUntil=a-1,!n.complete)break;if(n.length<1e3||t.recentUntil<t.recentTarget){finishRelayRecent(t);break}if(null!=i&&i!==state.relay.subscribeToken)break}return s}function finishRelayRecent(e){const t=Number(e.recentTarget||0)-1;e.newest=Math.max(Number(e.newest||0),Number(e.recentHigh||0)),t<=Number(e.since||0)?(e.historyDone=!0,e.historyUntil=Number(e.since||0)-1):e.historyDone||e.historyUntil&&!(e.historyUntil>t)||(e.historyUntil=t),e.recentHigh=0,e.recentUntil=0,e.recentTarget=0}async function syncRelayHistory(e,t,n,a,i){if(t.historyDone)return!1;(!t.historyUntil||t.historyUntil<n)&&(t.historyUntil=Math.max(t.newest||0,a));let s=!1;for(let a=0;a<10&&(null==i||i===state.relay.subscribeToken);a++){if(t.historyUntil<=n){t.historyDone=!0;break}const a=await queryRelayHotPage(e,{kinds:[window.WEBHOME_CONFIG.nostr.kind],"#t":[window.WEBHOME_CONFIG.nostr.tag],"#d":[HOT_VECTOR_D],since:n,until:t.historyUntil,limit:1e3},9e3);if(null!=i&&i!==state.relay.subscribeToken)break;if(isNostrRefreshActive(i)&&updateNostrRefreshProgress({phase:"回填历史",relay:shortRelay(e),historyPages:Number(state.relay.refresh&&state.relay.refresh.historyPages||0)+1,historyEvents:Number(state.relay.refresh&&state.relay.refresh.historyEvents||0)+a.length}),!a.length){if(!a.complete){markRelayBackfillRetry(t);break}clearRelayBackfillRetry(t),t.historyDone=!0;break}clearRelayBackfillRetry(t);let o=t.historyUntil;for(const e of a)o=Math.min(o,Number(e.created_at||o));if(await hotIngestEvents(a)&&(s=!0,isNostrRefreshActive(i)&&updateNostrRefreshProgress({phase:"写入索引",indexed:state.hot.items.length,relay:shortRelay(e)})),t.historyUntil=o-1,!a.complete)break;if(t.historyDone=a.length<1e3||t.historyUntil<=n,t.historyDone)break}return s}function publishEvent(e){if(!e||!e.sig)return void setStatus("publish","未签名,未发布");const t=window.WEBHOME_CONFIG.nostr.relays;state.relay.total=t.length;let n=0,a=0;state.relay.lastOk=0,state.relay.lastDone=0,setStatus("publish",`发布中 0/${t.length}`),t.forEach(i=>{try{const s=new WebSocket(i),o=(e,i)=>{n+=1,e&&(a+=1),state.relay.lastOk=a,state.relay.lastDone=n,setStatus("publish",`发布 ${a}/${n}/${t.length}${i?" · "+i:""}`),renderMetrics()},r=setTimeout(()=>{o(!1,shortRelay(i)+" 超时");try{s.close()}catch(e){}},6e3);s.onopen=()=>s.send(JSON.stringify(["EVENT",stripLocal(e)])),s.onmessage=e=>{const t=safeJson(e.data,[]);if("OK"===t[0]){clearTimeout(r),t[2]&&(state.relay.published+=1),o(!!t[2],`${shortRelay(i)} ${t[2]?"OK":t[3]||"拒绝"}`);try{s.close()}catch(e){}}},s.onerror=()=>{clearTimeout(r),o(!1,shortRelay(i)+" 失败")}}catch(e){n+=1,state.relay.lastOk=a,state.relay.lastDone=n,setStatus("publish",`发布 ${a}/${n}/${t.length} · ${shortRelay(i)} 失败`)}})}function eventAddress(e){const t=getD(e);return e&&e.kind&&e.pubkey&&t?`${e.kind}:${e.pubkey}:${t}`:""}function createDeleteEvent(e,t){const n=Array.from(new Set(e.map(e=>e&&e.id).filter(Boolean))),a=Array.from(new Set(e.map(eventAddress).filter(Boolean))),i=n.map(e=>["e",e]).concat(a.map(e=>["a",e]));i.push(["t",window.WEBHOME_CONFIG.nostr.tag],["app","fongmi-webhome"]);const s={kind:5,created_at:Math.floor(Date.now()/1e3),tags:i,content:"delete fongmi webhome preference events"};return window.NostrTools.finalizeEvent(s,t.secret)}function publishToRelay(e,t,n){return new Promise(a=>{let i=!1;const s=(e,t)=>{i||(i=!0,a({ok:e,text:t}))};try{const a=new WebSocket(e),i=setTimeout(()=>{try{a.close()}catch(e){}s(!1,"超时")},n||7e3);a.onopen=()=>a.send(JSON.stringify(["EVENT",t])),a.onmessage=e=>{const t=safeJson(e.data,[]);if("OK"===t[0]){clearTimeout(i);try{a.close()}catch(e){}s(!!t[2],t[2]?"OK":t[3]||"拒绝")}},a.onerror=()=>{clearTimeout(i),s(!1,"失败")}}catch(e){s(!1,e.message||"失败")}})}async function queryRelayEventsPaged(e,t,n){const a=[];let i=Math.floor(Date.now()/1e3);for(let s=0;s<20;s++){const s=await queryRelayHotPage(e,{kinds:[window.WEBHOME_CONFIG.nostr.kind],authors:[t],"#t":[window.WEBHOME_CONFIG.nostr.tag],"#d":[HOT_VECTOR_D],since:n,until:i,limit:1e3},9e3);if(!s.length)break;if(a.push(...s),i=Math.min(...s.map(e=>Number(e.created_at||i)))-1,s.length<1e3)break}return a}async function clearLocalPreferenceData(){await clearLocalEvents(!1),setStatus("publish","已清理本机缓存"),toast("本机偏好缓存已清理")}async function clearMyNostrData(e){if(!(e=e||await ensureIdentity())||!e.pubkey||!e.secret)return toast("请先同步或生成身份");setStatus("publish","查询我的事件");const t=hotWindowStart(),n=window.WEBHOME_CONFIG.nostr.relays,a=[];for(const i of n)a.push(...await queryRelayEventsPaged(i,e.pubkey,t));const i=Array.from(new Map(a.filter(e=>e&&e.id).map(e=>[e.id,e])).values());if(!i.length)return await clearLocalEvents(!0),setStatus("publish","没有找到我的远端事件"),void toast("没有找到需要删除的数据");const s=createDeleteEvent(i,e);let o=0,r=0;setStatus("publish",`删除中 0/${n.length}`);for(const e of n){const t=await publishToRelay(e,s,7e3);r+=1,t.ok&&(o+=1),setStatus("publish",`删除 ${o}/${r}/${n.length} · ${shortRelay(e)} ${t.text||""}`)}await clearLocalEvents(!0),toast(`删除请求已发送 ${o}/${n.length}`)}async function deleteAllPreferenceData(){const e=await ensureIdentity();await markIdentityDeletedLocally(e),stopWatchTracking(!1),await clearPendingWatch(),await clearLocalPreferenceData(),await clearMyNostrData(e)}function stripLocal(e){const t=Object.assign({},e);return delete t.local,t}function getD(e){const t=(e&&e.tags||[]).find(e=>e&&"d"===e[0]);return t&&t[1]}function eventContent(e){const t=e&&e.content;return t&&"object"==typeof t?t:safeJson(t,null)}function bindActions(){$("refreshNostrBtn").addEventListener("click",()=>{forceRefreshNostrRanking().catch(e=>toast(e.message||"刷新榜单失败"))}),$("mirrorRelayBtn").addEventListener("click",()=>{mirrorHotEventsToRelays().catch(e=>{setMirrorProgress(["镜像失败",e.message||String(e||"")]),toast(e.message||"镜像失败")})}),$("syncBtn").addEventListener("click",openSync),$("closeSyncBtn").addEventListener("click",()=>closeSync(!1)),$("saveNsecBtn").addEventListener("click",async()=>{try{await setIdentity($("nsecInput").value),toast("同步身份已导入")}catch(e){toast(e.message||"导入失败")}}),$("newNsecBtn").addEventListener("click",async()=>{if(await waitForNostrTools(),!window.NostrTools)return toast("Nostr 工具未加载");const e=window.NostrTools.nip19.nsecEncode(window.NostrTools.generateSecretKey());await setIdentity(e),$("nsecInput").value=e,toast("已生成新身份")}),$("connectionToggle").addEventListener("click",toggleConnectionPanel),$("connectionToggle").addEventListener("keydown",e=>{"Enter"!==normalizeRemoteKey(e)&&" "!==e.key||toggleConnectionPanel(e)}),$("deleteDataBtn").addEventListener("click",()=>{closeConnectionPanel(),setStatus("publish","后台删除数据中"),toast("已开始后台删除数据"),deleteAllPreferenceData().catch(e=>toast(e.message||"删除失败"))}),$("savePanConfigBtn").addEventListener("click",()=>{savePanConfig().catch(e=>toast(e.message||"保存失败"))}),document.querySelectorAll("[data-mobile-detail-style]").forEach(e=>{e.addEventListener("click",()=>{setMobileDetailStyle(e.dataset.mobileDetailStyle).catch(()=>{})}),e.addEventListener("keydown",e=>{if("ArrowLeft"!==e.key&&"ArrowRight"!==e.key)return;e.preventDefault();const t="ArrowRight"===e.key?"translucent":"immersive";setMobileDetailStyle(t).then(()=>{const e=document.querySelector(`[data-mobile-detail-style="${t}"]`);e&&focusRemoteTarget(e)}).catch(()=>{})})}),document.querySelectorAll("[data-rating-limit]").forEach(e=>{e.addEventListener("click",()=>{setRatingLimitEnabled("off"!==e.dataset.ratingLimit).catch(()=>{})}),e.addEventListener("keydown",e=>{if("ArrowLeft"!==e.key&&"ArrowRight"!==e.key)return;e.preventDefault();const t="ArrowRight"===e.key?"off":"on";setRatingLimitEnabled("off"!==t).then(()=>{const e=document.querySelector(`[data-rating-limit="${t}"]`);e&&focusRemoteTarget(e)}).catch(()=>{})})}),document.querySelectorAll("[data-home-fullscreen]").forEach(e=>{e.addEventListener("click",()=>{setHomeFullscreenEnabled("off"!==e.dataset.homeFullscreen).catch(()=>{})}),e.addEventListener("keydown",e=>{if("ArrowLeft"!==e.key&&"ArrowRight"!==e.key)return;e.preventDefault();const t="ArrowRight"===e.key?"off":"on";setHomeFullscreenEnabled("off"!==t).then(()=>{const e=document.querySelector(`[data-home-fullscreen="${t}"]`);e&&focusRemoteTarget(e)}).catch(()=>{})})}),document.querySelectorAll("[data-high-res-backdrop]").forEach(e=>{e.addEventListener("click",()=>{setHighResBackdropEnabled("off"!==e.dataset.highResBackdrop).catch(()=>{})}),e.addEventListener("keydown",e=>{if("ArrowLeft"!==e.key&&"ArrowRight"!==e.key)return;e.preventDefault();const t="ArrowRight"===e.key?"off":"on";setHighResBackdropEnabled("off"!==t).then(()=>{const e=document.querySelector(`[data-high-res-backdrop="${t}"]`);e&&focusRemoteTarget(e)}).catch(()=>{})})});const e=document.querySelector(".pan-config");e&&(e.addEventListener("input",markPanConfigDirty),e.addEventListener("change",markPanConfigDirty)),$("closeImageBtn").addEventListener("click",()=>closeImage(!1)),$("mobileImageBackBtn").addEventListener("click",()=>closeImage(!1)),$("imageViewer").addEventListener("click",e=>{e.target===$("imageViewer")&&closeImage(!1)}),$("detailSheet").addEventListener("scroll",()=>{updateMobileDetailBackButton(),scheduleUiSnapshotSave()},{passive:!0}),bindDetailCoverSwipe(),bindEpisodeViewerSwipe(),$("detailMoreBtn").addEventListener("click",toggleDetailTextMore),$("detailText").addEventListener("click",handleDetailTextClick),$("panTabs").addEventListener("click",handlePanTabEvent),$("panTabs").addEventListener("touchend",handlePanTabEvent),$("panTabs").addEventListener("keydown",e=>{"Enter"!==normalizeRemoteKey(e)&&" "!==e.key||handlePanTabEvent(e)}),$("panTabs").addEventListener("keyup",e=>{"Enter"!==normalizeRemoteKey(e)&&" "!==e.key||handlePanTabEvent(e)}),$("searchInput").addEventListener("input",scheduleSearchSuggest),$("searchInput").addEventListener("pointerdown",enableSearchEditing),$("searchInput").addEventListener("mousedown",enableSearchEditing),$("searchInput").addEventListener("touchstart",enableSearchEditing,{passive:!0}),$("searchInput").addEventListener("focus",()=>{$("searchInput").readOnly&&hideSearchSuggest()}),$("searchInput").addEventListener("blur",disableSearchEditing),document.querySelectorAll("#connectionBody input, #connectionBody textarea").forEach(e=>{e.addEventListener("pointerdown",()=>enablePanelTextEditing(e)),e.addEventListener("mousedown",()=>enablePanelTextEditing(e)),e.addEventListener("touchstart",()=>enablePanelTextEditing(e),{passive:!0}),e.addEventListener("blur",()=>disablePanelTextEditing(e))}),$("searchInput").addEventListener("keydown",e=>{if(document.activeElement!==$("searchInput"))return;const t=normalizeRemoteKey(e);if("ArrowDown"===t&&isSearchSuggestOpen()){const t=firstSearchSuggestItem();return e.preventDefault(),e.stopPropagation(),void(t&&focusSearchSuggestTarget(t))}return"ArrowDown"===t&&$("searchInput").readOnly?(e.preventDefault(),e.stopPropagation(),void focusHomeTopTarget(activeHomeChip(),{preventScroll:!0,force:!0})):"Enter"===t&&$("searchInput").readOnly?(e.preventDefault(),e.stopPropagation(),enableSearchEditing(),void $("searchInput").focus()):void 0}),document.addEventListener("click",e=>{$("searchForm").contains(e.target)||hideSearchSuggest()}),$("searchForm").addEventListener("submit",e=>{e.preventDefault(),submitSearchInput()});const t=$("searchSubmitBtn")||$("searchForm").querySelector("button[type='submit']");t.addEventListener("pointerdown",handleSearchNativeHoldStart),t.addEventListener("pointermove",handleSearchNativeHoldMove),t.addEventListener("pointerup",handleSearchNativeHoldEnd),t.addEventListener("pointercancel",clearSearchHold),t.addEventListener("pointerleave",clearSearchHold),t.addEventListener("contextmenu",e=>{Date.now()<Number(state.searchHold.suppressClickUntil||0)&&e.preventDefault()}),t.addEventListener("blur",clearSearchHold),t.addEventListener("click",handleSearchSubmitClick),$("homeSettingBtn").addEventListener("click",openSettingHome),$("clearSearchBtn").addEventListener("click",clearSearchResults),$("mobileDetailBackBtn").addEventListener("click",()=>closeDetail(!1)),$("detailContinueBtn").addEventListener("click",()=>{openDetailContinueHistory()}),$("detailSearchBtn").addEventListener("click",()=>{state.selected&&(rememberWatchIntent(state.selected,"search"),startWatchTracking(state.selected),nativeSearch(state.selected.title))}),$("panSearchBtn").addEventListener("click",()=>{state.selected&&searchPanResources(state.selected)}),$("backTopBtn").addEventListener("click",()=>{scrollHomeToTop()})}function bindDetailCoverSwipe(){const e=$("detailImage")&&$("detailImage").parentElement;e&&(e.addEventListener("touchstart",e=>{if(document.documentElement.classList.contains("tv-mode")||state.detailCover.images.length<=1)return;const t=e.touches&&e.touches[0];t&&(state.detailCover.swipe={x:t.clientX,y:t.clientY,at:Date.now(),moved:!1})},{passive:!0}),e.addEventListener("touchmove",e=>{const t=state.detailCover.swipe,n=e.touches&&e.touches[0];if(!t||!n)return;const a=n.clientX-t.x,i=n.clientY-t.y;Math.abs(a)>12&&Math.abs(a)>1.25*Math.abs(i)&&(t.moved=!0,e.preventDefault())},{passive:!1}),e.addEventListener("touchend",e=>{const t=state.detailCover.swipe;if(state.detailCover.swipe=null,!t||!t.moved||state.detailCover.images.length<=1)return;const n=e.changedTouches&&e.changedTouches[0];if(!n)return;const a=n.clientX-t.x,i=n.clientY-t.y;Math.abs(a)<42||Math.abs(a)<1.25*Math.abs(i)||Date.now()-t.at>900||(e.preventDefault(),e.stopPropagation(),shiftDetailCover(a<0?1:-1))},{passive:!1}),e.addEventListener("touchcancel",()=>{state.detailCover.swipe=null},{passive:!0}))}function bindEpisodeViewerSwipe(){const e=$("imageContent");e&&(e.addEventListener("touchstart",e=>{const t=$("imageViewer");if(!t||!t.classList.contains("episode-mode")||!t.classList.contains("active"))return;if((state.episodeViewer.episodes||[]).length<=1)return;const n=e.touches&&e.touches[0];n&&(state.episodeViewer.swipe={x:n.clientX,y:n.clientY,at:Date.now(),moved:!1})},{passive:!0}),e.addEventListener("touchmove",e=>{const t=state.episodeViewer.swipe,n=e.touches&&e.touches[0];if(!t||!n)return;const a=n.clientX-t.x,i=n.clientY-t.y;Math.abs(a)>16&&Math.abs(a)>1.35*Math.abs(i)&&(t.moved=!0,e.preventDefault())},{passive:!1}),e.addEventListener("touchend",e=>{const t=state.episodeViewer.swipe;if(state.episodeViewer.swipe=null,!t||!t.moved)return;const n=e.changedTouches&&e.changedTouches[0];if(!n)return;const a=n.clientX-t.x,i=n.clientY-t.y;Math.abs(a)<46||Math.abs(a)<1.35*Math.abs(i)||Date.now()-t.at>1e3||(e.preventDefault(),e.stopPropagation(),switchEpisodeViewer(a<0?1:-1))},{passive:!1}),e.addEventListener("touchcancel",()=>{state.episodeViewer.swipe=null},{passive:!0}))}function scrollHomeToTop(){try{window.scrollTo({top:0,behavior:"smooth"})}catch(e){window.scrollTo(0,0),document.documentElement.scrollTop=0,document.body.scrollTop=0}setTimeout(updateBackTopButton,260)}function installRemoteKeys(){document.addEventListener("keydown",e=>{const t=normalizeRemoteKey(e);if(!t)return;const n=document.activeElement,a=isTextEditingElement(n);if(!a&&shouldThrottleRemoteNav(t,e,n))return void e.preventDefault();if("Enter"!==t&&["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(t)&&ensureRemoteActiveFocus())return void e.preventDefault();if("Enter"===t){if(consumeBlockCardEnterDown(blockableRecommendCard(n),e))return;if(handleConnectionPanelEnterKey(e))return;if(consumeSearchSubmitEnterDown(n,e))return;return n===$("searchInput")&&n.readOnly?(e.preventDefault(),enableSearchEditing(),void n.focus()):void activateFocusedElement(n,e)}if(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(t)){if(handleSearchSuggestDirectionalKey(t,e))return;if(handleSearchFormDirectionalKey(t,e))return;if(handleConnectionPanelDirectionalKey(t,e))return}if(("Escape"===t||"Backspace"===t)&&handleConnectionPanelBackKey(e))return;if(a){if(n===$("searchInput")&&n.readOnly&&"ArrowDown"===t)return e.preventDefault(),n.blur(),void focusHomeTopTarget(activeHomeChip(),{preventScroll:!0,force:!0});if("Escape"===t&&(e.preventDefault(),n.blur()),["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(t)){const a=nearestFocusable(t,n);if(!a)return;e.preventDefault(),n.blur(),focusRemoteTarget(a)}return}if("Escape"===t||"Backspace"===t){if(exitBlockSelectMode())return void e.preventDefault();if(collapseInlineEpisodePreview(e))return;if(handleSearchSuggestBackKey(e))return;if(handleConnectionPanelBackKey(e))return;if(handlePanBackKey(e))return;if(handleSearchBackKey(e))return;return e.preventDefault(),$("imageViewer").classList.contains("active")||$("detailSheet").classList.contains("active")||$("syncSheet").classList.contains("active")?history.back():sdk().back?sdk().back():void 0}if(!["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(t))return;if(handleEpisodeViewerDirectionalKey(t,e))return;if(handleScrollableOverlayKey(t,e))return;if(handlePanDirectionalKey(t,e))return;if(handleDetailDirectionalKey(t,e))return;const i=fastHomeDirectionalTarget(t,n)||nearestFocusable(t);i&&(e.preventDefault(),isPanFocusTarget(i)||(state.pan.focusMode=""),focusRemoteTarget(i))}),document.addEventListener("keydown",e=>{const t=normalizeRemoteKey(e);"Escape"!==t&&"Backspace"!==t||shouldKeepBackspaceForTextEditing(e)||state.blocked.selecting||collapseInlineEpisodePreview(e)||handleSearchSuggestBackKey(e)||handleConnectionPanelBackKey(e)||handlePanBackKey(e)||handleSearchBackKey(e)},!0),document.addEventListener("keyup",e=>{"Enter"===normalizeRemoteKey(e)&&(handleSearchSubmitEnterUp(e)||handleBlockCardEnterUp(e)||clearBlockLongPress())},!0)}function activateFocusedElement(e,t){if(!isVisibleFocusable(e))return!1;if(isTextEditingElement(e))return!1;if(t.preventDefault(),t.stopPropagation(),state.blocked.longPressFired)return state.blocked.longPressFired=!1,!0;const n=blockableRecommendCard(e);if(state.blocked.selecting&&n)return!0;const a=getPanTypeFromElement(e);if(a)return selectPanType(a),!0;if("function"==typeof e.click)e.click();else{const t=document.createEvent("MouseEvents");t.initMouseEvent("click",!0,!0,window,1,0,0,0,0,!1,!1,!1,!1,0,null),e.dispatchEvent(t)}return!0}function isTextEditingElement(e){if(!e)return!1;if("TEXTAREA"===e.tagName||e.isContentEditable)return!0;if("INPUT"!==e.tagName)return!1;const t=String(e.getAttribute("type")||"text").toLowerCase();return!["button","checkbox","radio","submit","reset","range","color"].includes(t)}function shouldKeepBackspaceForTextEditing(e){if(!e||"Backspace"!==normalizeRemoteKey(e))return!1;const t=document.activeElement;return!(!t||!isTextEditingElement(t)||t.readOnly||t.disabled)}function isPanelTextField(e){return!(!(e&&$("connectionBody")&&$("connectionBody").contains(e))||"TEXTAREA"!==e.tagName&&("INPUT"!==e.tagName||["button","checkbox","radio","submit","reset","range","color"].includes(String(e.getAttribute("type")||"text").toLowerCase())))}function enablePanelTextEditing(e){if(!isPanelTextField(e))return!1;e.readOnly=!1,e.classList.add("panel-editing");try{e.focus({preventScroll:!0})}catch(t){e.focus()}return!0}function disablePanelTextEditing(e){return!!isPanelTextField(e)&&(e.readOnly=!0,e.classList.remove("panel-editing"),!0)}function disableConnectionTextEditing(){const e=$("connectionBody");e&&e.querySelectorAll("input,textarea").forEach(e=>{isPanelTextField(e)&&disablePanelTextEditing(e)})}function handleConnectionPanelEnterKey(e){if(!isConnectionPanelOpen())return!1;const t=document.activeElement;return!!(t&&$("connectionDock")&&$("connectionDock").contains(t))&&(t!==$("connectionToggle")&&(t.matches&&t.matches("input[type='checkbox']")?(e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation&&e.stopImmediatePropagation(),t.click(),t.dataset&&(t.dataset.mobileDetailStyle||t.dataset.ratingLimit)||markPanConfigDirty(),!0):!!isPanelTextField(t)&&(!!t.readOnly&&(e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation&&e.stopImmediatePropagation(),enablePanelTextEditing(t),!0))))}function handleScrollableOverlayKey(e,t){if(!$("imageViewer")||!$("imageViewer").classList.contains("active"))return!1;const n=$("imageContent");if(!n||"ArrowUp"!==e&&"ArrowDown"!==e)return!1;const a=n.scrollHeight-n.clientHeight;if(a<=4)return!1;const i=Math.max(80,Math.round(.72*n.clientHeight))*("ArrowDown"===e?1:-1);return"ArrowUp"===e&&n.scrollTop<=0?(t.preventDefault(),focusRemoteTarget($("closeImageBtn")),!0):!("ArrowDown"===e&&n.scrollTop>=a-2)&&(t.preventDefault(),n.scrollTop=Math.max(0,Math.min(a,n.scrollTop+i)),n.contains(document.activeElement)||focusRemoteTarget(n),!0)}function handleEpisodeViewerDirectionalKey(e,t){if("ArrowLeft"!==e&&"ArrowRight"!==e)return!1;const n=$("imageViewer");return!!(n&&n.classList.contains("active")&&n.classList.contains("episode-mode"))&&(t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation&&t.stopImmediatePropagation(),switchEpisodeViewer("ArrowRight"===e?1:-1),focusRemoteTarget($("imageContent")),!0)}function handlePanBackKey(e){const t=$("panTabs"),n=$("panResultList"),a=document.activeElement,i=!!(t&&n&&a&&n.contains(a));return!(!t||!n||!i&&"results"!==state.pan.focusMode)&&(e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation&&e.stopImmediatePropagation(),focusPanTabFromResults(),scheduleUiSnapshotSave(),!0)}function handleSearchBackKey(e){if(shouldKeepBackspaceForTextEditing(e))return!1;if(!state.searchItems.length||!$("searchSection")||"none"===$("searchSection").style.display)return!1;const t=document.activeElement;return!(!t||!$("searchSection").contains(t)&&!$("searchForm").contains(t))&&(e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation&&e.stopImmediatePropagation(),clearSearchResults(),requestAnimationFrame(()=>focusInitialHomeNow()),!0)}function handleSearchSuggestBackKey(e){if(shouldKeepBackspaceForTextEditing(e))return!1;if(!isSearchSuggestOpen())return!1;const t=document.activeElement,n=$("searchInput"),a=$("suggestPanel"),i=$("searchForm");return!(!t||!(t===n||a&&a.contains(t)||i&&i.contains(t)))&&(e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation&&e.stopImmediatePropagation(),hideSearchSuggest(),disableSearchEditing(),n&&requestAnimationFrame(()=>focusRemoteTarget(n)),!0)}function handleSearchSuggestDirectionalKey(e,t){if(!isSearchSuggestOpen()||!["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(e))return!1;const n=$("searchInput"),a=$("suggestPanel"),i=$("searchForm"),s=document.activeElement;if(!(s&&(s===n||a&&a.contains(s)||i&&i.contains(s))))return!1;const o=searchSuggestItems();let r=null;if(s===n||i&&i.contains(s)&&(!a||!a.contains(s))){if(s===n&&"ArrowRight"===e)return!1;r="ArrowDown"===e&&o[0]||n}else if(a&&a.contains(s)){const t=o.indexOf(s);r="ArrowDown"===e?o[Math.min(o.length-1,t+1)]||s:"ArrowUp"===e?t<=0?n:o[t-1]:s}return t.preventDefault(),t.stopPropagation(),r&&focusSearchSuggestTarget(r),!0}function handleSearchFormDirectionalKey(e,t){if(!$("searchForm"))return!1;const n=$("searchInput"),a=$("searchForm").querySelector("button[type='submit']"),i=$("homeSettingBtn"),s=document.activeElement;let o=null;return s===a&&"ArrowLeft"===e?o=n:s===a&&"ArrowRight"===e?o=i:s===i&&"ArrowLeft"===e||s===n&&"ArrowRight"===e?o=a:(s===n&&"ArrowDown"===e||s===a&&"ArrowDown"===e||s===i&&"ArrowDown"===e)&&(o=activeHomeChip()),!!o&&(t.preventDefault(),t.stopPropagation(),o===n&&n.readOnly&&hideSearchSuggest(),focusRemoteTarget(o),!0)}function isSearchSuggestOpen(){const e=$("suggestPanel");return!!(e&&e.classList.contains("open")&&e.querySelector(".suggest-item"))}function searchSuggestItems(){const e=$("suggestPanel");return e?Array.from(e.querySelectorAll(".suggest-item")).filter(isVisibleFocusable):[]}function firstSearchSuggestItem(){return searchSuggestItems()[0]||null}function focusSearchSuggestTarget(e){if(e){try{e.focus({preventScroll:!0})}catch(t){e.focus()}keepSearchSuggestItemVisible(e)}}function keepSearchSuggestItemVisible(e){const t=$("suggestPanel");if(!t||!e||!t.contains(e))return;const n=e.getBoundingClientRect(),a=t.getBoundingClientRect(),i=n.top-a.top,s=n.bottom-a.bottom;i<0?t.scrollTop+=i:s>0&&(t.scrollTop+=s)}function handleConnectionPanelBackKey(e){if(!isConnectionPanelOpen())return!1;const t=document.activeElement;if(isPanelTextField(t)&&!t.readOnly)return"Backspace"!==normalizeRemoteKey(e)&&(e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation&&e.stopImmediatePropagation(),disablePanelTextEditing(t),focusRemoteTarget(t),!0);e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation&&e.stopImmediatePropagation(),closeConnectionPanel();const n=$("connectionToggle");return n&&requestAnimationFrame(()=>focusRemoteTarget(n)),!0}function handleConnectionPanelDirectionalKey(e,t){if(!isConnectionPanelOpen()||!["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(e))return!1;const n=$("connectionDock"),a=$("connectionBody"),i=$("connectionToggle");if(!n||!a)return!1;const s=document.activeElement,o=connectionPanelItems();let r=null;return s&&n.contains(s)&&s!==i?a.contains(s)?(r=nearestFocusableFromList(e,s,o),r||"ArrowUp"!==e||(r=i||o[0]),r||(r=s)):r=o[0]||i:r="ArrowDown"===e?o[0]||i:i||o[0],t.preventDefault(),t.stopPropagation(),r&&focusRemoteTarget(r),!0}function restoreConnectionPanelFocus(){if(!isConnectionPanelOpen())return!1;const e=$("connectionDock"),t=document.activeElement;if(t&&e&&e.contains(t)&&isVisibleFocusable(t))return!1;const n=$("connectionToggle")||connectionPanelItems()[0];return!!n&&(focusRemoteTarget(n),!0)}function isConnectionPanelOpen(){const e=$("connectionDock"),t=$("connectionBody");return!!(e&&t&&e.classList.contains("open")&&t.classList.contains("open"))}function connectionPanelItems(){const e=$("connectionBody");return e?Array.from(e.querySelectorAll(".focusable,button,input,textarea")).filter(isVisibleFocusable):[]}function nearestFocusableFromList(e,t,n){const a=(n||[]).filter(e=>e&&e!==t&&isVisibleFocusable(e));if(!t||!a.length)return null;const i=center(t.getBoundingClientRect()),s="ArrowUp"===e||"ArrowDown"===e,o="ArrowRight"===e||"ArrowDown"===e;let r=null,c=1/0;for(const e of a){const t=center(e.getBoundingClientRect()),n=s?t.y-i.y:t.x-i.x,a=s?Math.abs(t.x-i.x):Math.abs(t.y-i.y);if(o?n<=4:n>=-4)continue;const l=1.25*Math.abs(n)+1.9*a;l<c&&(r=e,c=l)}return r}function focusPanTabFromResults(){const e=$("panTabs");if(!e)return!1;const t=findByDataset(e,"panType",state.pan.activeType)||e.querySelector(".chip.active")||e.querySelector(".chip");return!!t&&(state.pan.focusMode="tabs",focusPanTarget(t),!0)}function handlePanDirectionalKey(e,t){const n=$("panTabs"),a=$("panResultList"),i=document.activeElement;if(!n||!a||!i)return!1;const s=n.contains(i),o=a.contains(i);if(!s&&!o){if((i===$("detailContinueBtn")||i===$("panSearchBtn")||i===$("detailSearchBtn"))&&"ArrowDown"===e&&isPanSearchActive()){const e=n.querySelector(".chip.active")||n.querySelector(".chip")||a.querySelector(".pan-result-item");if(e)return t.preventDefault(),state.pan.focusMode=n.contains(e)?"tabs":"results",focusPanTarget(e,{keepBlockPosition:!0}),!0}if(isPanSearchActive()&&$("detailSheet")&&$("detailSheet").contains(i)){const s=$("panSearchBlock").getBoundingClientRect(),o=i.getBoundingClientRect?i.getBoundingClientRect():null;if("ArrowDown"===e&&o&&o.bottom<=s.bottom+8){t.preventDefault();const e=n.querySelector(".chip.active")||n.querySelector(".chip")||a.querySelector(".pan-result-item");return e?(state.pan.focusMode=n.contains(e)?"tabs":"results",focusPanTarget(e,{keepBlockPosition:!0})):centerPanSearchBlock(),!0}}return state.pan.focusMode="",!1}let r=null;if(s&&"ArrowDown"===e?r=panResultByColumn(i)||a.querySelector(".pan-result-item"):o&&"ArrowUp"===e&&isFirstVisiblePanResult(i)?r=findByDataset(n,"panType",state.pan.activeType)||n.querySelector(".chip.active")||n.querySelector(".chip"):!s||"ArrowLeft"!==e&&"ArrowRight"!==e?!o||"ArrowUp"!==e&&"ArrowDown"!==e||(r=siblingFocusable(a,i,"ArrowDown"===e?1:-1)):r=siblingFocusable(n,i,"ArrowRight"===e?1:-1),!r)return!!(s&&"ArrowDown"===e||o&&"ArrowDown"===e)&&(t.preventDefault(),centerPanSearchBlock(),!0);if(t.preventDefault(),a.contains(r))state.pan.focusKey=r.dataset.panKey||state.pan.focusKey,state.pan.focusMode="results",focusPanTarget(r,{keepBlockPosition:!0});else{state.pan.focusMode="tabs";const e=getPanTypeFromElement(r);e&&e!==state.pan.activeType&&selectPanType(e),focusPanTarget(r,{keepBlockPosition:!0})}return!0}function isPanFocusTarget(e){return!(!e||!($("panTabs")&&$("panTabs").contains(e)||$("panResultList")&&$("panResultList").contains(e)))}function panResultByColumn(e){const t=$("panResultList"),n=t?Array.from(t.querySelectorAll(".pan-result-item")).filter(isVisibleFocusable):[];if(!n.length)return null;const a=center(e.getBoundingClientRect());let i=null,s=1/0;for(const e of n.slice(0,5)){const t=center(e.getBoundingClientRect());if(t.y<a.y-4)continue;const n=1.15*Math.abs(t.x-a.x)+.35*Math.max(0,t.y-a.y);n<s&&(i=e,s=n)}return i||n[0]}function handleDetailDirectionalKey(e,t){const n=$("detailSheet"),a=document.activeElement;if(!(n&&n.classList.contains("active")&&a&&n.contains(a)))return!1;if(isPanSearchActive()&&isPanFocusTarget(a))return!1;const i=detailFocusBlock(a);if(!i)return!1;let s=null;return s="ArrowLeft"===e||"ArrowRight"===e?detailHorizontalTarget(i,a,"ArrowRight"===e?1:-1):detailVerticalTarget(i,a,"ArrowDown"===e?1:-1),!!s&&(t.preventDefault(),t.stopPropagation(),state.pan.focusMode="",prepareEpisodeFocusFromBelow(i,s)?(requestAnimationFrame(()=>focusEpisodeReturnTarget(s)),!0):(focusRemoteTarget(s),!0))}function prepareEpisodeFocusFromBelow(e,t){const n=$("detailSheet"),a=$("episodeRail");return!!(n&&a&&t&&a.contains(t))&&(!(!e||["seasonBlock","detailActions","detailInfo"].includes(e.id))&&(positionEpisodeRailAtViewportBottom(t),!0))}function positionEpisodeRailAtViewportBottom(e){const t=$("detailSheet");if(!t||!e||!e.getBoundingClientRect)return;const n=t.getBoundingClientRect?t.getBoundingClientRect():{top:0,bottom:window.innerHeight||0},a=e.getBoundingClientRect(),i=t.clientHeight||window.innerHeight||0,s=Math.max(34,Math.round(.08*i)),o=n.top+i-s,r=a.bottom-o;Math.abs(r)<2||(t.scrollTop+=r)}function focusEpisodeReturnTarget(e){if(e){try{e.focus({preventScroll:!0})}catch(t){e.focus()}keepEpisodeCardHorizontallyVisible(e)}}function keepEpisodeCardHorizontallyVisible(e){const t=$("episodeRail");if(!(t&&e&&t.contains(e)&&e.getBoundingClientRect))return;const n=e.getBoundingClientRect(),a=t.getBoundingClientRect(),i=n.left-a.left-8,s=n.right-a.right+8;i<0?t.scrollLeft+=i:s>0&&(t.scrollLeft+=s)}function detailFocusBlock(e){if(e===$("detailMoreBtn"))return{id:"detailInfo",root:e.closest(".detail-info")};if(e===$("detailContinueBtn")||e===$("detailSearchBtn")||e===$("panSearchBtn"))return{id:"detailActions",root:e.closest(".actions")};const t=["panSearchBlock","seasonBlock","castBlock","personWorkBlock","recommendBlock"];for(const n of t){const t=$(n);if(t&&t.contains(e))return{id:n,root:t}}return null}function detailBlockOrder(){const e=[],t=$("detailMoreBtn")&&$("detailMoreBtn").closest(".detail-info");t&&detailBlockFocusables(t).length&&e.push({id:"detailInfo",root:t});const n=$("detailSearchBtn")&&$("detailSearchBtn").closest(".actions");return n&&detailBlockFocusables(n).length&&e.push({id:"detailActions",root:n}),["panSearchBlock","seasonBlock","castBlock","personWorkBlock","recommendBlock"].forEach(t=>{const n=$(t);n&&"none"!==n.style.display&&"true"!==n.getAttribute("aria-hidden")&&detailBlockFocusables(n).length&&e.push({id:t,root:n})}),e}function detailVerticalTarget(e,t,n){const a="seasonBlock"===e.id?detailSeasonVerticalTarget(t,n):null;if(a)return a;const i=detailBlockOrder(),s=i.findIndex(t=>t.id===e.id);if(s<0)return null;const o=n>0?i.slice(s+1):i.slice(0,s).reverse();for(const e of o){const a="seasonBlock"===e.id&&n>0&&lastEpisodeFocusTarget()||detailClosestInBlock(e.root,t,n);if(a)return a}return null}function detailHorizontalTarget(e,t,n){const a=detailEpisodeHorizontalTarget(t,n);if(a)return a;const i=detailBlockFocusables(t&&t.closest&&t.closest("#seasonTabs, #episodeRail, #castRail, #personWorkRail, #recommendWorkRail, #panTabs, .actions")||e.root),s=i.indexOf(t);return s<0?null:i[s+n]||null}function detailEpisodeHorizontalTarget(e,t){const n=$("episodeRail");if(!n||!e||!n.contains(e))return null;const a=state.episodeViewer.episodes||[];if(a.length<=1)return null;const i=e.dataset&&e.dataset.episodeNumber||state.episodeViewer.episodeNumber||"",s=i?a.findIndex(e=>String(e&&e.episode_number||"")===i):Number(state.episodeViewer.index||0),o=(state.episodeViewer.effectiveIndexes||[]).filter(e=>e>=0&&e<a.length),r=o.length?o:a.map((e,t)=>t);if(r.length<=1)return null;let c=r.indexOf(s);c<0&&(c=t>0?-1:0);const l=(c+(t>0?1:-1)+r.length)%r.length,d=a[r[l]],u=d?findByDataset(n,"episodeNumber",String(d.episode_number||"")):null;return isVisibleFocusable(u)?u:null}function detailSeasonVerticalTarget(e,t){const n=$("seasonTabs"),a=$("episodeRail");if(n&&n.contains(e))return t<0?null:lastEpisodeFocusTarget()||detailClosestInBlock(a,e,t);if(a&&a.contains(e)){if(t>0)return null;state.episodePreview&&state.episodePreview.active&&(clearInlineEpisodePreview({restoreDetail:!0}),ensureDefaultDetailHeaderVisible());const a=detailClosestInBlock(n,e,t);return a||(detailPrimaryActionButton()||$("panSearchBtn"))}return null}function ensureDefaultDetailHeaderVisible(){const e=$("detailSheet"),t=$("detailTitle")&&$("detailTitle").closest(".detail-info"),n=$("detailText");if(!(e&&t&&n&&e.classList.contains("active")))return;const a=parseFloat(getComputedStyle(n).lineHeight||"28")||28,i=Math.round(3.2*a);n.style.setProperty("--detail-text-max",`${i}px`),n.classList.add("clamped"),$("detailMoreBtn")&&($("detailMoreBtn").dataset.expanded="",$("detailMoreBtn").style.display="inline-flex",$("detailMoreBtn").textContent="更多"),requestAnimationFrame(()=>{const n=e.getBoundingClientRect?e.getBoundingClientRect():{top:0},a=t.getBoundingClientRect?t.getBoundingClientRect():null;if(!a)return;const i=n.top+42;(a.top<i||a.top>i+24)&&(e.scrollTop+=a.top-i)})}function detailClosestInBlock(e,t,n){const a=detailBlockFocusables(e);if(!a.length)return null;if(!t||!t.getBoundingClientRect)return n>0?a[0]:a[a.length-1];const i=center(t.getBoundingClientRect());let s=null,o=1/0;for(const e of a){const t=e.getBoundingClientRect(),a=center(t),r=1.1*Math.max(0,n>0?t.top-i.y:i.y-t.bottom)+1.5*Math.abs(a.x-i.x);r<o&&(s=e,o=r)}return s||(n>0?a[0]:a[a.length-1])}function detailBlockFocusables(e){return e?e.matches&&e.matches(".focusable,button,input,textarea")?isVisibleFocusable(e)?[e]:[]:Array.from(e.querySelectorAll(".focusable,button,input,textarea")).filter(isVisibleFocusable):[]}function isFirstVisiblePanResult(e){const t=$("panResultList");if(!t||!t.contains(e))return!1;let n=t.firstElementChild;for(;n;){if(n.classList&&n.classList.contains("pan-result-item")&&isVisibleFocusable(n))return n===e;n=n.nextElementSibling}return!1}function siblingFocusable(e,t,n){if(!e||!t)return null;if("panResultList"===e.id&&t.classList&&t.classList.contains("pan-result-item")){let e=n>0?t.nextElementSibling:t.previousElementSibling;for(;e;){if(e.classList&&e.classList.contains("pan-result-item")&&isVisibleFocusable(e))return e;e=n>0?e.nextElementSibling:e.previousElementSibling}return null}const a=Array.from(e.querySelectorAll(".focusable,button,input,textarea")).filter(isVisibleFocusable),i=a.indexOf(t);return i<0?null:a[i+n]||null}function normalizeRemoteKey(e){if(["Enter","Escape","Backspace","BrowserBack","GoBack","ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(e.key))return"BrowserBack"===e.key||"GoBack"===e.key?"Escape":e.key;return{13:"Enter",23:"Enter",66:"Enter",4:"Escape",8:"Backspace",27:"Escape",10009:"Escape",461:"Escape",19:"ArrowUp",20:"ArrowDown",21:"ArrowLeft",22:"ArrowRight"}[e.keyCode||e.which]||""}function shouldThrottleRemoteNav(e,t,n){if(!isTvMode()||!["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(e))return!1;if(focusScopeRoot()!==document||isConnectionPanelOpen()||isSearchSuggestOpen())return!1;if($("searchForm")&&n&&$("searchForm").contains(n))return!1;const a=window.performance&&performance.now?performance.now():Date.now(),i=state.remoteKeyGate||{key:"",at:0},s=i.key===e?56:38;return!!(i.at&&a-i.at<s)||(state.remoteKeyGate={key:e,at:a},!1)}function fastHomeDirectionalTarget(e,t){return!isTvMode()||focusScopeRoot()!==document||isConnectionPanelOpen()||isSearchSuggestOpen()?null:t&&["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(e)?isTextEditingElement(t)||$("connectionDock")&&$("connectionDock").contains(t)||$("searchForm")&&$("searchForm").contains(t)?null:fastHomeSearchControlTarget(e,t)||fastHomeChipTarget(e,t)||fastHomeGridTarget(e,t)||fastHomeSearchRailTarget(e,t):null}function fastHomeChipTarget(e,t){const n=$("chips");return n&&n.contains(t)?"ArrowLeft"===e||"ArrowRight"===e?fastHomeSibling(n,t,"ArrowRight"===e?1:-1,".chip"):"ArrowDown"===e&&t===activeHomeChip()?searchReturnCard(t)||firstActiveGridCard():null:null}function fastHomeGridTarget(e,t){const n=t&&t.classList&&t.classList.contains("card")?t:null,a=n&&n.closest&&n.closest(".media-grid");if(!a||a.closest&&a.closest(".list-panel[hidden]"))return null;if(a!==activeMediaGrid())return null;let i=Number(n.dataset.cardIndex||-1);if((!Number.isFinite(i)||i<0)&&(i=Array.prototype.indexOf.call(a.children,n)),i<0)return null;const s=Math.max(1,gridColumns(a)),o=a.children.length;let r=-1;if("ArrowLeft"===e&&i%s>0)r=i-1;else if("ArrowRight"===e&&i%s<s-1)r=i+1;else if("ArrowUp"===e){if(r=i-s,r<0)return searchResultCardNear(n)||activeHomeChip()}else"ArrowDown"===e&&(r=i+s);return r>=0&&r<o?homeGridCardAt(a,r):"ArrowDown"===e&&r>=o&&appendGridBatch(a)?(observeInfiniteScroll(),homeGridCardAt(a,r)):null}function fastHomeSearchRailTarget(e,t){const n=t&&t.closest&&t.closest("#searchRail");if(!n||!n.contains(t))return null;if("ArrowLeft"===e||"ArrowRight"===e)return fastHomeSibling(n,t,"ArrowRight"===e?1:-1,".card");if("ArrowUp"===e){const e=searchClearButton();return e?(state.searchReturnCard=t,e):activeHomeChip()}return"ArrowDown"===e?activeGridCardNear(t)||firstActiveGridCard():null}function fastHomeSearchControlTarget(e,t){return t!==searchClearButton()?null:"ArrowDown"===e?searchReturnCard(t)||firstActiveGridCard():"ArrowUp"===e?activeHomeChip():null}function homeGridCardAt(e,t){const n=e&&t>=0?e.children[t]:null;return n&&n.classList&&n.classList.contains("card")&&canFastHomeFocus(n)?n:null}function fastHomeSibling(e,t,n,a){let i=n>0?t.nextElementSibling:t.previousElementSibling;for(;i&&e.contains(i);){if(i.matches&&i.matches(a)&&canFastHomeFocus(i))return i;i=n>0?i.nextElementSibling:i.previousElementSibling}return null}function canFastHomeFocus(e){return!(!(e&&e.matches&&e.matches(".focusable,button,input,textarea"))||e.disabled||"-1"===e.getAttribute("tabindex")||e.hidden||e.closest("[hidden]")||e.closest('[aria-hidden="true"]'))}function focusRemoteTarget(e){if(e){try{e.focus({preventScroll:!0})}catch(t){e.focus()}maybeAppendGridForFocus(e),scheduleFocusInView(e),e&&e.closest&&e.closest("#recommendRail")&&scheduleAutoBlockViewportScan(220)}}function scheduleFocusInView(e){state.blocked.restoring||"home"===uiSnapshotRoute()&&e&&e.closest&&e.closest("#chips")&&homeScrollTop()>8||(state.focusScrollTarget=e,state.focusScrollTimer||(state.focusScrollTimer=requestAnimationFrame(()=>{const e=state.focusScrollTarget;state.focusScrollTimer=0,state.focusScrollTarget=null,e&&e.isConnected&&keepFocusInView(e)})))}function keepFocusInView(e){if(state.blocked.restoring)return;if("home"===uiSnapshotRoute()&&e&&e.closest&&e.closest("#chips")&&homeScrollTop()>8)return;if(!e)return;const t=e.getBoundingClientRect(),n=window.innerHeight||document.documentElement.clientHeight||0,a=window.innerWidth||document.documentElement.clientWidth||0;if(n&&a&&!(t.top>=54&&t.bottom<=n-54&&t.left>=8&&t.right<=a-8))try{e.scrollIntoView({block:"nearest",inline:"nearest"})}catch(t){e.scrollIntoView(!1)}}function isVisibleFocusable(e){if(!e||!e.matches||!e.matches(".focusable,button,input,textarea"))return!1;if(e.disabled||"-1"===e.getAttribute("tabindex")||e.closest('[aria-hidden="true"]'))return!1;const t=window.getComputedStyle?window.getComputedStyle(e):null;return(!t||"hidden"!==t.visibility&&"none"!==t.display&&"none"!==t.pointerEvents)&&!(null===e.offsetParent&&!e.getClientRects().length)}function rememberFocusReturn(){const e=document.activeElement;isVisibleFocusable(e)&&(state.focusReturnEl=e)}function restoreFocusReturn(e){const t=isVisibleFocusable(state.focusReturnEl)?state.focusReturnEl:e||firstContentFocus();state.focusReturnEl=null,t&&requestAnimationFrame(()=>focusRemoteTarget(t))}function visibleFocusable(){const e=focusScopeRoot();return Array.from(e.querySelectorAll(".focusable,button,input,textarea")).filter(isVisibleFocusable)}function focusScopeRoot(){return $("imageViewer")&&$("imageViewer").classList.contains("active")?$("imageViewer"):$("syncSheet")&&$("syncSheet").classList.contains("active")?$("syncSheet"):$("detailSheet")&&$("detailSheet").classList.contains("active")?$("detailSheet"):document}function nearestFocusable(e,t){const n=document.activeElement,a=t||(isVisibleFocusable(n)?n:null);if("ArrowDown"===e&&a&&a.closest&&a.closest("#chips")&&a===activeHomeChip()){const e=searchReturnCard(a)||firstActiveGridCard();if(e)return e}if("ArrowUp"===e&&a&&a.classList&&a.classList.contains("card")){const e=a.closest&&a.closest(".media-grid");if(e&&e===activeMediaGrid()){let t=Number(a.dataset.cardIndex||-1);if((!Number.isFinite(t)||t<0)&&(t=Array.prototype.indexOf.call(e.children,a)),t>=0&&t<gridColumns(e))return searchResultCardNear(a)||activeHomeChip()}}const i=visibleFocusable();if(!i.length)return null;if(!a)return firstContentFocus()||i[0];const s=center(a.getBoundingClientRect()),o="ArrowUp"===e||"ArrowDown"===e,r="ArrowRight"===e||"ArrowDown"===e;let c=null,l=1/0;for(const e of i){if(e===a)continue;const t=center(e.getBoundingClientRect()),n=o?t.y-s.y:t.x-s.x,i=o?Math.abs(t.x-s.x):Math.abs(t.y-s.y);if(r?n<=4:n>=-4)continue;const d=1.25*Math.abs(n)+1.9*i;d<l&&(c=e,l=d)}return c}function firstContentFocus(){const e=focusScopeRoot(),t=["#chips .chip.active","#chips .chip","#recommendRail .card","#listStack .card","#searchRail .card",".focusable:not(#searchInput)"];for(const n of t){const t=Array.from(e.querySelectorAll(n)).find(isVisibleFocusable);if(t)return t}return null}function center(e){return{x:e.left+e.width/2,y:e.top+e.height/2}}function uiSnapshotRoute(){return $("imageViewer")&&$("imageViewer").classList.contains("active")?"image":$("syncSheet")&&$("syncSheet").classList.contains("active")?"sync":$("detailSheet")&&$("detailSheet").classList.contains("active")?"detail":"home"}function compactPanResults(e){return(e||[]).slice(0,400).map(e=>({key:e.key,diskType:e.diskType,url:e.url,normalizedUrl:e.normalizedUrl||"",password:e.password||"",title:e.title||"",source:e.source||"",datetime:e.datetime||"",index:e.index||0}))}function buildUiSnapshot(){const e=$("panResultList"),t=$("detailSheet");return{version:1,savedAt:Date.now(),route:uiSnapshotRoute(),hash:location.hash||"",activeList:state.activeList,scrollY:Math.round(window.scrollY||document.documentElement.scrollTop||document.body.scrollTop||0),connectionOpen:!(!$("connectionDock")||!$("connectionDock").classList.contains("open")),selected:state.selected?normalizeSnapshot(state.selected):null,detailScrollTop:t?Math.round(t.scrollTop||0):0,imageUrl:$("viewerImage")&&"none"!==$("viewerImage").style.display&&$("viewerImage").getAttribute("src")||"",detailReturn:state.detailReturn||null,homeReturn:state.homeReturn||null,pan:{visible:!(!$("panSearchBlock")||!$("panSearchBlock").classList.contains("active")),keyword:state.pan.keyword||"",activeType:state.pan.activeType||"",results:compactPanResults(state.pan.results),health:state.pan.health||{},listScrollTop:e?Math.round(e.scrollTop||0):0,focusKey:state.pan.focusKey||"",focusMode:state.pan.focusMode||"",playbackReturn:state.pan.playbackReturn||null}}}function scheduleUiSnapshotSave(){clearTimeout(scheduleUiSnapshotSave.timer),scheduleUiSnapshotSave.timer=setTimeout(saveUiSnapshotNow,260)}async function saveUiSnapshotNow(){try{await sdk().cache.set(cacheKey("ui"),JSON.stringify(buildUiSnapshot()))}catch(e){}}async function readUiSnapshot(){try{const e=safeJson(await sdk().cache.get(cacheKey("ui")),null);return e&&1===e.version?Date.now()-Number(e.savedAt||0)>432e5?null:e:null}catch(e){return null}}function shouldRestoreUiSnapshot(){try{return"1"===new URLSearchParams(location.search||"").get("_fm_restore")}catch(e){return/(?:^|[?&])_fm_restore=1(?:&|$)/.test(location.search||"")}}function restorePanSnapshot(e){e&&(e.keyword||(e.results||[]).length)&&(state.pan.loading=!1,state.pan.keyword=e.keyword||"",state.pan.activeType=e.activeType||"",state.pan.results=Array.isArray(e.results)?e.results.map((e,t)=>Object.assign({index:t},e)):[],state.pan.health=e.health&&"object"==typeof e.health?e.health:{},state.pan.focusKey=e.focusKey||"",state.pan.focusMode=e.focusMode||"",state.pan.playbackReturn=e.playbackReturn||null,state.pan.pending={},state.pan.queued.clear(),state.pan.inFlight.clear(),state.pan.renderKeys="",state.pan.viewToken=`restore-${Date.now()}`,$("panSearchBlock")&&($("panSearchBlock").classList.add("active"),$("panSearchBlock").style.display=""),renderPanResults(),updatePostPanFocusState(),requestAnimationFrame(()=>{$("panResultList")&&($("panResultList").scrollTop=Number(e.listScrollTop||0))}))}function restoreSearchSnapshot(){$("searchInput")&&($("searchInput").value=""),state.searchItems=[],hideSearchSuggest(),renderSearch()}async function restoreUiSnapshot(e){return!!e&&(state.detailReturn=e.detailReturn||null,state.homeReturn=e.homeReturn||null,restoreSearchSnapshot(e.search),e.activeList&&(state.activeList=e.activeList),normalizeActiveListForViewport(),renderAll({deferContent:"home"===e.route}),e.connectionOpen&&$("connectionDock")&&$("connectionBody")&&($("connectionDock").classList.add("open"),$("connectionBody").classList.add("open"),fitConnectionPanel()),"detail"!==e.route&&"image"!==e.route||!e.selected?"sync"===e.route?(history.replaceState({sheet:"sync"},"","#sync"),openSync({restore:!0,skipHistory:!0})):requestAnimationFrame(()=>window.scrollTo(0,Number(e.scrollY||0))):("#detail"!==location.hash&&"detail"===e.route&&history.replaceState({sheet:"detail"},"","#detail"),openDetail(e.selected,{restore:!0,skipHistory:!0}),restorePanSnapshot(e.pan),requestAnimationFrame(()=>{$("detailSheet")&&($("detailSheet").scrollTop=Number(e.detailScrollTop||0))}),"image"===e.route&&e.imageUrl&&(history.replaceState({sheet:"image"},"","#image"),openImage(e.imageUrl,{restore:!0,skipHistory:!0}))),!0)}function scheduleWebHomeResume(e){const t=e||{};clearTimeout(state.resume.timer),state.resume.timer=setTimeout(()=>handleWebHomeResume(t),null==t.delay?80:t.delay)}function handleWebHomeResume(e){const t=e||{},n=Date.now();if(!t.force&&n-Number(state.resume.lastAt||0)<650)return;state.resume.lastAt=n;const a=!!(state.pan.playbackReturn&&$("detailSheet")&&$("detailSheet").classList.contains("active")&&$("panSearchBlock")&&$("panSearchBlock").classList.contains("active"));if(lockViewportWidth(),fitConnectionPanel(),renderConnection(),a||($("detailSheet")&&$("detailSheet").classList.contains("active")&&state.selected&&refreshActiveDetailView(),$("panSearchBlock")&&$("panSearchBlock").classList.contains("active")&&renderPanResults(),renderAll({deferContent:"home"===uiSnapshotRoute()}),normalizeRails()),restorePanPlaybackReturn({skipRender:a})||restoreDetailReturn(),updateBackTopButton(),scheduleHistorySettlement(),loadRecentList({refresh:!0,silent:!0}).catch(()=>{}),sampleWatchStatus(),!a){const e=$("home");e&&(e.style.transform="translateZ(0)",requestAnimationFrame(()=>e.style.transform=""))}scheduleUiSnapshotSave()}function refreshActiveDetailView(){if(state.episodePreview&&state.episodePreview.active&&clearInlineEpisodePreview({restoreDetail:!1}),!state.detail||!state.selected)return state.detailCover.images&&state.detailCover.images.length?(updateDetailCoverControls(),void syncDetailCoverFrame($("detailImage"))):void renderDetailBase(state.selected);renderDetailExtras(state.selected,state.detail)}function safeJson(e,t){try{return JSON.parse(e||"")}catch(e){return t}}function escapeHtml(e){return String(e||"").replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"}[e]))}function escapeAttr(e){return escapeHtml(e).replace(/`/g,"`")}function shortKey(e){return e?e.length>14?e.slice(0,8)+"..."+e.slice(-4):e:""}function toast(e){const t=$("toast");t.textContent=e||"",t.classList.add("show"),clearTimeout(toast.timer),toast.timer=setTimeout(()=>t.classList.remove("show"),2200)}function updateBackTopButton(){const e=window.scrollY||document.documentElement.scrollTop||document.body.scrollTop||0;$("backTopBtn").classList.toggle("show",e>window.innerHeight)}function updateMobileDetailBackButton(){const e=$("detailSheet"),t=$("mobileDetailBackBtn");if(!e||!t)return;const n=document.documentElement.classList.contains("native-phone-app")&&e.classList.contains("active")&&!e.classList.contains("detail-large")&&e.scrollTop>120;t.classList.toggle("is-hidden",n)}function lockViewportWidth(){const e=Math.floor(window.innerWidth||document.documentElement.clientWidth||0);e&&(document.documentElement.style.width=e+"px",document.body.style.width=e+"px",document.body.style.maxWidth=e+"px")}async function boot(){lockViewportWidth(),refreshSafeAreaMode(),bindActions(),installRemoteKeys(),await initTmdbConfig(),await initPanConfig(),await initUiPrefs({timeout:0}),setupRelayMirrorDefaults(),await loadBlockedRecommend(),await loadAutoBlockedMedia(),renderConnection(),armFallbackTimers(),hotLoadIndex().catch(()=>{}),await loadInfo(),await loadCatalog();const e=shouldRestoreUiSnapshot(),t=!!e&&await restoreUiSnapshot(await readUiSnapshot());await ensureIdentity(),await loadEvents(),scheduleHistorySettlement(),setTimeout(subscribeNostr,600),renderMetrics(),t&&scheduleWebHomeResume({force:!0}),e||scheduleUiSnapshotSave(),updateBackTopButton(),setTimeout("home"===uiSnapshotRoute()?focusInitialHomeNow:ensureRemoteInitialFocus,80),"home"===uiSnapshotRoute()&&setTimeout(focusInitialHomeNow,260)}window.addEventListener("popstate",()=>{if("#detail"!==location.hash&&$("detailSheet").classList.contains("active")&&"results"===state.pan.focusMode)return history.pushState({sheet:"detail"},"","#detail"),void focusPanTabFromResults();"#image"!==location.hash&&$("imageViewer").classList.contains("active")&&closeImage(!0),"#detail"!==location.hash&&$("detailSheet").classList.contains("active")&&closeDetail(!0),"#sync"!==location.hash&&$("syncSheet").classList.contains("active")&&closeSync(!0)}),window.addEventListener("fmviewport",e=>{updateSafeAreaMode(e&&e.detail?e.detail:{}),state.gridColumnCache={},syncClientModeClasses(),document.body.style.minHeight=getComputedStyle(document.documentElement).getPropertyValue("--fm-web-height"),lockViewportWidth(),fitConnectionPanel();syncDetailLayout()&&$("detailSheet")&&$("detailSheet").classList.contains("active")&&state.selected&&refreshActiveDetailView(),renderAll({deferContent:"home"===uiSnapshotRoute()}),scheduleDetailTextClamp(),scheduleHistorySettlement()}),window.addEventListener("resize",()=>{state.gridColumnCache={},syncClientModeClasses(),lockViewportWidth(),fitConnectionPanel();syncDetailLayout()&&$("detailSheet")&&$("detailSheet").classList.contains("active")&&state.selected&&refreshActiveDetailView(),renderAll({deferContent:"home"===uiSnapshotRoute()}),scheduleDetailTextClamp()}),window.addEventListener("scroll",()=>{if(state.scrollingUntil=Date.now()+900,homeScrollTop()>8&&(state.remoteInitialFocused=!0),updateBackTopButton(),scheduleUiSnapshotSave(),scheduleAutoBlockViewportScan(950),"IntersectionObserver"in window)return;const e=document.documentElement;(window.scrollY||e.scrollTop||0)+window.innerHeight<e.scrollHeight-900||(clearTimeout(state.scrollLoadTimer),state.scrollLoadTimer=setTimeout(loadMoreVisible,80))},{passive:!0}),window.addEventListener("pagehide",()=>{saveUiSnapshotNow(),clearRelayBackfillTimers(),pauseDetailCoverCarousel(),stopWatchTracking(!0)}),window.addEventListener("pageshow",()=>scheduleWebHomeResume()),window.addEventListener("fmsdk",()=>{syncClientModeClasses(),refreshSafeAreaMode(),Promise.all([initUiPrefs({timeout:0}),initTmdbConfig({preserveDirty:!0,timeout:0}),initPanConfig({preserveDirty:!0,timeout:0})]).then(loadInfo).then(()=>scheduleWebHomeResume({force:!0})).catch(()=>{})}),window.addEventListener("fmresume",()=>{refreshSafeAreaMode(),loadInfo().finally(()=>scheduleWebHomeResume())}),window.addEventListener("fmpause",saveUiSnapshotNow),document.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState&&(saveUiSnapshotNow(),state.detailCover.swipe=null,pauseDetailCoverCarousel()),"visible"===document.visibilityState&&(restartDetailCoverCarousel(),updateDetailCoverControls(),syncDetailCoverFrame($("detailImage")),scheduleWebHomeResume())}),boot()
|
||
</script></body></html> |