// ==UserScript==
// @name xhamster-优化
// @version 1.0.0
// @namespace https://sleazyfork.org/zh-CN/users/1461640-%E6%98%9F%E5%AE%BF%E8%80%81%E9%AD%94
// @author 星宿老魔
// @description 自动宽屏,自动最高画质,自动播放,隐藏已观看,收藏夹内视频快速移除。
// @match https://zh.xhamster.com/*
// @match https://xhamster.com/*
// @icon https://www.google.com/s2/favicons?sz=64&domain=xhamster.com
// @license MIT
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_registerMenuCommand
// @grant GM_addStyle
// @grant GM_deleteValue
// ==/UserScript==
(function(){"use strict";const s={name:"xhamster-优化",version:"0.4.3",description:"自动宽屏,自动最高画质,自动播放,隐藏已观看,收藏夹内视频快速移除",domains:["zh.xhamster.com","xhamster.com"],pageTypes:{search:"/search/",category:"/categories/",tags:"/tags/",video:"/videos/",excludedPrefixes:["/photos/","/users/","/my/","/messages","/live","/creators","/p/","/info"]},selectors:{playButton:".play-inner",settingsButton:".settings",qualityOptions:".xp-settings-inner-list span[data-value]",menuContainer:".items-3b1bc",menuContainerAlt:".container-3b1bc",moreButton:".dropdown-3b1bc",menuItem:".container-64b3c",menuLink:".root-48288.invert-48288.link-64b3c",menuText:".h4-8643e.invert-8643e.linkText-64b3c",videoItems:".thumb-list__item.video-thumb",watchedIndicator:".thumb-image-container__watched",hiddenByScript:".hidden-by-script",adContainers:".thumbContainer-53a78, .thumb-53a78",redirectLinks:'a[href*="/fh/out?url="]',badges:".badge-cb84e, .badge",favoriteVideos:".video-thumb[data-video-id]",removeButton:".remove-btn",imageContainer:".thumb-image-container",commentTabSet:".tabSet-792ed.tabSet-0c900",commentNoTabSet:".noTabs-0c900",commentBox:"#commentBox, .commentsWrap-99011",commentTab:".tab-98bb0",commentCount:".comments-heading .value-42516, .triggerBlock-42516 .value-42516",commentItems:".commentItem-5228f",commentForm:".form-42516",commentInput:".root-77ac5.desktop-77ac5",commentPagination:".pagerSection-99011, .pager-section",relatedTabTitle:".relatedTabTitleDesktop-0c900",showMoreButton:'.container-90841.desktop-90841[data-role="show-more-container"]',topMenuAds:['[data-nav-item-id="cams"]','[data-nav-item-id="dating"]','[data-nav-item-id="priority-vpn"]','[data-nav-item-id="ai-friend"]','[data-nav-item-id="flirtify"]','[data-item="premium"]']},qualityOrder:["2160p","1080p","720p","480p","240p","144p"],adKeywords:["已支付","付费","PAID","Premium","24/7不间断直播","约会","Free VPN","AI Girlfriend","性爱聊天","独家视频"],adLinkPatterns:["/cam/out","/dating","/fh/out","/ff/out","priorityvpn.app","lovescape.com"],performance:{debounceDelay:300,retryLimit:20,retryInterval:500,cleanupInterval:5e3}};class C{static init(){try{this.maintainWideScreen(),this.clickPlayButton()||this.waitForElement(".play-inner",()=>this.clickPlayButton()),this.setHighestQuality()||this.waitForElement(".settings",()=>this.setHighestQuality())}catch(e){console.error(`[${s.name}] 视频增强失败:`,e)}}static maintainWideScreen(){const e=()=>{if(typeof window.togglePlayerSize=="function")try{return window.togglePlayerSize(),console.log("✅ 自动宽屏已启用"),!0}catch(n){return console.warn("❌ 宽屏切换失败:",n),!1}else return!1},t=document.querySelector(".large-mode");if(t){t.click(),console.log("✅ 自动宽屏");return}e()||setTimeout(()=>{e()||this.tryManualWideScreen()},1e3)}static tryManualWideScreen(){const e=[".large-mode",".xp-fullscreen",".fullscreen-btn",".theater-mode",".wide-screen",'[title*="全屏"]','[title*="宽屏"]','[title*="Theater"]','[title*="Wide"]','[title*="Large"]','[data-xp-tooltip*="Large"]',".xp-theater",".player-controls .fullscreen",".video-controls .fullscreen"];for(const t of e){const n=document.querySelector(t);if(n)try{n.click(),console.log("✅ 自动宽屏");return}catch{}}this.waitForElement(".xplayer, .player, .video-player",()=>{setTimeout(()=>{for(const t of e){const n=document.querySelector(t);if(n){n.click(),console.log("✅ 自动宽屏");return}}},2e3)})}static clickPlayButton(){const e=document.querySelector(".play-inner");return e?(e.click(),console.log("✅ 自动播放"),!0):!1}static setHighestQuality(){const e=document.querySelector(".settings");if(e){e.click(),console.log("✅ 点击设置按钮");const t=["2160p","1080p","720p","480p","240p","144p"],n=()=>{for(const o of t){const i=document.querySelector(`.xp-settings-inner-list span[data-value="${o}"]`);if(i)return i.click(),console.log(`✅ 自动选择画质: ${o}`),!0}return!1};if(!n()){const o=new MutationObserver((i,a)=>{n()&&a.disconnect()});o.observe(document.body,{childList:!0,subtree:!0}),setTimeout(()=>o.disconnect(),1e4)}return!0}return!1}static waitForElement(e,t){if(document.querySelector(e)){t();return}new MutationObserver((i,a)=>{document.querySelector(e)&&(t(),a.disconnect())}).observe(document.body,{childList:!0,subtree:!0})}}class f{static getGlobalHideWatchedSetting(){return GM_getValue("hideWatched_global",!1)}static setGlobalHideWatchedSetting(e){GM_setValue("hideWatched_global",e)}static cleanupOldSettings(){["hideWatched_home","hideWatched_search","hideWatched_category","hideWatched_tags","hideWatched_video"].forEach(t=>{GM_getValue(t,null)!==null&&(GM_deleteValue(t),console.log(`🧹 清理旧设置: ${t}`))})}}class l{static init(){console.log(`[${s.name}] 初始化内容过滤功能...`),this.addFilterStyles(),this.removeTopMenuAds(),this.removeVideoAds(),this.applyWatchedVideoFilter(),console.log(`[${s.name}] 内容过滤功能初始化完成`)}static addFilterStyles(){if(typeof GM_addStyle<"u")GM_addStyle(`
.hidden-by-script { display: none !important; }
.menu-ad-hidden { display: none !important; }
`),console.log("✅ 过滤样式已添加");else{console.warn("⚠️ GM_addStyle 不可用,使用备用方式添加样式");const e=document.createElement("style");e.textContent=`
.hidden-by-script { display: none !important; }
.menu-ad-hidden { display: none !important; }
`,document.head.appendChild(e)}}static removeTopMenuAds(){try{const e=['[data-nav-item-id="cams"]','[data-nav-item-id="dating"]','[data-nav-item-id="priority-vpn"]','[data-nav-item-id="ai-friend"]','[data-nav-item-id="flirtify"]','[data-item="premium"]'];let t=0;e.forEach(i=>{document.querySelectorAll(i).forEach(r=>{r&&r.parentNode&&(r.classList.add("menu-ad-hidden"),t++)})});const n=["24/7不间断直播","约会","Free VPN","AI Girlfriend","性爱聊天","独家视频"];return document.querySelectorAll(".container-64b3c").forEach(i=>{const a=i.textContent?.trim();a&&n.some(r=>a.includes(r))&&(i.classList.contains("menu-ad-hidden")||(i.classList.add("menu-ad-hidden"),t++))}),t>0&&console.log(`🚫 已隐藏 ${t} 个顶部菜单广告项`),t}catch(e){return console.warn("移除顶部菜单广告时出错:",e),0}}static removeVideoAds(){let e=0;try{return document.querySelectorAll(".thumbContainer-53a78, .thumb-53a78").forEach(i=>{i&&i.parentNode&&(i.remove(),e++)}),document.querySelectorAll('a[href*="/fh/out?url="]').forEach(i=>{const a=i.closest(".thumb-list__item, .thumbContainer-53a78, .video-thumb");a&&a.parentNode&&(a.remove(),e++)}),document.querySelectorAll(".thumb-list__item .title, .thumb-list__item .caption, .thumbContainer-53a78 .title, .video-thumb .title").forEach(i=>{if(i.textContent&&(i.textContent.includes("已支付")||i.textContent.includes("付费")||i.textContent.includes("PAID")||i.textContent.includes("Premium"))){const a=i.closest(".thumb-list__item, .thumbContainer-53a78, .video-thumb");a&&a.parentNode&&(a.remove(),e++)}}),e>0&&console.log(`🚫 已移除 ${e} 个广告视频`),e}catch(t){return console.warn("移除视频广告时出错:",t),0}}static applyWatchedVideoFilter(){if(!(!this.shouldApplyHideWatchedFeature()||!f.getGlobalHideWatchedSetting()))try{const e=this.safeQuerySelectorAll(".thumb-list__item.video-thumb");console.log(`🔍 找到 ${e.length} 个视频项用于检查已观看状态`);let t=0;e.forEach(n=>{n&&this.safeQuerySelector(".thumb-image-container__watched",n)&&(n.classList.add("hidden-by-script"),t++)}),t>0&&console.log(`👁️ 已隐藏 ${t} 个已观看视频`)}catch(e){console.warn("隐藏已观看视频时出错:",e)}}static showWatchedVideos(){try{const e=this.safeQuerySelectorAll(".hidden-by-script");let t=0;e.forEach(n=>{n&&n.classList&&(n.classList.remove("hidden-by-script"),t++)}),t>0&&console.log(`👁️ 已显示 ${t} 个之前隐藏的视频`)}catch(e){console.warn("显示已观看视频时出错:",e)}}static shouldApplyHideWatchedFeature(){const e=window.location.pathname;return["/search/","/categories/","/tags/","/videos/"].some(o=>e.startsWith(o))?!0:!["/photos/","/users/","/my/","/messages","/live","/creators","/p/","/info"].some(o=>e.startsWith(o))}static toggleWatchedVideos(e){f.setGlobalHideWatchedSetting(!e),console.log(`🔄 切换已观看视频显示状态: ${e?"显示":"隐藏"} (全局生效)`),e?this.showWatchedVideos():this.applyWatchedVideoFilter()}static getCurrentHideWatchedSetting(){return f.getGlobalHideWatchedSetting()}static safeQuerySelector(e,t=document){try{return t.querySelector(e)}catch(n){return console.warn(`选择器查询失败: ${e}`,n),null}}static safeQuerySelectorAll(e,t=document){try{return t.querySelectorAll(e)}catch(n){return console.warn(`选择器查询失败: ${e}`,n),document.querySelectorAll("never-match")}}}class g{static init(){console.log(`[${s.name}] 初始化收藏管理功能...`),this.initRemoveFeature(),console.log(`[${s.name}] 收藏管理功能初始化完成`)}static addRemoveButtons(){if(!window.location.href.includes("watch-later")&&!window.location.href.includes("/my/favorites/videos"))return;if(!document.querySelector(".xh-icon")){setTimeout(()=>this.addRemoveButtons(),100);return}document.querySelectorAll(".video-thumb[data-video-id]").forEach(t=>{if(t.querySelector(".remove-btn"))return;const n=t.getAttribute("data-video-id");let o=null;if(window.location.href.includes("watch-later"))o=window.location.pathname.match(/\/videos\/([^-]+)-watch-later/)?.[1]||null;else if(window.location.href.includes("/my/favorites/videos")){const c=window.location.pathname.match(/\/videos\/([^\/]+)/);if(c)o=c[1];else{const h=document.querySelector(".favorites-collection.active, .active[data-id]");if(h)o=h.getAttribute("data-id");else{const d=t.closest(".favorites-collection, [data-collection-id]");d&&(o=d.getAttribute("data-collection-id")||d.getAttribute("data-id"))}}}if(!n||!o)return;const i=document.createElement("div");i.className="remove-btn",i.style.cssText=`
position: absolute;
top: 5px;
right: 5px;
width: 24px;
height: 24px;
background: rgba(0, 0, 0, 0.7);
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
z-index: 10;
transition: background 0.2s;
opacity: 1;
visibility: visible;
`;const a=document.createElement("i");a.className="xh-icon bucket cobalt",a.style.cssText="color: white; font-size: 12px; display: inline-block;",i.appendChild(a),i.addEventListener("mouseenter",()=>{i.style.background="rgba(255, 0, 0, 0.8)"}),i.addEventListener("mouseleave",()=>{i.style.background="rgba(0, 0, 0, 0.7)"}),i.addEventListener("click",c=>{c.preventDefault(),c.stopPropagation(),this.removeFromFavorites(n,o)});const r=t.querySelector(".thumb-image-container");r&&(r.style.position="relative",r.appendChild(i))})}static async removeFromFavorites(e,t){try{if((await fetch("/x-api",{method:"POST",headers:{"Content-Type":"text/plain","X-Requested-With":"XMLHttpRequest"},body:JSON.stringify([{name:"favoriteVideosModelSync",requestData:{model:{id:null,$id:this.generateUUID(),modelName:"favoriteVideosModel",itemState:"changed",collections:[],contentType:"videos",contentEntity:{id:e}}}}])})).ok){const o=document.querySelector(`[data-video-id="${e}"]`);o&&(o.remove(),console.log(`✅ 视频 ${e} 已从收藏列表中移除`))}else console.error("❌ 移除视频失败")}catch(n){console.error("❌ 移除视频时发生错误:",n)}}static generateUUID(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){const t=Math.random()*16|0;return(e=="x"?t:t&3|8).toString(16)})}static initRemoveFeature(){(window.location.href.includes("watch-later")||window.location.href.includes("/my/favorites/videos"))&&(document.readyState==="complete"?setTimeout(()=>this.addRemoveButtons(),500):window.addEventListener("load",()=>{setTimeout(()=>this.addRemoveButtons(),500)}))}}class v{static getCurrentPageType(){const e=window.location.pathname;return e.startsWith(s.pageTypes.search)?"search":e.startsWith(s.pageTypes.category)?"category":e.startsWith(s.pageTypes.tags)?"tags":e.startsWith(s.pageTypes.video)?"video":s.pageTypes.excludedPrefixes.some(n=>e.startsWith(n))?null:"home"}static shouldApplyHideWatchedFeature(){const e=window.location.pathname;return[s.pageTypes.search,s.pageTypes.category,s.pageTypes.tags,s.pageTypes.video].some(o=>e.startsWith(o))?!0:!s.pageTypes.excludedPrefixes.some(o=>e.startsWith(o))}static isInFavoritesPage(){const e=window.location.href;return e.includes("watch-later")||e.includes("/my/favorites/videos")}}const b=class b{static init(){console.log(`[${s.name}] 初始化评论标签管理功能...`),v.getCurrentPageType()==="video"&&this.addCommentTab(),console.log(`[${s.name}] 评论标签管理功能初始化完成`)}static addCommentTab(){if(this.hasCommentTabAdded)return;this.hideAllCommentBoxes();const e=document.querySelector(s.selectors.commentBox);if(!e){setTimeout(()=>this.addCommentTab(),1e3);return}this.originalCommentBox=e;const t=this.detectLayoutType();switch(t){case"tabSet":this.handleTabSetLayout();break;case"noTabs":this.handleNoTabsLayout();break;case"none":setTimeout(()=>this.addCommentTab(),1e3);return}this.hasCommentTabAdded=!0,console.log(`[${s.name}] 评论标签已添加,布局类型: ${t}`)}static hideAllCommentBoxes(){const e=document.querySelectorAll("#commentBox, .commentsWrap-99011");e.length>1&&(console.log(`[${s.name}] 发现 ${e.length} 个评论区域,将隐藏多余的`),e.forEach((n,o)=>{if(o>0){const i=n;i.style.display="none",console.log(`[${s.name}] 隐藏多余的评论区域[${o}]: ${i.id||i.className}`)}})),[".comments-section",".comment-wrapper",".commentSection"].forEach(n=>{const o=document.querySelectorAll(n);o.length>0&&o.forEach(i=>{const a=i;a.style.display="none",console.log(`[${s.name}] 隐藏其他评论区域: ${n}`)})})}static detectLayoutType(){return document.querySelector(s.selectors.commentTabSet)?"tabSet":document.querySelector(s.selectors.commentNoTabSet)?"noTabs":"none"}static handleTabSetLayout(){const e=document.querySelector(s.selectors.commentTabSet);if(!e||e.querySelector('[data-tab-type="comments"]'))return;const n=this.getCommentCount(),o=this.createCommentTab(n),i=e.querySelector(".after-792ed");i?e.insertBefore(o,i):e.appendChild(o),this.createCommentContentContainer(),this.bindCommentTabClick(o),this.observeOtherTabClicks()}static handleNoTabsLayout(){const e=document.querySelector(s.selectors.commentNoTabSet);if(!e||document.querySelector("#comment-section-enhanced"))return;const n=this.createTabSetContainer(),o=e.parentElement;o&&o.insertBefore(n,e.nextSibling);const i=this.getCommentCount(),a=this.createRelatedTab();n.appendChild(a);const r=this.createCommentTab(i),c=document.createElement("div");c.className="after-792ed",n.appendChild(r),n.appendChild(c),this.createRelatedContentContainer(e),this.createCommentContentContainer(),this.bindCommentTabClick(r),this.bindRelatedTabClick(a),this.toggleTabContent("related")}static createCommentTab(e){const t=document.createElement("div");t.className="tab-98bb0",t.setAttribute("data-tab-type","comments");const n=document.createElement("span");n.className="root-48288 unset-48288 link-a68d6";const o=document.createElement("div");return o.className="body-bold-8643e unset-8643e",o.textContent=e>0?`评论 (${e})`:"评论",n.appendChild(o),t.appendChild(n),t.style.cursor="pointer",t.addEventListener("mouseenter",()=>{t.classList.contains("selected-98bb0")||(n.style.opacity="0.8")}),t.addEventListener("mouseleave",()=>{n.style.opacity=""}),t}static getCommentCount(){const e=[".comments-heading .value-42516",".triggerBlock-42516 .value-42516",".commentTabs-42516 .value-42516"];for(const n of e){const o=document.querySelector(n);if(o){const i=parseInt(o.textContent?.trim()||"0",10);if(!isNaN(i))return i}}return document.querySelectorAll(".commentItem-5228f").length}static createCommentContentContainer(){const e=document.querySelector(s.selectors.commentTabSet)||document.querySelector("#comment-section-enhanced");if(!e||!this.originalCommentBox)return;this.commentContentContainer=document.createElement("div"),this.commentContentContainer.id="comment-tab-content",this.commentContentContainer.style.cssText=`
display: none;
margin-top: 20px;
`,this.reorganizeCommentContent(),this.rebindCommentEvents();const t=e.parentElement;if(t){const n=e.nextElementSibling;n?t.insertBefore(this.commentContentContainer,n):t.appendChild(this.commentContentContainer)}}static reorganizeCommentContent(){!this.originalCommentBox||!this.commentContentContainer||(console.log(`[${s.name}] 使用新策略:保持原评论区位置,在标签中创建引用`),this.originalCommentBox.style.display="none",this.commentContentContainer.innerHTML=`
<div style="text-align: center; padding: 20px; color: #666;">
评论区已加载,请稍候...
</div>
`,this.setupCommentVisibilityControl())}static setupCommentVisibilityControl(){const e=document.createElement("div");e.id="comment-tab-marker",e.style.display="none",this.commentContentContainer?.appendChild(e)}static rebindCommentEvents(){if(!this.commentContentContainer)return;console.log(`[${s.name}] 评论区已重新组织,原始事件绑定应该保持完整`);const e=this.commentContentContainer.querySelectorAll(".page-button-link, .prev-next-list-link"),t=this.commentContentContainer.querySelector(".form-42516"),n=this.commentContentContainer.querySelector("[contenteditable]");console.log(`[${s.name}] 功能验证:`,{分页按钮:e.length,评论表单:!!t,评论输入框:!!n})}static bindCommentTabClick(e){e.addEventListener("click",t=>{t.preventDefault(),t.stopPropagation(),e.parentElement?.querySelectorAll(".tab-98bb0")?.forEach(o=>{o.classList.remove("selected-98bb0")}),e.classList.add("selected-98bb0"),this.toggleTabContent("comments")})}static createTabSetContainer(){const e=document.createElement("div");return e.className="tabSet-792ed tabSet-0c900",e.id="comment-section-enhanced",e}static createRelatedTab(){const e=document.createElement("div");e.className="tab-98bb0 selected-98bb0",e.setAttribute("data-tab-type","related");const t=document.createElement("span");t.className="root-48288 unset-48288 link-a68d6";const n=document.createElement("div");return n.className="body-bold-8643e unset-8643e",n.textContent="有关的影片",t.appendChild(n),e.appendChild(t),e.style.cursor="pointer",e.addEventListener("mouseenter",()=>{e.classList.contains("selected-98bb0")||(t.style.opacity="0.8")}),e.addEventListener("mouseleave",()=>{t.style.opacity=""}),e}static createRelatedContentContainer(e){const t=document.createElement("div");for(t.id="related-tab-content",t.style.cssText=`
display: block;
margin-top: 20px;
`;e.firstChild;)t.appendChild(e.firstChild);const n=document.querySelector("#comment-section-enhanced");if(n&&n.parentElement){const o=n.nextElementSibling;o?n.parentElement.insertBefore(t,o):n.parentElement.appendChild(t)}}static bindRelatedTabClick(e){e.addEventListener("click",t=>{t.preventDefault(),t.stopPropagation(),e.parentElement?.querySelectorAll(".tab-98bb0")?.forEach(o=>{o.classList.remove("selected-98bb0")}),e.classList.add("selected-98bb0"),this.toggleTabContent("related")})}static toggleTabContent(e){const t=document.querySelector("#related-tab-content"),n=this.commentContentContainer,o=document.querySelector(s.selectors.showMoreButton);e==="comments"?(t&&(t.style.display="none"),n&&(n.style.display="block"),this.originalCommentBox&&(n.innerHTML="",n.appendChild(this.originalCommentBox),this.originalCommentBox.style.display="block",console.log(`[${s.name}] 评论区已移动到评论标签中`)),o&&(o.style.display="none"),this.hideOtherTabContents()):e==="related"&&(t&&(t.style.display="block"),n&&(n.style.display="none"),this.originalCommentBox&&this.originalCommentBox.parentElement===n&&(document.body.appendChild(this.originalCommentBox),this.originalCommentBox.style.display="none",console.log(`[${s.name}] 评论区已移回原位置(隐藏)`)),o&&(o.style.display="block"),this.showOtherTabContents())}static hideOtherTabContents(){const e=document.querySelector("#related-tab-content");e&&(e.style.display="none");const t=document.querySelector(s.selectors.commentTabSet)||document.querySelector("#comment-section-enhanced");if(!t)return;const n=t.parentElement;if(!n)return;[".videos-list",".thumb-list",".content-container","[data-tab-content]"].forEach(i=>{n.querySelectorAll(i).forEach(r=>{r!==this.commentContentContainer&&r.id!=="related-tab-content"&&(r.style.display="none")})})}static observeOtherTabClicks(){const e=document.querySelector(s.selectors.commentTabSet)||document.querySelector("#comment-section-enhanced");e&&e.addEventListener("click",t=>{const o=t.target.closest(".tab-98bb0");if(!o)return;const i=o.getAttribute("data-tab-type");if(i==="comments"||i==="related")return;e.querySelectorAll(".tab-98bb0").forEach(h=>h.classList.remove("selected-98bb0")),o.classList.add("selected-98bb0"),this.commentContentContainer&&(this.commentContentContainer.style.display="none",this.originalCommentBox&&this.originalCommentBox.parentElement===this.commentContentContainer&&(document.body.appendChild(this.originalCommentBox),this.originalCommentBox.style.display="none",console.log(`[${s.name}] 评论区已移回原位置(隐藏)`)));const r=document.querySelector("#related-tab-content");r&&(r.style.display="none");const c=document.querySelector(s.selectors.showMoreButton);c&&(c.style.display="block"),this.showOtherTabContents()})}static showOtherTabContents(){const e=document.querySelector("#related-tab-content");e&&(e.style.display="block");const t=document.querySelector(s.selectors.commentTabSet)||document.querySelector("#comment-section-enhanced");if(!t)return;const n=t.parentElement;if(!n)return;[".videos-list",".thumb-list",".content-container","[data-tab-content]"].forEach(i=>{n.querySelectorAll(i).forEach(r=>{r!==this.commentContentContainer&&r.id!=="related-tab-content"&&(r.style.display="")})})}static reset(){this.hasCommentTabAdded=!1,this.commentContentContainer=null,this.originalCommentBox=null}static update(){v.getCurrentPageType()==="video"&&this.addCommentTab()}};b.hasCommentTabAdded=!1,b.commentContentContainer=null,b.originalCommentBox=null;let p=b;function x(u,e){let t;return(...n)=>{clearTimeout(t),t=setTimeout(()=>u(...n),e)}}const y=class y{static init(){console.log(`[${s.name}] 初始化应用控制器...`),f.cleanupOldSettings(),this.addPreloadStyles(),this.createToggleUI(),this.initUnifiedObserver(),console.log(`[${s.name}] 应用控制器初始化完成`)}static addPreloadStyles(){const e=document.createElement("style");e.id="xh-preload-styles",e.textContent=`
/* 防止广告闪烁的预加载样式 */
.menu-ad-hidden { display: none !important; }
.hidden-by-script { display: none !important; }
/* 预隐藏已知广告选择器 */
[data-nav-item-id="cams"],
[data-nav-item-id="dating"],
[data-nav-item-id="priority-vpn"],
[data-nav-item-id="ai-friend"],
[data-nav-item-id="flirtify"],
[data-item="premium"] {
display: none !important;
}
/* 通过选择器隐藏广告(比:has()更兼容) */
`,document.head.insertBefore(e,document.head.firstChild)}static shouldApplyHideWatchedFeature(){const e=window.location.pathname;return["/search/","/categories/","/tags/","/videos/"].some(o=>e.startsWith(o))?!0:!["/photos/","/users/","/my/","/messages","/live","/creators","/p/","/info"].some(o=>e.startsWith(o))}static createToggleUI(){if(!this.shouldApplyHideWatchedFeature())return;const t=(()=>{let n=document.querySelector(".items-3b1bc");if(n||(n=document.querySelector(".container-3b1bc")),n||(n=document.querySelector("nav .container-3b1bc, header .container-3b1bc")),n){const o=n.querySelector(".dropdown-3b1bc");return o?{container:n,insertAfter:o}:{container:n,insertBefore:null}}return null})();if(t){const n=document.createElement("div");n.id="xh-toggle-compact-btn",n.className="container-64b3c",n.style.cssText=`
display: flex;
align-items: center;
cursor: pointer;
transition: all 0.3s ease;
margin: 0;
padding: 0;
`;const o=document.createElement("div");o.className="root-48288 invert-48288 link-64b3c",o.style.cssText=`
display: flex;
align-items: center;
padding: 0 12px;
height: 100%;
text-decoration: none;
color: inherit;
`;const i=document.createElement("div");i.className="h4-8643e invert-8643e linkText-64b3c",i.style.cssText=`
display: flex;
align-items: center;
gap: 6px;
`;const a=document.createElement("span");a.style.cssText=`
white-space: nowrap;
font-size: inherit;
`;const r=document.createElement("div");r.style.cssText=`
width: 24px;
height: 12px;
background: rgba(255, 255, 255, 0.2);
border-radius: 6px;
position: relative;
transition: background 0.3s;
margin-left: 8px;
`;const c=document.createElement("div");c.style.cssText=`
position: absolute;
top: 1px;
left: 1px;
width: 10px;
height: 10px;
background: white;
border-radius: 50%;
transition: all 0.3s ease;
`,r.appendChild(c),i.appendChild(a),i.appendChild(r),o.appendChild(i),n.appendChild(o);const h=()=>{l.getCurrentHideWatchedSetting()?(a.textContent="隐藏已观看",r.style.background="rgba(76, 175, 80, 0.4)",c.style.background="#4CAF50",c.style.left="13px",n.style.opacity="1"):(a.textContent="显示已观看",r.style.background="rgba(255, 255, 255, 0.2)",c.style.background="white",c.style.left="1px",n.style.opacity="0.7")};n.addEventListener("click",d=>{d.preventDefault(),d.stopPropagation();const w=!l.getCurrentHideWatchedSetting();l.toggleWatchedVideos(!w),h()}),n.addEventListener("mouseenter",()=>{a.style.color="#ccc"}),n.addEventListener("mouseleave",()=>{a.style.color=""});try{if(!document.querySelector("#xh-toggle-compact-btn"))if(t.insertAfter){const d=t.insertAfter.nextSibling;d?t.container.insertBefore(n,d):t.container.appendChild(n)}else t.container.appendChild(n)}catch(d){console.warn("插入开关按钮失败:",d)}h()}else setTimeout(()=>this.createToggleUI(),500)}static initUnifiedObserver(){this.debouncedContentHandler=x(()=>{l.removeVideoAds(),l.applyWatchedVideoFilter(),g.addRemoveButtons(),l.removeTopMenuAds(),p.update()},300),setTimeout(()=>{l.removeVideoAds(),l.applyWatchedVideoFilter(),l.removeTopMenuAds(),p.update()},100),this.intervalId=window.setInterval(()=>{l.removeVideoAds(),l.applyWatchedVideoFilter(),l.removeTopMenuAds(),p.update()},5e3),this.mutationObserver=new MutationObserver(t=>{let n=!1;t.forEach(o=>{o.type==="childList"&&o.addedNodes.length>0&&o.addedNodes.forEach(i=>{if(i.nodeType===Node.ELEMENT_NODE){const a=i,r=a.classList&&(a.classList.contains("thumb-list__item")||a.classList.contains("thumbContainer-53a78")||a.classList.contains("video-thumb")||a.classList.contains("thumb-53a78")||a.classList.contains("content")||a.classList.contains("main")||a.classList.contains("tabSet-792ed")||a.classList.contains("commentsWrap-99011")),c=a.querySelector&&(a.querySelector(".thumb-list__item")||a.querySelector(".video-thumb")||a.querySelector('a[href*="/fh/out?url="]')||a.querySelector(".badge-cb84e")||a.querySelector(".tabSet-792ed")||a.querySelector(".commentsWrap-99011"));(r||c)&&(n=!0)}})}),n&&this.debouncedContentHandler()});const e=[document.querySelector(".thumb-list"),document.querySelector(".videos-list"),document.querySelector(".content-container"),document.querySelector("main"),document.querySelector("#content")].filter(Boolean);e.length>0?e.forEach(t=>{this.mutationObserver.observe(t,{childList:!0,subtree:!0})}):this.mutationObserver.observe(document.body,{childList:!0,subtree:!0})}static triggerUpdate(){this.debouncedContentHandler&&this.debouncedContentHandler()}static cleanup(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null)}};y.mutationObserver=null,y.intervalId=null,y.debouncedContentHandler=null;let m=y;function T(){try{C.init(),l.init(),g.init(),p.init(),m.init(),console.log(`[${s.name}] 已加载`)}catch(u){console.error(`[${s.name}] 初始化失败:`,u)}}function S(){setTimeout(()=>{m.triggerUpdate()},300)}function E(){m.cleanup()}T(),document.readyState==="complete"?S():window.addEventListener("load",S),window.addEventListener("beforeunload",E),window.XhamsterOptimizer={config:s,modules:{VideoEnhancer:C,ContentFilter:l,FavoritesManager:g,CommentTabManager:p,AppController:m},utils:{triggerUpdate:()=>m.triggerUpdate(),cleanup:()=>m.cleanup()}}})();