// ==UserScript==
// @name sis001-预览
// @version 1.1.4
// @namespace https://sleazyfork.org/zh-CN/users/1461640-%E6%98%9F%E5%AE%BF%E8%80%81%E9%AD%94
// @author 星宿老魔
// @description sis001第一会所综合社区,帖子图片预览,板块收纳,搜索优化
// @match https://sis001.com/*
// @match https://*.sis001.com/*
// @icon https://www.google.com/s2/favicons?sz=64&domain=sis001.com
// @license MIT
// @grant none
// @run-at document-start
// ==/UserScript==
(function(){"use strict";const f={ACCENT:"#00599F",BG_LIGHT:"#f8f9fa",BG_ERROR:"#f0f0f0",BORDER_LIGHT:"#e3e6ea",BORDER_NORMAL:"#e9ecef",TEXT_PRIMARY:"#2c3e50",TEXT_SECONDARY:"#666",TEXT_MUTED:"#6c757d",TEXT_LIGHT:"#999",TEXT_ERROR:"#333"},C={SM:"6px",MD:"8px",XL:"12px",ROUND:"50%",PILL:"999px"},b={MD:"8px",LG:"10px",XL:"12px",XXL:"16px"},A={LIGHT:"0 2px 6px rgba(0,0,0,0.08)",NORMAL:"0 3px 12px rgba(0,0,0,0.08)",IMAGE:"0 2px 8px rgba(0,0,0,0.12)"},T={GRADIENT:"linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%)",WHITE_ALPHA:"rgba(255,255,255,0.9)",LIGHT_ALPHA:"rgba(248,249,250,0.6)"},s={select(d){return document.querySelector(d)},selectAll(d){return document.querySelectorAll(d)},create(d,e={},t={}){const r=document.createElement(d);return Object.entries(e).forEach(([o,n])=>{r.setAttribute(o,n)}),Object.entries(t).forEach(([o,n])=>{r.style[o]=n}),r},addStyle(d,e){const t=document.createElement("style");return e&&(t.id=e),t.textContent=d,document.head.appendChild(t),t}};async function O(d,e,t=8){const r=[...d],o=new Set,n=[];async function a(){if(r.length===0)return;const i=r.shift(),c=e(i).then(l=>{n.push(l)}).finally(()=>{o.delete(c)});return o.add(c),o.size>=t&&await Promise.race(Array.from(o)),a()}return await a(),await Promise.all(Array.from(o)),n}const x={resolve(d,e){try{return new URL(e,d).href}catch(t){return console.warn("[URL] 解析 URL 失败:",t),e}},isHttp(d){return/^https?:\/\//i.test(d)}},S={applyButtonStyle(d,e={}){const{primary:t=!1}=e;d.style.cssText=["display:inline-flex","align-items:center","justify-content:center","height:28px","padding:0 12px","border-radius:6px","font-size:12px","line-height:1","cursor:pointer","user-select:none","white-space:nowrap","box-sizing:border-box",`background:#fff;color:${f.TEXT_PRIMARY};border:1px solid ${f.BORDER_LIGHT}`].join(";")},ensureToggleStyles(){if(document.querySelector('style[data-sis-toggle-style="1"]'))return;const d=`.sis-toggle{display:inline-flex;align-items:center;gap:${C.SM};cursor:pointer;user-select:none;height:28px;padding:0 12px;border:1px solid ${f.BORDER_LIGHT};border-radius:${C.SM};background:#fff;box-shadow:${A.LIGHT};vertical-align:middle;box-sizing:border-box}.sis-toggle .sis-input{position:absolute;opacity:0;width:0;height:0}.sis-toggle .sis-switch{position:relative;width:30px;height:16px;background:#e5e7eb;border-radius:${C.PILL};box-shadow:inset 0 0 0 1px #d1d5db;flex:0 0 30px}.sis-toggle .sis-switch::before{content:"";position:absolute;top:2px;left:2px;width:12px;height:12px;background:#fff;border-radius:${C.ROUND};box-shadow:0 1px 2px rgba(0,0,0,.2)}.sis-toggle .sis-input:checked + .sis-text + .sis-switch{background:${f.ACCENT}}.sis-toggle .sis-input:checked + .sis-text + .sis-switch::before{transform:translateX(14px)}.sis-toggle .sis-text{color:${f.TEXT_ERROR};font-size:12px}`;s.addStyle(d,"sis-toggle-styles").setAttribute("data-sis-toggle-style","1")}},m={createOverlay(){return s.create("div",{},{position:"fixed",inset:"0",background:"rgba(0,0,0,0.4)",zIndex:"10001",display:"flex",alignItems:"center",justifyContent:"center"})},createPanel(d="480px"){return s.create("div",{},{width:d,maxWidth:"92vw",maxHeight:"80vh",overflow:"auto",background:"#fff",borderRadius:"10px",boxShadow:"0 10px 30px rgba(0,0,0,.2)"})},createHeader(d,e){const t=s.create("div",{},{padding:"12px 16px",borderBottom:"1px solid #e9ecef",fontWeight:"600",display:"flex",justifyContent:"space-between",alignItems:"center"});t.textContent=d;const r=s.create("button");return r.textContent="×",S.applyButtonStyle(r),r.onclick=e,t.appendChild(r),t},createFooter(d,e,t="保存并刷新"){const r=s.create("div",{},{padding:"12px 16px",borderTop:"1px solid #e9ecef",display:"flex",justifyContent:"flex-end",gap:"10px"}),o=s.create("button");o.textContent="取消",S.applyButtonStyle(o),o.onclick=d;const n=s.create("button");return n.textContent=t,S.applyButtonStyle(n),n.onclick=e,r.appendChild(o),r.appendChild(n),r}},_={waitForDOMContentLoaded(){return document.readyState==="loading"?new Promise(d=>{document.addEventListener("DOMContentLoaded",()=>d(),{once:!0})}):Promise.resolve()},waitForWindowLoad(){return document.readyState!=="complete"?new Promise(d=>{window.addEventListener("load",()=>d(),{once:!0})}):Promise.resolve()}},L=class L{static init(){this.setupMagnetLinks()}static setupMagnetLinks(){if(!s.select(".t_msgfont"))return;s.selectAll(".t_msgfont").forEach(t=>{this.processPost(t)})}static processPost(e){if(this.processed.has(e))return;const t=/([a-fA-F0-9]{40})/g;t.test(e.innerHTML)&&(e.innerHTML=e.innerHTML.replace(t,r=>`magnet:?xt=urn:btih:${r}`)),this.processed.add(e)}static refresh(){this.setupMagnetLinks()}};L.processed=new WeakSet;let k=L;class N{static init(){this.injectHidingCSS(),this.removeRulesTable(),this.removePublicMessages(),this.removeStickyTopics(),this.removeImportantTopics(),this.removeAdministrativeThreads(),setTimeout(()=>{this.removeRulesTable(),this.removePublicMessages(),this.removeStickyTopics(),this.removeImportantTopics(),this.removeAdministrativeThreads()},1e3)}static injectHidingCSS(){if(s.select('style[data-sis-ad-remover="1"]'))return;s.addStyle(`
/* 立即隐藏本版规则表格 */
table[summary="Rules and Recommend"] { display: none !important; }
/* 立即隐藏公共消息 */
.maintable#pmprompt,
.box#pmprompt { display: none !important; }
/* 立即隐藏固定主题和重要主题区块 */
thead.separation { display: none !important; }
tbody[id^="stickthread_"] { display: none !important; }
/* 立即隐藏版务相关帖子(备用CSS) */
.sis-hide-admin { display: none !important; }
`).setAttribute("data-sis-ad-remover","1")}static removeRulesTable(){const e=document.querySelector('table[summary="Rules and Recommend"]');e&&e.remove()}static removePublicMessages(){const e=document.querySelector(".maintable#pmprompt");e&&e.remove();const t=document.querySelector(".box#pmprompt");t&&t.remove()}static removeStickyTopics(){document.querySelectorAll("thead.separation").forEach(t=>{const r=t.querySelectorAll("font");let o=!1;if(r.forEach(n=>{n.textContent?.includes("固定主題")&&(o=!0)}),o){t.remove();let n=t.nextElementSibling;for(;n&&(n.tagName==="TBODY"&&n.id&&n.id.startsWith("stickthread_"));){const a=n;n=n.nextElementSibling,a.remove()}}})}static removeImportantTopics(){document.querySelectorAll("thead.separation").forEach(t=>{const r=t.querySelectorAll("font");let o=!1;if(r.forEach(n=>{n.textContent?.includes("重要主題")&&(o=!0)}),o){t.remove();let n=t.nextElementSibling;for(;n&&(n.tagName==="TBODY"&&n.id&&n.id.startsWith("stickthread_"));){const a=n;n=n.nextElementSibling,a.remove()}}})}static removeAdministrativeThreads(){document.querySelectorAll('tbody[id^="stickthread_"], tbody[id^="normalthread_"]').forEach(t=>{t.querySelectorAll('em a[href*="typeid=528"]').length>0&&(t.classList.add("sis-hide-admin"),setTimeout(()=>{t.remove()},10))})}static refresh(){this.removeRulesTable(),this.removePublicMessages(),this.removeStickyTopics(),this.removeImportantTopics(),this.removeAdministrativeThreads()}}const h={collectNames:"sis_board_collect_names",favoriteNames:"sis_board_favorite_names",collectionOpen:"sis_board_collection_open",favoriteOpen:"sis_board_favorite_open",searchFavForums:"sis_search_fav_forums",searchFavAuto:"sis_search_fav_auto",previewCache:"sis_preview_cache_v1",previewMaxImages:"sis_preview_max_images",previewConcurrency:"sis_preview_concurrency"},P={MAX_PREVIEW_CONCURRENCY:9,MAX_IMAGES_PER_POST:3,PREVIEW_CACHE_TTL_MS:900*1e3};class p{static getMaxPreviewConcurrency(){const e=parseInt(localStorage.getItem(h.previewConcurrency)||"",10);return Number.isFinite(e)&&e>=1&&e<=100?e:P.MAX_PREVIEW_CONCURRENCY}static setMaxPreviewConcurrency(e){try{localStorage.setItem(h.previewConcurrency,String(e))}catch(t){console.warn("[Config] 保存预览并发数失败:",t)}}static getMaxImagesPerPost(){const e=parseInt(localStorage.getItem(h.previewMaxImages)||"",10);return Number.isFinite(e)&&e>=1&&e<=20?e:P.MAX_IMAGES_PER_POST}static setMaxImagesPerPost(e){try{localStorage.setItem(h.previewMaxImages,String(e)),this.clearPreviewCache()}catch(t){console.warn("[Config] 保存图片数量配置失败:",t)}}static clearPreviewCache(){try{localStorage.removeItem(h.previewCache),console.log("[Config] 已清除预览缓存")}catch(e){console.warn("[Config] 清除预览缓存失败:",e)}}static getPreviewCache(){try{return JSON.parse(localStorage.getItem(h.previewCache)||"{}")}catch(e){return console.warn("[Config] 解析预览缓存失败:",e),{}}}static setPreviewCache(e){try{localStorage.setItem(h.previewCache,JSON.stringify(e))}catch(t){console.warn("[Config] 保存预览缓存失败:",t)}}static getPreviewCacheEntry(e){const r=this.getPreviewCache()[e];return!r||Date.now()-r.ts>P.PREVIEW_CACHE_TTL_MS?null:Array.isArray(r.urls)?r.urls:null}static savePreviewCacheEntry(e,t){const r=this.getPreviewCache();r[e]={ts:Date.now(),urls:t.slice(0,this.getMaxImagesPerPost())};const o=Object.keys(r);if(o.length>200){o.sort((n,a)=>(r[n].ts||0)-(r[a].ts||0));for(let n=0;n<o.length-200;n++)delete r[o[n]]}this.setPreviewCache(r)}static getCollectedBoardNames(){try{const e=localStorage.getItem(h.collectNames);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t:[]}catch(e){return console.warn("[Config] 获取收纳板块列表失败:",e),[]}}static setCollectedBoardNames(e){try{localStorage.setItem(h.collectNames,JSON.stringify(e||[]))}catch(t){console.warn("[Config] 保存收纳板块列表失败:",t)}}static getFavoriteBoardNames(){try{const e=localStorage.getItem(h.favoriteNames);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t:[]}catch(e){return console.warn("[Config] 获取收藏板块列表失败:",e),[]}}static setFavoriteBoardNames(e){try{localStorage.setItem(h.favoriteNames,JSON.stringify(e||[]))}catch(t){console.warn("[Config] 保存收藏板块列表失败:",t)}}static getCollectionOpen(){try{return localStorage.getItem(h.collectionOpen)==="1"}catch(e){return console.warn("[Config] 获取收纳区状态失败:",e),!1}}static setCollectionOpen(e){try{localStorage.setItem(h.collectionOpen,e?"1":"0")}catch(t){console.warn("[Config] 保存收纳区状态失败:",t)}}static getFavoriteOpen(){try{return localStorage.getItem(h.favoriteOpen)==="1"}catch(e){return console.warn("[Config] 获取收藏区状态失败:",e),!1}}static setFavoriteOpen(e){try{localStorage.setItem(h.favoriteOpen,e?"1":"0")}catch(t){console.warn("[Config] 保存收藏区状态失败:",t)}}static getSearchFavForums(){try{const e=localStorage.getItem(h.searchFavForums);return e?JSON.parse(e):[]}catch(e){return console.warn("[Config] 获取搜索收藏论坛失败:",e),[]}}static setSearchFavForums(e){try{localStorage.setItem(h.searchFavForums,JSON.stringify(e||[]))}catch(t){console.warn("[Config] 保存搜索收藏论坛失败:",t)}}static getSearchFavAuto(){try{return localStorage.getItem(h.searchFavAuto)==="1"}catch(e){return console.warn("[Config] 获取搜索自动记忆状态失败:",e),!1}}static setSearchFavAuto(e){try{localStorage.setItem(h.searchFavAuto,e?"1":"0")}catch(t){console.warn("[Config] 保存搜索自动记忆状态失败:",t)}}}class w{static filterValidImages(e){const t={};return e.filter(o=>{const n=this.getBestImageSource(o),a=this.shouldKeepImage(n,o);return a.keep?(t[a.reason]=(t[a.reason]||0)+1,!0):!1})}static getBestImageSource(e){const t=e.getAttribute("zoomfile");if(t&&t.trim())return this.resolveImageUrl(t.trim());const r=e.getAttribute("file");if(r&&r.trim())return this.resolveImageUrl(r.trim());const o=e.src||e.getAttribute("src")||"";return this.resolveImageUrl(o.trim())}static resolveImageUrl(e){return e?x.isHttp(e)?e:x.resolve(window.location.href,e):""}static shouldKeepImage(e,t){if(!e||!this.isValidImageUrl(e))return{keep:!1,reason:"无效图片源"};if(x.isHttp(e)&&!e.includes("sis001.com/forum/images/"))return{keep:!0,reason:"外部图片"};if(/(^|\/)attachments\//i.test(e))return{keep:!0,reason:"附件图片"};if(t){const r=t.getAttribute("onclick")||"";if(r.includes("zoom(this)")||r.includes("zoom("))return{keep:!0,reason:"zoom图片"}}if(t&&(t.getAttribute("file")||t.getAttribute("zoomfile")))return{keep:!0,reason:"file属性"};if(t){const r=parseInt(t.getAttribute("width")||t.style.width||"0"),o=parseInt(t.getAttribute("height")||t.style.height||"0");if(r>150||o>150)return{keep:!0,reason:"大尺寸图片"}}return{keep:!1,reason:"系统图片"}}static isValidImageUrl(e){if(!e||typeof e!="string")return!1;const t=e.trim();if(!t)return!1;try{return new URL(t),!0}catch{return t.startsWith("/")||t.startsWith("./")||t.startsWith("../")}}static shouldKeepCachedUrl(e){return!e||!this.isValidImageUrl(e)?{keep:!1,reason:"无效图片源"}:x.isHttp(e)&&!e.includes("sis001.com/forum/images/")?{keep:!0,reason:"外部图片"}:/(^|\/)attachments\//i.test(e)?{keep:!0,reason:"附件图片"}:{keep:!1,reason:"系统图片"}}}class F{static async init(){await this.displayThreadImages()}static async displayThreadImages(){if(s.select(".postmessage")||s.select("#postlist")||s.select(".plhin"))return;const e=window.location.href.includes("/search.php"),t=window.location.href.includes("/tag.php");let r=[];if(e||t){const n=s.selectAll("tbody");r=Array.from(n).filter(a=>{const i=a.querySelector('a[href*="thread-"]'),c=a.querySelector(".icon");return i&&c})}else{const n=s.selectAll('tbody[id^="normalthread_"]');r=Array.from(n)}const o=r.map(n=>async()=>{if(n.id&&n.id.startsWith("stickthread_")||n.querySelector(".new-post-layout"))return;const a=n.querySelector('a[href*="thread-"]');if(!a)return;const i=a.href;let c=a.textContent?.trim()||"";if(!c){const l=n.querySelector('span[id^="thread_"]');l&&(c=l.textContent?.trim()||"")}await this.transformPostLayout(n,i,c)});await O(o,n=>n(),p.getMaxPreviewConcurrency())}static async transformPostLayout(e,t,r){e.innerHTML="";const o=s.create("tr"),n=s.create("td",{colspan:"6"},{padding:"4px !important",border:"none !important",background:"transparent !important"}),a=this.createPostContainer(),i=this.createTitleSection(t,r),c=this.createImageSection();a.appendChild(i),a.appendChild(c),n.appendChild(a),o.appendChild(n),e.appendChild(o),await this.loadImagesForPost(t,c)}static createPostContainer(){return s.create("div",{class:"new-post-layout"},{background:T.GRADIENT,border:`1px solid ${f.BORDER_LIGHT}`,borderRadius:C.XL,boxShadow:A.NORMAL,overflow:"hidden"})}static createTitleSection(e,t){const r=s.create("div",{},{padding:`${b.XL} ${b.XXL}`,background:T.WHITE_ALPHA,borderBottom:`1px solid ${f.BORDER_NORMAL}`}),o=s.create("a",{href:e},{fontWeight:"500",color:f.TEXT_PRIMARY,fontSize:"15px",lineHeight:"1.3",textDecoration:"none",display:"block",wordBreak:"break-word"});return o.textContent=t||"无标题",r.appendChild(o),r}static createImageSection(){const e=s.create("div",{},{padding:`${b.MD} ${b.XXL}`,background:T.LIGHT_ALPHA,display:"flex",gap:b.LG,minHeight:"200px",flexWrap:"nowrap",alignItems:"stretch",overflow:"auto"}),t=s.create("div",{},{color:f.TEXT_SECONDARY,fontSize:"14px"});return t.textContent="正在加载图片预览...",e.appendChild(t),e}static async loadImagesForPost(e,t){try{const r=p.getPreviewCacheEntry(e);if(r&&r.length>0){const g=this.filterCachedImageUrls(r);if(g.length>0){this.renderCachedImages(t,g,e);return}else p.clearPreviewCache()}const n=await(await fetch(e)).text(),i=new DOMParser().parseFromString(n,"text/html"),c=Array.from(i.querySelectorAll("img")),l=w.filterValidImages(c).slice(0,p.getMaxImagesPerPost());if(l.length>0){const g=l.map(y=>w.getBestImageSource(y))}if(t.innerHTML="",l.length===0){this.showNoImagesMessage(t);return}const u=l.map(g=>x.resolve(e,w.getBestImageSource(g)));p.savePreviewCacheEntry(e,u),this.renderImages(t,l,u,e)}catch(r){console.warn("[ImagePreview] 加载图片失败:",r),t.innerHTML='<div style="color: #999; font-size: 14px;">图片加载失败</div>'}}static filterCachedImageUrls(e){const t=e.filter(r=>w.shouldKeepCachedUrl(r).keep);return t.length<e.length,t}static renderCachedImages(e,t,r){e.innerHTML="",t.slice(0,p.getMaxImagesPerPost()).forEach((o,n)=>{const a=this.createImageContainer(),i=this.createLoadingPlaceholder(),c=this.createImageElement(o);c.onerror=()=>this.handleImageError(c,o);const l=c.onload;c.onload=u=>{l&&l.call(c,u),i.remove()},this.setupImageInteraction(a,t,n,r),a.appendChild(i),a.appendChild(c),e.appendChild(a)})}static renderImages(e,t,r,o){t.forEach((n,a)=>{const i=this.createImageContainer(),c=this.createLoadingPlaceholder(),l=this.createImageElement(r[a]);l.onerror=()=>this.handleImageErrorWithFallback(l,n,o,r[a]);const u=l.onload;l.onload=g=>{u&&u.call(l,g),c.remove()},this.setupImageInteraction(i,r,a,o),i.appendChild(c),i.appendChild(l),e.appendChild(i)})}static createImageContainer(){return s.create("div",{},{position:"relative",flex:"1",minWidth:"120px",cursor:"pointer",borderRadius:C.MD,overflow:"hidden",boxShadow:A.IMAGE,height:"184px",backgroundColor:f.BG_LIGHT})}static createImageElement(e){const t=s.create("img",{src:e},{width:"100%",height:"100%",objectFit:"cover",display:"block",opacity:"0"});return t.onload=()=>{t.style.opacity="1"},t.onerror=()=>{console.warn("[ImagePreview] 图片加载失败:",e)},t}static createLoadingPlaceholder(){const e=s.create("div",{},{position:"absolute",top:"0",left:"0",width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:f.BG_LIGHT,color:f.TEXT_MUTED,fontSize:"12px",zIndex:"1"});return e.textContent="加载中...",e}static setupImageInteraction(e,t,r,o){e.addEventListener("click",()=>{const n=t.map(a=>s.create("img",{src:a}));this.showImageViewer(n,r,o)})}static handleImageError(e,t){const r=parseInt(e.dataset.attempts||"0",10);if(r>=3){this.showImageLoadError(e);return}if(e.dataset.attempts=String(r+1),console.log(`[ImagePreview] 缓存图片重试第 ${r+1} 次:`,t),r===0){e.referrerPolicy="no-referrer",e.crossOrigin=null,e.removeAttribute("crossorigin"),e.src="",setTimeout(()=>{e.src=t},100);return}if(r===1){const o=document.createElement("img");o.style.cssText=e.style.cssText,o.onload=()=>{o.style.opacity="1"},o.onerror=()=>{console.warn("[ImagePreview] 缓存图片重试失败:",t),this.showImageLoadError(o)},e.parentNode&&e.parentNode.replaceChild(o,e),setTimeout(()=>{o.src=t},200);return}if(r===2){e.referrerPolicy="",e.crossOrigin=null,e.removeAttribute("crossorigin"),e.removeAttribute("referrerpolicy"),e.src="",setTimeout(()=>{e.src=t},300);return}this.showImageLoadError(e)}static handleImageErrorWithFallback(e,t,r,o){const n=parseInt(e.dataset.attempts||"0",10);if(n>=4){this.showImageLoadError(e);return}if(e.dataset.attempts=String(n+1),console.log(`[ImagePreview] 图片重试第 ${n+1} 次:`,o),n===0){e.referrerPolicy="no-referrer",e.crossOrigin=null,e.removeAttribute("crossorigin"),e.src="",setTimeout(()=>{e.src=o},100);return}if(n===1){const a=t.getAttribute("file");if(a){const i=x.resolve(r,a);if(i!==e.src){e.referrerPolicy="no-referrer",e.removeAttribute("crossorigin"),e.src=i;return}}}if(n===2&&/(^|\/)attachments\//i.test(o)&&!x.isHttp(o)){let i=o.startsWith("/")?o:"/"+o;i.startsWith("/attachments/")||(i="/attachments/"+i.replace(/^(\.\/)?attachments\//,""));const l=new URL(r).origin+i;if(l!==e.src){e.referrerPolicy="no-referrer",e.removeAttribute("crossorigin"),e.src=l;return}}if(n===3){const a=document.createElement("img");a.style.cssText=e.style.cssText,Array.from(e.attributes).forEach(i=>{i.name.startsWith("data-")&&i.name!=="data-attempts"&&a.setAttribute(i.name,i.value)}),a.onload=()=>{a.style.opacity="1"},a.onerror=()=>{console.warn("[ImagePreview] 最终重试失败:",o),this.showImageLoadError(a)},e.parentNode&&e.parentNode.replaceChild(a,e),setTimeout(()=>{a.src=o},200);return}this.showImageLoadError(e)}static showImageLoadError(e){e.style.background=f.BG_ERROR,e.style.opacity="1",e.alt="图片加载失败";const t=e.parentElement?.querySelector('div[style*="position: absolute"]');t&&t.remove()}static showNoImagesMessage(e){const t=s.create("div",{},{color:f.TEXT_LIGHT,fontSize:"14px",fontStyle:"italic"});t.textContent="暂无图片预览",e.appendChild(t)}static showImageViewer(e,t,r){const o=this.createViewerOverlay(),{container:n,img:a,info:i,prevBtn:c,nextBtn:l}=this.createViewerElements();let u=t;const g=()=>{const v=w.getBestImageSource(e[u]);a.src=x.resolve(r||location.href,v),i.textContent=`${u+1} / ${e.length}`};c.addEventListener("click",()=>{u=(u-1+e.length)%e.length,g()}),l.addEventListener("click",()=>{u=(u+1)%e.length,g()});const y=v=>{v.key==="ArrowLeft"?c.click():v.key==="ArrowRight"?l.click():v.key==="Escape"&&(o.remove(),document.removeEventListener("keydown",y))};o.addEventListener("click",v=>{v.target===o&&(o.remove(),document.removeEventListener("keydown",y))}),n.appendChild(i),n.appendChild(c),n.appendChild(l),n.appendChild(a),o.appendChild(n),document.body.appendChild(o),document.addEventListener("keydown",y),g()}static createViewerOverlay(){return s.create("div",{},{position:"fixed",top:"0",left:"0",width:"100%",height:"100%",background:"rgba(0,0,0,0.9)",zIndex:"10000",display:"flex",alignItems:"center",justifyContent:"center"})}static createViewerElements(){const e=s.create("div",{},{position:"relative",maxWidth:"90%",maxHeight:"90%",textAlign:"center"}),t=s.create("img",{},{maxWidth:"100%",maxHeight:"100%",objectFit:"contain",borderRadius:"8px",boxShadow:"0 4px 20px rgba(0,0,0,0.5)"}),r=s.create("div",{},{position:"absolute",top:"-40px",left:"50%",transform:"translateX(-50%)",color:"white",fontSize:"16px",fontWeight:"bold",background:"rgba(0,0,0,0.7)",padding:"8px 16px",borderRadius:"20px"}),o={position:"absolute",top:"50%",transform:"translateY(-50%)",background:"rgba(255,255,255,0.2)",color:"white",border:"none",fontSize:"24px",width:"44px",height:"44px",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer"},n=s.create("button",{},{...o,left:"-60px"});n.innerHTML="❮";const a=s.create("button",{},{...o,right:"-60px"});return a.innerHTML="❯",{container:e,img:t,info:r,prevBtn:n,nextBtn:a}}}class M{static init(){this.normalizeExclusiveLists(),this.setupBoardCollectionCollapse(),this.setupBoardFavoriteSection(),this.setupBoardHotkeys()}static normalizeExclusiveLists(){const e=new Set(p.getFavoriteBoardNames()),t=new Set(p.getCollectedBoardNames());let r=!1;e.forEach(o=>{t.has(o)&&(t.delete(o),r=!0)}),r&&p.setCollectedBoardNames(Array.from(t))}static findBoardElementsMap(){const e=new Map;return s.selectAll("div.mainbox.forumlist").forEach(r=>{const n=r.querySelector("h3 > a")?.textContent?.trim()||"";n&&!e.has(n)&&e.set(n,r)}),e}static moveBoardsToContainer(e,t){const r=this.findBoardElementsMap(),o=[];return e.forEach(n=>{const a=r.get(n);a&&(t.appendChild(a),o.push(n))}),o}static setupBoardCollectionCollapse(){if(s.select("#board-collection-container"))return;const e=new Set(p.getCollectedBoardNames()),t=Array.from(s.selectAll("div.mainbox.forumlist"));if(t.length===0)return;const r=t.filter(a=>{const c=a.querySelector("h3 > a")?.textContent?.trim()||"";return c&&e.has(c)}),o=this.createBoardContainer("board-collection-container","板块收纳区",r.length),{content:n}=this.setupContainerElements(o,{isOpen:p.getCollectionOpen(),onToggle:a=>p.setCollectionOpen(a),onSettings:()=>this.openBoardCollectSettings(),title:"板块收纳区",count:r.length});if(this.insertContainer(o),r.length===0)this.showEmptyMessage(n,'未选择任何板块,可点击右侧"设置"进行选择。');else{const a=r.map(i=>i.querySelector("h3 > a")?.textContent?.trim()||"");this.moveBoardsToContainer(a,n)}}static setupBoardFavoriteSection(){if(s.select("#board-favorite-container"))return;const e=new Set(p.getFavoriteBoardNames()),t=Array.from(s.selectAll("div.mainbox.forumlist"));if(t.length===0)return;const r=t.filter(a=>{const c=a.querySelector("h3 > a")?.textContent?.trim()||"";return c&&e.has(c)}),o=this.createBoardContainer("board-favorite-container","板块收藏区",r.length),{content:n}=this.setupContainerElements(o,{isOpen:p.getFavoriteOpen(),onToggle:a=>p.setFavoriteOpen(a),onSettings:()=>this.openBoardFavoriteSettings(),title:"板块收藏区",count:r.length});if(this.insertFavoriteContainer(o),r.length===0)this.showEmptyMessage(n,'未选择任何收藏板块,可点击右侧"设置"进行选择。');else{const a=r.map(i=>i.querySelector("h3 > a")?.textContent?.trim()||"");this.moveBoardsToContainer(a,n)}}static createBoardContainer(e,t,r){return s.create("div",{id:e},{margin:"12px 0",border:"1px solid #e3e6ea",borderRadius:"10px",boxShadow:"0 3px 12px rgba(0,0,0,0.08)",overflow:"hidden",background:"#fff"})}static setupContainerElements(e,t){const r=s.create("div",{},{padding:"10px 14px",background:t.isOpen?"#e9ecef":"linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%)",borderBottom:"1px solid #e9ecef",cursor:"pointer",userSelect:"none",display:"flex",alignItems:"center",justifyContent:"space-between"}),o=s.create("span",{},{fontWeight:"600",color:"#2c3e50",fontSize:"14px"});o.textContent=`${t.title}(共 ${t.count} 个)`;const n=s.create("span",{},{fontSize:"12px",color:"#666"});n.textContent=t.isOpen?"[点击收起]":"[点击展开]";const a=s.create("button");a.textContent="设置",a.title="选择需要管理的板块",S.applyButtonStyle(a),a.addEventListener("click",l=>{l.stopPropagation(),t.onSettings()});const i=s.create("div",{},{display:"flex",alignItems:"center",gap:"10px"});i.appendChild(n),i.appendChild(a),r.appendChild(o),r.appendChild(i);const c=s.create("div",{},{padding:"10px",background:"rgba(248,249,250,0.6)",display:t.isOpen?"":"none"});return r.addEventListener("click",()=>{const l=c.style.display==="none";c.style.display=l?"":"none",n.textContent=l?"[点击收起]":"[点击展开]",r.style.background=l?"#e9ecef":"linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%)",t.onToggle(l)}),e.appendChild(r),e.appendChild(c),{header:r,content:c,toggleHint:n}}static insertContainer(e){const t=s.select('table.portalbox[summary="HeadBox"]')||s.select("#hottags")?.closest("table")||s.select("#hottags");if(t?.parentNode){const r=t.parentNode;t.nextSibling?r.insertBefore(e,t.nextSibling):r.appendChild(e)}else document.body.appendChild(e)}static insertFavoriteContainer(e){const t=s.select("#board-collection-container");if(t?.parentNode){const r=t.parentNode;t.nextSibling?r.insertBefore(e,t.nextSibling):r.appendChild(e)}else this.insertContainer(e)}static showEmptyMessage(e,t){const r=s.create("div",{},{color:"#666",fontSize:"12px"});r.textContent=t,e.appendChild(r)}static openBoardCollectSettings(){const e=this.getAllBoardNames();this.openBoardSettings(e,p.getCollectedBoardNames(),"板块收纳设置","勾选需要收纳到顶部的板块:",t=>{const r=new Set(p.getFavoriteBoardNames());t.forEach(o=>r.delete(o)),p.setFavoriteBoardNames(Array.from(r)),p.setCollectedBoardNames(t),location.reload()})}static openBoardFavoriteSettings(){const e=this.getAllBoardNames();this.openBoardSettings(e,p.getFavoriteBoardNames(),"板块收藏设置",'勾选需要加入"板块收藏区"的板块:',t=>{const r=new Set(p.getCollectedBoardNames());t.forEach(o=>r.delete(o)),p.setCollectedBoardNames(Array.from(r)),p.setFavoriteBoardNames(t),location.reload()})}static getAllBoardNames(){const e=Array.from(s.selectAll("div.mainbox.forumlist > h3 > a")).map(t=>t.textContent?.trim()||"").filter(Boolean);return Array.from(new Set(e))}static openBoardSettings(e,t,r,o,n){const a=m.createOverlay(),i=m.createPanel("520px"),c=m.createHeader(r,()=>a.remove()),l=s.create("div",{},{padding:"12px 16px"}),u=s.create("div",{},{color:"#666",marginBottom:"8px"});u.textContent=o,l.appendChild(u);const g=s.create("div",{},{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"6px"}),y=new Set(t);e.forEach(I=>{const B=s.create("label",{},{display:"flex",alignItems:"center",gap:"6px",padding:"6px",border:"1px solid #eee",borderRadius:"6px"}),E=s.create("input",{type:"checkbox"});E.checked=y.has(I),E.onchange=()=>{E.checked?y.add(I):y.delete(I)};const R=s.create("span");R.textContent=I,B.appendChild(E),B.appendChild(R),g.appendChild(B)}),l.appendChild(g);const v=m.createFooter(()=>a.remove(),()=>n(Array.from(y)));i.appendChild(c),i.appendChild(l),i.appendChild(v),a.appendChild(i),document.body.appendChild(a)}static setupBoardHotkeys(){window.__sisBoardHotkeysReady||(window.__sisBoardHotkeysReady=!0,document.addEventListener("keydown",e=>{if(e.altKey)if(e.key.toLowerCase()==="b"){const t=s.select("#board-collection-content"),r=s.select("#board-collection-container > div");if(!t||!r)return;const o=t.style.display==="none";t.style.display=o?"":"none";const n=r.querySelector("span:last-child");n&&(n.textContent=o?"[点击收起]":"[点击展开]"),r.style.background=o?"#f0f2f5":"linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%)"}else e.key.toLowerCase()==="m"&&this.openBoardCollectSettings()}))}}class H{static init(){this.setupSearchFavorites()}static setupSearchFavorites(){if(!/\/search\.php(\?|$)/.test(location.pathname+location.search))return;const e=s.select("#srchfid");!e||e.tagName!=="SELECT"||!e.multiple||(this.createSearchTools(e),this.setupTopGrouping(e),this.setupAutoRemember(e))}static createSearchTools(e){const t=s.create("div",{},{margin:"6px 0",display:"flex",gap:"12px",alignItems:"center"}),r=s.create("button",{type:"button"},{height:"30px"});r.textContent="置顶设置",S.applyButtonStyle(r),r.addEventListener("click",n=>{n.preventDefault(),n.stopPropagation(),this.openSearchFavSettings(e)}),S.ensureToggleStyles();const{switchWrap:o}=this.createToggleSwitch();t.appendChild(r),t.appendChild(o),e.parentNode?.insertBefore(t,e)}static createToggleSwitch(){const e=s.create("label",{class:"sis-toggle"}),t=s.create("input",{type:"checkbox",class:"sis-input"});t.checked=p.getSearchFavAuto();const r=s.create("span",{class:"sis-text"});r.textContent="多选记忆";const o=s.create("span",{class:"sis-switch"});return e.appendChild(t),e.appendChild(r),e.appendChild(o),t.addEventListener("change",()=>{if(p.setSearchFavAuto(t.checked),t.checked){const n=s.select("#srchfid");if(n){const a=Array.from(n.selectedOptions).map(i=>i.value).filter(Boolean);a.length>0&&p.setSearchFavForums(a)}}}),{switchWrap:e,switchInput:t}}static setupTopGrouping(e){const t=p.getSearchFavForums();if(t.length===0)return;const r=s.create("optgroup",{label:"常用置顶"});e.insertBefore(r,e.firstChild);const o=Array.from(e.querySelectorAll("option"));t.forEach(n=>{const a=o.find(i=>i.value===n);a&&r.appendChild(a)}),p.getSearchFavAuto()&&(Array.from(e.options).forEach(n=>n.selected=!1),Array.from(r.querySelectorAll("option")).forEach(n=>n.selected=!0))}static setupAutoRemember(e){p.getSearchFavAuto()&&e.addEventListener("change",()=>{const t=Array.from(e.selectedOptions).map(r=>r.value).filter(Boolean);p.setSearchFavForums(t)})}static openSearchFavSettings(e){const t=Array.from(e.querySelectorAll("option")).filter(l=>l.value),r=m.createOverlay(),o=m.createPanel("1100px"),n=m.createHeader("置顶设置",()=>r.remove()),{body:a,favSet:i}=this.createPanelBody(e,t),c=m.createFooter(()=>r.remove(),()=>{p.setSearchFavForums(Array.from(i)),location.reload()});o.appendChild(n),o.appendChild(a),o.appendChild(c),r.appendChild(o),document.body.appendChild(r)}static createPanelBody(e,t){const r=s.create("div",{},{padding:"12px 16px",display:"grid",gridTemplateColumns:"repeat(auto-fit,minmax(260px,1fr))",gap:"12px"}),o=new Set(p.getSearchFavForums());return this.organizeOptions(e,t).forEach(a=>{const i=this.createGroupCard(a,o);r.appendChild(i)}),{body:r,favSet:o}}static organizeOptions(e,t){const r=[];Array.from(e.querySelectorAll("optgroup")).forEach(a=>{const i=Array.from(a.querySelectorAll("option")).filter(c=>c.value);i.length>0&&r.push({label:a.label||"分组",options:i})});const n=Array.from(e.children).filter(a=>a.tagName==="OPTION"&&a.value&&a.value!=="all");return n.length>0&&r.unshift({label:"其他",options:n}),r}static createGroupCard(e,t){const r=s.create("div",{},{border:"1px solid #e9ecef",borderRadius:"8px",overflow:"hidden",background:"#fff"}),o=s.create("div",{},{padding:"8px 10px",background:"#f8f9fa",borderBottom:"1px solid #e9ecef",fontWeight:"600",color:"#2c3e50",fontSize:"12px"});o.textContent=e.label;const n=s.create("div",{},{padding:"8px 10px",display:"flex",flexDirection:"column",gap:"6px"});return e.options.forEach(a=>{const i=s.create("label",{},{display:"flex",alignItems:"center",gap:"6px",padding:"6px",border:"1px solid #eee",borderRadius:"6px"}),c=s.create("input",{type:"checkbox"});c.checked=t.has(a.value),c.onchange=()=>{c.checked?t.add(a.value):t.delete(a.value)};const l=s.create("span");l.textContent=a.textContent?.trim()||"",i.appendChild(c),i.appendChild(l),n.appendChild(i)}),r.appendChild(o),r.appendChild(n),r}}class z{static init(){this.hideVirtualSoccerEarly(),this.injectScriptConfigMenuButton()}static hideVirtualSoccerEarly(){if(s.select('style[data-sis-hide-soccer="1"]'))return;s.addStyle(`
a[href="z_soccer.php"],
a[href*="z_soccer"] {
display: none !important;
}
`,"sis-hide-soccer").setAttribute("data-sis-hide-soccer","1")}static injectScriptConfigMenuButton(){const e=document.querySelector('a[href="z_soccer.php"]');if(e){e.textContent="脚本配置",e.href="javascript:void(0)";const t=e.cloneNode(!0);t.addEventListener("click",o=>{o.preventDefault(),this.openScriptSettingsPanel()}),e.parentNode?.replaceChild(t,e),t.style.display="";const r=t.closest("li");r&&(r.id="sis-script-settings")}else{const t=document.querySelectorAll('a[href*="z_soccer"]');if(t.length>0){const r=t[0];r.textContent="脚本配置",r.href="javascript:void(0)";const o=r.cloneNode(!0);o.addEventListener("click",a=>{a.preventDefault(),this.openScriptSettingsPanel()}),r.parentNode?.replaceChild(o,r),o.style.display="";const n=o.closest("li");n&&(n.id="sis-script-settings")}}}static openScriptSettingsPanel(){const e=m.createOverlay(),t=m.createPanel("480px"),r=this.createPanelBody(),o=m.createHeader("脚本配置",()=>e.remove()),n=m.createFooter(()=>e.remove(),()=>this.saveSettings(r));t.appendChild(o),t.appendChild(r),t.appendChild(n),e.appendChild(t),document.body.appendChild(e)}static createPanelBody(){const e=s.create("div",{},{padding:"12px 16px",display:"flex",flexDirection:"column",gap:"12px"}),t=this.createSelectRow("预览图数量",[{value:"3",text:"3张"},{value:"4",text:"4张"},{value:"5",text:"5张"}],String(p.getMaxImagesPerPost())),r=this.createSelectRow("加载并发上限",[{value:"6",text:"6个(推荐)"},{value:"10",text:"10个(平衡)"},{value:"15",text:"15个(快速)"}],String(p.getMaxPreviewConcurrency())),o=s.create("div",{},{color:"#777",fontSize:"12px"});return o.textContent="提示:并发过大会增加服务器负载,推荐使用默认档位。",e.appendChild(t),e.appendChild(r),e.appendChild(o),e}static createSelectRow(e,t,r){const o=s.create("label",{},{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"12px",padding:"8px 10px",border:"1px solid #e9ecef",borderRadius:"8px"}),n=s.create("span",{},{fontSize:"13px",color:"#2c3e50"});n.textContent=e;const a=s.create("select",{},{width:"120px",padding:"6px 8px",border:"1px solid #e3e6ea",borderRadius:"6px",background:"#fff",fontSize:"12px"});return t.forEach(i=>{const c=s.create("option",{value:i.value});c.textContent=i.text,i.value===r&&(c.selected=!0),a.appendChild(c)}),o.__select=a,o.appendChild(n),o.appendChild(a),o}static saveSettings(e){const t=Array.from(e.children).filter(r=>r.__select);if(t.length>=2){const r=t[0].__select,o=t[1].__select,n=parseInt(r.value,10),a=parseInt(o.value,10);p.setMaxImagesPerPost(n),p.setMaxPreviewConcurrency(a),location.reload()}}}async function D(){try{G(),N.init(),document.readyState==="loading"&&await _.waitForDOMContentLoaded(),k.init(),await _.waitForWindowLoad(),await F.init(),M.init(),H.init(),z.init()}catch(d){console.error("[SIS001 Preview] 初始化失败:",d)}}function G(){const d=document.querySelectorAll("a");for(let e=0;e<d.length;e++){const t=d[e];if(t.textContent&&t.textContent.includes("电脑版")){window.location.href=t.href;break}}}D()})();