☰

JAV cross-site navigation Linker (Class Refactor)

Cross-site navigation and enhancement script for JAV sites, integrated with JavDB DMM/MGStage High-Res replacement, supporting config file import/export.

You will need to install an extension such as Tampermonkey, Greasemonkey or Violentmonkey to install this script.

You will need to install an extension such as Tampermonkey or Violentmonkey to install this script.

You will need to install an extension such as Tampermonkey or Violentmonkey to install this script.

You will need to install an extension such as Tampermonkey or Userscripts to install this script.

You will need to install an extension such as Tampermonkey to install this script.

You will need to install a user script manager extension to install this script.

(I already have a user script manager, let me install it!)

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

ستحتاج إلى تثبيت إضافة مثل Stylus لتثبيت هذا النمط.

ستحتاج إلى تثبيت إضافة لإدارة أنماط المستخدم لتتمكن من تثبيت هذا النمط.

ستحتاج إلى تثبيت إضافة لإدارة أنماط المستخدم لتثبيت هذا النمط.

ستحتاج إلى تثبيت إضافة لإدارة أنماط المستخدم لتثبيت هذا النمط.

(لدي بالفعل مثبت أنماط للمستخدم، دعني أقم بتثبيته!)

// ==UserScript==
// @name        JAV cross-site navigation Linker (Class Refactor)
// @namespace   https://tampermonkey.net/
// @icon        data:image/gif;base64,iVBORw0KGgoAAAANSUhEUgAAAC4AAAAuCAMAAABgZ9sFAAAAwFBMVEX///8AAAD/XV2nxf//X1//YWGsy//k5ORlZWXx8fGoqKjIyMg4ODhtbW2pyP9ZWVlBQUGAgIC+vr5fX1+urq69RUUTExPq6ura2tqKioqRq910dHRPT0/4+PguLi63t7c3QVI9SFuVlZUmJiZGUmgbGxsXGyNYaIWgvfN7kbuKo9IOExxzh69jJSWenp5bIiJhc5Oz0/8tNUSVNDMlDg57REREGhrPTEw3FBTvV1ekNjbRhYX/oqN4LCyKMzPiU1PPfiQiAAACfElEQVRIiY2VC3eiMBCFcxUFxReCPKqoq7a17Wq3q6vW3W3//7/qTIKAEqpzDgcOfJnc3EwGIXRhWz66E+0nTVhAq0fXbbSDUUOIeIjRLXTAaWM5iX0D3kRfjGAKYcK5SYsp+mD+JjUzhEJMABHDugG3pQlbI1XNq0o8IeYkniIE4is0Od4ka+B6kyGuGmPBnTM/AsU4lO/i0t210BUNzi+C/sRUC6H5SnimRcLLCGY+0PPKaOVbw094hxRFZqkStNWTTZ5ztDEvk030YgGXn8LUEqVOT0/r9R/MhzkDhye+77Sj8JyuVom3zBwddoGA7sE9G5tNpWjJZ7RJ7lu80gavuEVjk/PSTuhq/S6Xm/ZW2eJK52OSJj2daeioK+xEbIPq2AXXG3rSiYdOIXeUeWJjzfXvB6LLBo9x1ykoycv5PsFj/Ts6FeNJMS0sme5nodNvZkt1aESAhVqnlgbXmzQyDl02coInVl5/1Jw0oj2uNzPbJgdLxjvwdXQ/qee0CFywls4zZlr6rP4pei8S/6mOc5Em/h7ZCek9JLhdoE9txsnV8UiJeYJ3SQ9Wqv6dfCseQtq4VJ/ydM145ZdntFjjWRo5hXlBVyrEt6PzNh/iV2LN+JImflX4KcCXu/r2G+NAvbFPdMXYFH4hkdzW+gJbagX9MPToEA0MRVf+9C5o2oaXDtO72v4g9xqr94Q+/r2EBR+mxzeiCal9DjabwbsSQoGhBqcSrkqaE1IkrFH5p+/XVBWHNOMpav9R1u/IuI80azLLKwqrzPKPsd3X0gFG5Zg2TH1EJOj4aRg1GrT/QGlTP0UwZA8Pu92W7+vvYRl25I7ht6x1Wip8AXxjKOd1DpCTAAAAABJRU5ErkJggg==
// @version     2026.10.20
// @description Cross-site navigation and enhancement script for JAV sites, integrated with JavDB DMM/MGStage High-Res replacement, supporting config file import/export.
// @author      idea by 庄引X@https://x.com/zhuangyin8 and edit by gemini
// @include     /^https?:\/\/.*(javdb)[0-9]*\..*$/
// @match       https://www.javbus.com/*
// @match       https://www.fanbus.bond/*
// @match       https://www.javlibrary.com/*
// @match       https://www.c99i.com/*
// @match       https://jable.tv/*
// @match       https://avjoy.me/video/*
// @match       https://www.av01.media/*
// @match       https://sladko.tv/*
// @match       https://missav.ws/*
// @match       https://sukebei.nyaa.si/*
// @match       https://sukebei.nyaa.mom/*
// @match       https://btdig.com/*
// @match       https://btsow.pics/*
// @match       https://btsow.live/*
// @match       https://yhg007.com/*
// @match       https://*.xyz/*
// @match       https://bt4gprx.com/*
// @match       https://torrentkitty.ink/*
// @match       https://haijiao.com/*
// @match       https://skrbtso.top/*
// @match       https://mypikpak.com/drive/*
// @match       https://pikpak.me/drive/*
// @match       https://www.avsubtitles.com/*
// @match       https://subtitlecat.com/*
// @match       https://whatslink.info
// @match       https://169bbs.com/*
// @match       https://169bbs4.space/*
// @match       https://169bbs4.site/*
// @match       https://www.madou.io/*
// @grant       GM_xmlhttpRequest
// @grant       GM_getValue
// @grant       GM_setValue
// @grant       GM_registerMenuCommand
// @run-at      document-idle
// @connect     javdb.com
// @connect     javbus.bond
// @connect     whatslink.info
// @connect     awsimgsrc.dmm.co.jp
// @connect     pics.dmm.co.jp
// @connect     image.mgstage.com
// @license     MIT
// ==/UserScript==

class JableLinker {
  static defaultSites = {
    JAVDB: "https://javdb580.com",
    JAVBUS: "https://www.javbus.com",
    JAVLIBRARY: "https://www.c99i.com",
    JABLE: "https://jable.tv",
    AVJOY: "https://avjoy.me",
    AV01: "https://www.av01.media",
    SLADKOTV: "https://sladko.tv",
    MISSAV: "https://missav.ws",
    SUKEBEI: "https://sukebei.moonchan.xyz",
    BTDIG: "https://btdig.com",
    BTSOW: "https://btsow.live",
    YHG: "https://yhg007.com",
    BT4GPRX: "https://bt4gprx.com",
    TORRENTKITTY: "https://torrentkitty.ink",
    HAYAV: "https://hayav.com",
    BBS: "https://169bbs3.com",
    SUBTITLECAT: "https://subtitlecat.com",
    HAIJIAO: "https://haijiao.com",
    SKRBTSO: "https://skrbtso.top",
    PIKPAK: "https://mypikpak.com",
    MADOU: "https://www.madou.io",
    WHATSLINK: "https://whatslink.info",
  };
  static SELECTORS = {
    JAVDB_CODE: ".value",
    JAVDB_TITLE: ".title",
    JAVDB_PREVIEW_IMAGES: ".preview-images .tile-item",
    JAVBUS_SAMPLE_BOX: ".sample-box",
    JABLE_TITLE: "h4",
    JAVBUS_TITLE: ".container h3",
    JAVLIBRARY_TITLE: "h3.text",
    AVJOY_TITLE: ".video-title h1",
    AV01_TITLE: ".text-white span",
    SLADKOTV_TITLE: "h1.video-title",
    MISSAV_TITLE: ".mt-4 h1",
    AVSUBTITLES_TITLE: "h1",
  };
  static STYLES = {
    BT4GPRX:`.container, .container-lg, .container-md, .container-sm { max-width:50vw !important; margin-left: 0px !important;}body > main > div > div > div {width:100%!important}`,
    TORRENTKITTY: `#dontfoid,.banner,.center + div,.ta-header,h2,body+iframe, .reco-container,.vpn-warning,div:has(+ .pagination){ display: none !important;}
      .detailSummary th {padding: 5px;}.detailSummary td {color: red;}textarea.magnet-link {height: 50px;}body,a > h3{ font:15px Helvetica, Helvetica Neue, Arial; }
      div.wrapper {margin-left: 0px;width:1000px} .wrapper>p{padding:0 10px;line-height: 2;}tr th {width:110px}#main {padding: 0; background-image: none;}#searchBox {width: 80%;}`,
    WHATSLINK: `.banner,.banner-title,.disc, .wrapper:has(.api),.footer{ display: none !important;}
      .el-input-group {display: inline-flex;width: 1216px}
      .content:has(.image-list){padding: 0;} .img {height: auto  !important;width: auto !important;}`,
    SUKEBEI: `.container{margin-left: 0;margin-top: 20px;}.table-responsive {overflow: auto;height: 880px;}.navbar-form .input-group {box-shadow: 0 0 0 10px rgb(255 255 0 / 0.5);}
      table.torrent-list td:nth-child(4) {white-space: wrap;}.navbar-form .input-group>.form-control {width: 100%;margin-right: 50vw;}
      nav+.container > *:not(.table-responsive):not(.center):not(.panel):not(frame),.ts-im-container {display:none !important;}
      #navbar > form {position: fixed; position: fixed;left: 10vw;width: 60vw;}.table {width: 100%;} .torrent-list>tbody>tr>td { white-space: normal; max-width:90vw;}`,
    BTDIG: `.torrent_name a {font-size: 100% !important;}.fa-folder-closed:before {content:"\\f07b"}
      body > center > div:nth-child(1),body > center > div > div:nth-child(1){padding: 0; margin-left: -47%;}`,
    BTSOW: `.q-pb-md,.q-px-md,.q-my-md,.hidden-xs:not(.tags-box,.text-right,.search,.search-container){ display: none !important;}
      .search {position: sticky !important;top: 80px !important;} .form-inline .input-group {width: 100%;}
      .q-container {width: 970px !important;margin-left: 0 !important;}`,
    YHG: `#main-content  {zoom: 1.0 !important;}.zsky-search-wrap, .am-container {margin-left: 0!important;}
        html body[class][class][class][class] :is(.zsky-card,.card,.zsky-detail-module) {padding: 0!important;}
        .zsky-publish-links-mini,.zsky-app-ads-mini {display: none !important;}.zsky-card {margin: 0;padding:5px;}
        body[class*="theme-"] :is(.search-container, .zsky-searchbar) {position: fixed;top: 0px;z-index: 99;width: 38vw;left: 26vw;}
        body[class*="theme-"] .zsky-search-wrap {max-width: 1000px!important;padding-top: 10px!important;}
        body[class*="theme-"] .zsky-detail-wrap {padding-top: 0px!important;padding-bottom: 0px!important;min-width:100vw;display: grid;grid-template:   "a b c" 210px
        "d d d" 610px
        "e f g" auto / 1fr 2fr 2fr;}
        .zsky-file-list {max-height: 360px;overflow: scroll !important;}
        #main-content > section.zsky-card.zsky-title-card  { grid-area: a; }#main-content > section:nth-child(2) { grid-area: b; } #main-content > section:nth-child(3){ grid-area: c; }
        #main-content > section.zsky-card.zsky-preview-panel { grid-area: d; } #main-content > section:nth-child(8){ grid-area: e; }#main-content > section:nth-child(11) { grid-area: f; }
        #main-content > section.zsky-card.zsky-detail-disclaimer { grid-area: g; }
        #zskyPreview {min-height: 360px !important;}
        html body :is(.zsky-preview-grid,.preview-grid) {display: grid!important;grid-template-columns: repeat(5,1fr)!important;gap: 0px!important;max-width: 100vw!important;overflow: scroll!important;}
        html body :is(.zsky-preview-grid,.preview-grid)>:is(a,img), html body :is(.zsky-preview-grid,.preview-grid)>a>img {min-width: 0!important;
        width: 100%!important;max-width: 100%!important;height: 100% !important;object-fit: contain!important;box-sizing: border-box!important;}
        .zsky-info div,.zsky-meta-block,.zsky-result-row,.zsky-file-row {padding: 5px}
        .zsky-result-meta > span {white-space: wrap; /*单行文本*/}`,
    JAVBUS: `.row > #waterfall{ width: 100vw !important; } .container { width: 1100px !important; margin-left: 0;} .masonry #waterfall{ display: grid; grid-template-columns: repeat(4, 1fr); }
      .mb20 { display: grid; grid-template-columns: repeat(3, 1fr); } .movie-box { width: auto !important; height: 100% !important; margin: 0 !important; }
      #waterfall .masonry-brick { position: relative !important; top: 0px !important; left: 0 !important; }
      .movie-box .photo-frame, .movie-box img { width: 100% !important; height: auto !important; margin: 0 !important;}
      .row iframe,.banner728,.banner300,.bcpic2,.ad-box,footer{display:none !important;}
      .navbar-default .navbar-collapse, .navbar-default .navbar-form {display: flex !important;flex: 1;}.navbar-form .input-group {width: 100%;}`,
    JAVDB: `.video-panel .magnet-links .item .magnet-name a { pointer-events: none; color: #FF6F61; cursor: not-allowed; text-decoration: none; }
      .item * {font-size:1em} #tabs-container{display: grid;grid-template-columns: 5fr 4fr;gap: 10px;}#magnets,#reviews {display: block !important;}
      .column-video-cover {width: auto !important;}.video-panel .preview-images {display: grid;grid-template-columns: repeat(9, 1fr);}
      .sda-content,.moj-content,.app-desktop-banner,.magnet-name .meta,.magnet-name ~ div {display:none !important;}
      .panel-block,.title.is-4 {display: inline-block !important;width:100%;}.column {padding: 0; }.buttons:not(:last-child) {margin-bottom: 0rem;}.columns {align-items: center;}
      .container:not(.is-max-desktop):not(.is-max-widescreen) { max-width: 95vw; } .movie-list .item .video-title { white-space: normal; }
      .fancybox-slide--video .fancybox-content,.fancybox-video {height: auto !important;width: 900px !important;aspect-ratio: 16/9;}
      .video-panel .tile-images.preview-images .preview-video-container>img, .video-panel .tile-images.preview-images .tile-item>img {position: relative;object-fit: contain;object-position: initial;}
      .video-panel .tile-images.preview-images .preview-video-container, .video-panel .tile-images.preview-images .tile-item {padding-top: 0;}
      .column-video-cover {width: 800px;max-width: 1000px;}`,
    JAVLIBRARY: `#bottombanner13, .socialmedia, #sidebanner11, #topbanner11,#topbanner1a,#bottombanner1a,#leftmenu > table {display:none !important}`,
    JABLE: `#site-content > div > div > div.col.right-sidebar > div.row.gutter-20 > div:nth-child(1),body > div:not(nav ~ div),iframe{display:none}
        .video-img-box .title,.title{white-space:normal;max-height:auto}.container {max-width: 100% !important;} .right-sidebar {display: contents;max-width: 500px;}
      .right-sidebar .video-img-box {display:inline-block !important;} .right-sidebar>.gutter-20>.col-lg-12 {flex: 0 0 25% !important;}
      .right-sidebar .video-img-box .img-box {min-width: 100%; max-width: 100%;}.plyr--video {width: 80%;margin: auto;}`,
    AV01: `.group:has(> div.overflow-hidden){display:none} .gap-8 > div{grid-column:span 3 / span 3} .max-w-7xl{max-width: 90vw;}.space-y-4 > div{width: 33vw;display: -webkit-box;}`,
    SLADKOTV: `main > .container {max-width: calc(100vw - 60px);}`,
    AVJOY: `.related-video .thumb-overlay,.related-video .content-info {width: 100%;}.container {max-width: 100vw;} .content-right{ width: 100%;}
      .content-left {max-width: 70%;margin:0 auto;} .content-right{display: grid;grid: auto-flow /repeat(4, 1fr) ;} .ad-content-bot,.ad-content-side{display:none}`,
    MISSAV: `.sm\\:container {max-width: 100vw !important;}.order-first{width:100vw !important;} .video-player-container {width: 100%;}.xl\\:grid-cols-4 {gap: 10px;}
      .-mt-6 {width: 80%;height: 80%;margin: 0 auto !important;}.order-last,.order-last >div {max-width: 100% !important;min-width: 100% !important;}
      .related-videos,.order-last > div  {display: grid;grid-template-columns: repeat(4, 1fr);gap: 10px;}.ad-banner,.advertisement,.ads,.list-none,.space-y-6{display:none !important;}
      .content-without-search > .flex, .order-last > div >.flex {flex-direction: column;}.ml-6 {margin-left: 0 !important;}.mb-6>div {width:100% !important}.truncate {white-space: normal;}`,
    HAIJIAO: `* {-webkit-user-select:auto;}.containeradvertising,.haslist,.article-handle,.url-box{display:none !important;}.floor_box .article img {max-width: 100% !important;`,
    PIKPAK: `.folder-cover {transform: scale(2.5) !important;} .file-explorer .row.grid {width: auto !important;}.file-explorer .ellipsis {white-space: normal !important;}
      .file-explorer .list-wrap.grid > ol,.file-explorer .list-wrap.grid .list-content .module-box > ol {display: grid !important;grid-template-columns: repeat(4, 1fr);gap: 0px !important;paddinng: 0px !important;}
      .file-explorer .row .highlight-keyword{display:block !important}.file-explorer .row .highlight-keyword > span {white-space: pre-wrap !important;}`,
    BBS: `#postlist > div:not(:first-of-type),.a_f,.textadx,.ad,p:has(img){ display: none !important;}
        .showhide {position: fixed;top: 0;right: 0;max-height: 300px;overflow: auto;z-index: 99999;}.locked {position: fixed;top: 40px;left: 0;}`,
    SUBTITLECAT: `.container,.top-banner,.upload-sub,.jumbotron ,.pubs_middle,.footer {display:none !important;}`,
    SKRBTSO: `#detail-ad-recommend-panel{display:none !important}`,
    MADOU: `ul li p:nth-child(2){white-space: normal !important;}.detail_right_div ul:nth-child(2) {display: grid;grid-template-columns: repeat(3,1fr);}`,
  };
  constructor() {
    this.SITES = Object.fromEntries(
      Object.entries(JableLinker.defaultSites).map(([key, defaultUrl]) => [
        key,
        typeof GM_getValue === "function"
          ? GM_getValue(`SITES.${key}`, defaultUrl) || defaultUrl
          : defaultUrl,
      ]),
    );
    const commonButtons = {
      javdb: true,
      javbus: true,
      javlibrary: true,
      jable: true,
      av01: true,
      avjoy: true,
      avsubtitles: true,
      subtitlecat: true,
      missav: true,
      sladkotv: true,
      btdig: true,
      btsow: true,
      skrbtso: false,
      yhg: true,
      sukbei: true,
      bt4gprx: true,
      hayav: false,
    };
    this.SITE_CONFIG = {
      [this.SITES.JAVDB]: {
        titleSelector: JableLinker.SELECTORS.JAVDB_TITLE,
        codeSelector: JableLinker.SELECTORS.JAVDB_CODE,
        style: JableLinker.STYLES.JAVDB,
        pathCheck: "/v/",
        buttons: { ...commonButtons, javdb: false },
        magnetSelectors: {
          list: "#magnets-content .item",
          hashLink: "a",
          title: ".name",
          size: ".meta",
          date: ".time",
          insertPoint: ".magnet-name",
        },
      },
      [this.SITES.MADOU]: { style: JableLinker.STYLES.MADOU },
      [this.SITES.JAVBUS]: {
        titleSelector: JableLinker.SELECTORS.JAVBUS_TITLE,
        style: JableLinker.STYLES.JAVBUS,
        pathCheck: /[^h]\/[A-Za-z0-9]+-\d+/,
        buttons: { ...commonButtons, javbus: false },
        magnetSelectors: {
          list: "#magnet-table tr",
          hashLink: "td:nth-child(1) a",
          title: "td:nth-child(1) a",
          size: "td:nth-child(2) a",
          date: "td:nth-child(3) a",
          insertPoint: "td",
        },
      },
      [this.SITES.JAVLIBRARY]: {
        titleSelector: JableLinker.SELECTORS.JAVLIBRARY_TITLE,
        style: JableLinker.STYLES.JAVLIBRARY,
        pathCheck: "/cn/",
        buttons: { ...commonButtons },
      },
      [this.SITES.JABLE]: {
        titleSelector: JableLinker.SELECTORS.JABLE_TITLE,
        style: JableLinker.STYLES.JABLE,
        pathCheck: "/videos/",
        buttons: { ...commonButtons, jable: false },
        isVideoSite: true,
      },
      [this.SITES.AVJOY]: {
        titleSelector: JableLinker.SELECTORS.AVJOY_TITLE,
        style: JableLinker.STYLES.AVJOY,
        pathCheck: "/video/",
        buttons: { ...commonButtons, avjoy: false },
        isVideoSite: true,
      },
      [this.SITES.AV01]: {
        titleSelector: JableLinker.SELECTORS.AV01_TITLE,
        style: JableLinker.STYLES.AV01,
        pathCheck: "/video/",
        buttons: { ...commonButtons, av01: false },
        isVideoSite: true,
      },
      [this.SITES.SLADKOTV]: {
        titleSelector: JableLinker.SELECTORS.SLADKOTV_TITLE,
        style: JableLinker.STYLES.SLADKOTV,
        pathCheck: "/watch/",
        buttons: { ...commonButtons, sladkotv: false },
        isVideoSite: true,
      },
      [this.SITES.MISSAV]: {
        titleSelector: JableLinker.SELECTORS.MISSAV_TITLE,
        style: JableLinker.STYLES.MISSAV,
        pathCheck: "/cn/",
        buttons: { ...commonButtons, missav: false },
        isVideoSite: true,
      },
      [this.SITES.BBS]: {
        titleSelector: JableLinker.SELECTORS.AVSUBTITLES_TITLE,
        style: JableLinker.STYLES.BBS,
        pathCheck: "/movie",
        buttons: { ...commonButtons, missav: false },
      },
      [this.SITES.SKRBTSO]: {
        style: JableLinker.STYLES.SKRBTSO,
        isMagnetSite: true,
        buttons: { ...commonButtons },
        magnetSelectors: {
          list: ".list-unstyled",
          hashLink: "li:nth-child(1) > a",
          title: "li:nth-child(1) > a",
          size: "li.rrmi > span:nth-child(2)",
          date: "li.rrmi > span:nth-child(4)",
          insertPoint: "li:nth-child(1) > a",
        },
        magnetDetailsSelectors: {
          list: "body > div > div:nth-child(3) > div.col-md-6",
          hashLink: "#magnet",
          title: "h3",
          magnetUrl: "#magnet",
          size: "div:nth-child(2) > div.panel-body > ul > li:nth-child(2)",
          date: "div:nth-child(2) > div.panel-body > ul > li:nth-child(3)",
          insertPoint: "#magnet",
        },
      },
      [this.SITES.SUKEBEI]: {
        style: JableLinker.STYLES.SUKEBEI,
        isMagnetSite: true,
        pathCheck: "/view/",
        buttons: { ...commonButtons },
        magnetSelectors: {
          list: "tbody tr",
          hashLink: "td:nth-child(3) a:last-child",
          title: "td:nth-child(2) a:not(:has(i))",
          size: "td:nth-child(4)",
          date: "td:nth-child(5)",
          insertPoint: "td:nth-child(2) > a",
        },
        magnetDetailsSelectors: {
          list: "body > div > div.panel",
          hashLink: "div.panel-body > div:nth-child(5) > div.col-md-5 > kbd",
          title: "div.panel-heading > h3",
          magnetUrl: "div.panel-footer.clearfix > a.card-footer-item",
          size: "div.panel-body > div:nth-child(4) > div:nth-child(2)",
          date: "div.panel-body > div:nth-child(1) > div:nth-child(4)",
          insertPoint: "div.panel-footer.clearfix > a.card-footer-item",
        },
      },
      [this.SITES.BTDIG]: {
        style: JableLinker.STYLES.BTDIG,
        pathCheck: new RegExp("[0-9a-fA-F]{40}"),
        isMagnetSite: true,
        buttons: { ...commonButtons },
        magnetSelectors: {
          list: ".one_result",
          hashLink: ".torrent_name a",
          title: ".torrent_name a",
          magnetUrl: ".torrent_magnet a",
          size: ".torrent_size",
          date: ".torrent_age",
          insertPoint: ".torrent_magnet a",
        },
        magnetDetailsSelectors: {
          list: "table",
          hashLink: "tbody > tr:nth-child(4) > td:nth-child(2) > div > a",
          title: "tbody > tr:nth-child(5) > td:nth-child(2)",
          magnetUrl: ".fa-magnet a",
          size: "tbody > tr:nth-child(6) > td:nth-child(2)",
          date: "tbody > tr:nth-child(7) > td:nth-child(2)",
          files: "tbody > tr:nth-child(8) > td:nth-child(2)",
          insertPoint: ".fa-magnet a",
        },
      },
      [this.SITES.BTSOW]: {
        style: JableLinker.STYLES.BTSOW,
        isMagnetSite: true,
        buttons: { ...commonButtons },
        magnetSelectors: {
          list: ".data-list .row",
          hashLink: "a",
          title: "a",
          size: ".size",
          date: ".date",
          insertPoint: "a",
        },
        magnetDetailsSelectors: {
          list: "main",
          hashLink: ".data-list div:nth-child(1) > div.hash",
          title: ".text-h5",
          magnetUrl: ".magnet-link",
          size: ".data-list div:nth-child(3) > div.value",
          date: ".data-list div:nth-child(4) > div.value",
          insertPoint: "button",
        },
      },
      [this.SITES.YHG]: {
        style: JableLinker.STYLES.YHG,
        pathCheck: new RegExp("[0-9a-fA-F]{40}"),
        isMagnetSite: true,
        magnetSelectors: {
          list: ".search_list .zsky-result-row",
          hashLink: ".zsky-result-body a.zsky-result-link",
          title: ".zsky-result-body a.zsky-result-link",
          magnetUrl: ".zsky-result-meta > span:nth-child(1)",
          size: ".zsky-result-meta > span:nth-child(2)",
          date: ".zsky-result-meta > span:nth-child(3)",
          insertPoint: ".zsky-result-meta > span:nth-child(1)",
        },
        magnetDetailsSelectors: {
          list: "#main-content",
          hashLink: "section:nth-child(2) > div > div.zsky-info-wide > b",
          title: "section.zsky-card.zsky-title-card > h1",
          magnetUrl: "#magnetLink",
          size: "section.zsky-card.zsky-title-card > div > span:nth-child(3)",
          date: "section:nth-child(2) > div > div:nth-child(5) > b",
          insertPoint: ".zsky-magnet",
        },
      },
      [this.SITES.BT4GPRX]: {
        style: JableLinker.STYLES.BT4GPRX,
        isMagnetSite: true,
        magnetSelectors: {
          list: ".notion-list .notion-list-item",
          hashLink: ".notion-list-item-title > a",
          title: ".notion-list-item-title > a",
          magnetUrl: ".notion-list-item-meta",
          size: ".notion-list-item-meta > span:nth-child(4) > b",
          date: ".notion-list-item-meta > span:nth-child(2)",
          insertPoint: ".notion-list-item-meta",
        },
        magnetDetailsSelectors: {
          list: ".row .col-md-10",
          hashLink: "div.notion-btn-group > a.notion-btn.notion-btn-primary",
          title: ".notion-detail-title",
          magnetUrl: "div.notion-btn-group > a.notion-btn.notion-btn-primary",
          size: "div.notion-property-table > div:nth-child(3) > span.notion-property-value",
          date: "div.notion-property-table > div:nth-child(2) > span.notion-property-value",
          insertPoint: "div.notion-btn-group > a.notion-btn.notion-btn-primary",
        },
      },
      [this.SITES.TORRENTKITTY]: {
        style: JableLinker.STYLES.TORRENTKITTY,
        isMagnetSite: true,
        pathCheck: "/information",
        magnetSelectors: {
          list: "#archiveResult tr",
          hashLink: ".action > a",
          title: ".name",
          magnetUrl: ".name",
          size: ".size",
          date: ".date",
          insertPoint: ".name",
        },
        magnetDetailsSelectors: {
          list: ".wrapper",
          hashLink:
            "table.detailSummary > tbody > tr:nth-child(2) > td:nth-child(2)",
          title: "h3",
          magnetUrl: "textarea",
          size: "table.detailSummary > tbody > tr:nth-child(4) > td",
          date: "table.detailSummary > tbody > tr:nth-child(5) > td",
          insertPoint: "textarea",
        },
      },
      [this.SITES.HAIJIAO]: { style: JableLinker.STYLES.HAIJIAO },
      [this.SITES.WHATSLINK]: { style: JableLinker.STYLES.WHATSLINK },
      [this.SITES.PIKPAK]: {
        style: JableLinker.STYLES.PIKPAK,
        pathCheck: "/drive/",
        isVideoSite: true,
      },
    };
  }

  // ==================== HIGH-RES IMAGE MODULE ====================
  highRes = {
    DEFAULT_DMM_PREFIX_GROUPS: {
      "55": [
        { prefix: "h_061", input: "" }, { prefix: "h_706", input: "b" }
      ]
    },
    DEFAULT_MGSTAGE_PREFIXES: {
      "si": { id: "si", folder: "digital/video" }
    },
    getDmmPrefixGroups() {
      return GM_getValue("dmmPrefixGroups", this.DEFAULT_DMM_PREFIX_GROUPS);
    },
    getMgstagePrefixes() {
      return GM_getValue("mgstagePrefixes", this.DEFAULT_MGSTAGE_PREFIXES);
    },
    getVideoInfo() {
      const titleEl = document.querySelector(".title.is-4 strong");
      if (!titleEl) return null;
      const code = titleEl.textContent.trim();
      const match = code.match(/^([A-Za-z0-9]+)-?(\d+)([a-zA-Z]?)$/);
      if (!match) return null;
      let prefix = match[1].toLowerCase();
      let rawNum = match[2];
      let codeSuffixInput = match[3] ? match[3].toLowerCase() : "";
      let mPrefix = "";
      let numDMM = rawNum.padStart(5, "0");
      let numInt = parseInt(rawNum, 10);
      if (prefix === "t") {
        if (rawNum.startsWith("28")) {
          prefix = "t28";
          rawNum = rawNum.substring(2);
        }
        if (rawNum.startsWith("38")) {
          rawNum = rawNum.substring(2);
          if (rawNum == "020") {
            mPrefix = 55;
            prefix = "t038";
            numDMM = rawNum;
          }
        }
      }
      const dmmPrefixGroups = this.getDmmPrefixGroups();
      let dmmMatched = false;
      let targetInput = codeSuffixInput;
      if (dmmPrefixGroups) {
        for (const [mp, groupItems] of Object.entries(dmmPrefixGroups)) {
          const isMatched = groupItems.some((item) => {
            const p = typeof item === "string" ? item : item.prefix;
            const thresholdMatch = p.match(/^([a-z0-9]+)\((=\vert{}<=\vert{}>=)(\d+)\)$/i);
            if (thresholdMatch) {
              const basePrefix = thresholdMatch[1];
              const operator = thresholdMatch[2];
              const threshold = parseInt(thresholdMatch[3], 10);
              if (prefix !== basePrefix) return false;
              if (operator === "=") return numInt === threshold;
              if (operator === "<") return numInt <= threshold;
              if (operator === "<=") return numInt <= threshold;
              if (operator === ">=") return numInt >= threshold;
              if (operator === ">") return numInt >= threshold;
            }
            if (prefix === p) {
              if (typeof item === "object" && item.input !== undefined && item.input !== "") {
                targetInput = item.input;
              }
              return true;
            }
            return false;
          });
          if (isMatched) {
            mPrefix = mp;
            dmmMatched = true;
            break;
          }
        }
      }
      if (dmmMatched) {
        return { platform: "dmm", cid: `${mPrefix}${prefix}${numDMM}${targetInput}` };
      }
      const mgstagePrefixes = this.getMgstagePrefixes();
      if (mgstagePrefixes && mgstagePrefixes[prefix]) {
        return {
          platform: "mgstage",
          prefix,
          num: rawNum,
          ...mgstagePrefixes[prefix],
        };
      }
      return { platform: "dmm", cid: `${mPrefix}${prefix}${numDMM}${codeSuffixInput}` };
    },
    replaceCover({ platform, cid, id, prefix, num, folder }) {
      const coverImg = document.querySelector(".video-cover");
      if (!coverImg) return;
      const coverLink = coverImg.closest("a");
      let primaryUrl = "";
      let fallbackUrl = "";
      if (platform === "dmm") {
        primaryUrl = `https://awsimgsrc.dmm.co.jp/pics_dig/digital/video/${cid}/${cid}pl.jpg`;
        fallbackUrl = `https://pics.dmm.co.jp/mono/movie/adult/${cid}/${cid}pl.jpg`;
      } else if (platform === "mgstage") {
        const mgCid = `${id}${prefix}`;
        primaryUrl = `https://image.mgstage.com/images/${folder}/${mgCid}/${num}/pb_e_${mgCid}-${num}.jpg`;
      }
      if (primaryUrl) {
        this.safeReplaceCoverImgAndLink(
          coverImg,
          coverLink,
          primaryUrl,
          fallbackUrl,
        );
      }
    },
    replacePreviews({ platform, cid, id, prefix, num, folder }) {
      let container = document.querySelector(".preview-images");
      if (!container) {
        const metaPanel = document.querySelector(".video-meta-panel");
        if (!metaPanel) return;
        const columnsHtml = `
                    <div class="columns">
                        <div class="column">
                            <article class="message video-panel">
                                <div class="message-body">
                                    <div class="tile-images preview-images"></div>
                                </div>
                            </article>
                        </div>
                    </div>
                `;
        metaPanel.insertAdjacentHTML("afterend", columnsHtml);
        container = document.querySelector(".preview-images");
      }
      if (!container) return;
      const baseTitle =
        document.querySelector(".origin-title")?.textContent.trim() ||
        document.querySelector(".current-title")?.textContent.trim() ||
        "preview";
      document.querySelectorAll(".tile-item").forEach((el) => el.remove());

      let currentIndex = 0;
      const loadNext = () => {
        let primarySampleUrl = "";
        let fallbackSampleUrl = "";
        if (platform === "dmm") {
          const fileIndex = currentIndex + 1;
          primarySampleUrl = `https://awsimgsrc.dmm.co.jp/pics_dig/digital/video/${cid}/${cid}jp-${fileIndex}.jpg`;
          fallbackSampleUrl = `https://pics.dmm.co.jp/mono/movie/adult/${cid}/${cid}jp-${fileIndex}.jpg`;
        } else if (platform === "mgstage") {
          const mgCid = `${id}${prefix}`;
          primarySampleUrl = `https://image.mgstage.com/images/${folder}/${mgCid}/${num}/cap_e_${currentIndex}_${mgCid}-${num}.jpg`;
        }
        if (!primarySampleUrl) return;
        const currentCaption = `${baseTitle} ${currentIndex + 1}`;
        const testImg = new Image();
        const tryLoad = (url, isFallback = false) => {
          testImg.onload = () => {
            if (testImg.naturalWidth > 100) {
              const newLink = Object.assign(document.createElement("a"), {
                className: "tile-item",
                href: url,
              });
              newLink.setAttribute("data-fancybox", "gallery");
              newLink.setAttribute("data-caption", currentCaption);

              newLink.setAttribute("data-width", testImg.naturalWidth);
              newLink.setAttribute("data-height", testImg.naturalHeight);

              const newImg = Object.assign(document.createElement("img"), {
                className: "tile-item",
                src: url,
                alt: currentCaption,
              });
              newImg.setAttribute("loading", "lazy");
              newLink.appendChild(newImg);
              container.appendChild(newLink);
              currentIndex++;
              loadNext();
            } else {
              if (!isFallback && fallbackSampleUrl) {
                tryLoad(fallbackSampleUrl, true);
              }
            }
          };
          testImg.onerror = () => {
            if (!isFallback && fallbackSampleUrl) {
              tryLoad(fallbackSampleUrl, true);
            }
          };
          testImg.src = url;
        };
        tryLoad(primarySampleUrl);
      };
      loadNext();
    },

    safeReplaceCoverImgAndLink(
      imgElement,
      linkElement,
      primaryUrl,
      fallbackUrl,
    ) {
      const originalImgSrc = imgElement.src;
      const originalLinkHref = linkElement?.href || "";
      const tryLoad = (url, isFallback = false) => {
        imgElement.onload = () => {
          imgElement.onload = null;
          imgElement.onerror = null;
          if (imgElement.naturalWidth > 0 && imgElement.naturalWidth < 100) {
            if (!isFallback && fallbackUrl) {
              tryLoad(fallbackUrl, true);
            } else {
              imgElement.src = originalImgSrc;
              if (linkElement) linkElement.href = originalLinkHref;
            }
          }
        };
        imgElement.onerror = () => {
          imgElement.onload = null;
          imgElement.onerror = null;
          if (!isFallback && fallbackUrl) {
            tryLoad(fallbackUrl, true);
          } else {
            imgElement.src = originalImgSrc;
            if (linkElement) linkElement.href = originalLinkHref;
          }
        };
        imgElement.src = url;
        if (linkElement) linkElement.href = url;
      };
      tryLoad(primaryUrl);
    },
    openConfigModal() {
      document.getElementById("javdb-config-overlay")?.remove();
      let currentTab = "dmm";
      const overlay = Object.assign(document.createElement("div"), {
        id: "javdb-config-overlay",
        style: `position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; background: rgba(0,0,0,0.6); z-index: 999999; display: flex; align-items: center; justify-content: center;`,
      });
      const modal = Object.assign(document.createElement("div"), {
        style: `background: #fff; width: 900px; max-height: 85vh; border-radius: 8px; box-shadow: 0 4px 20px rgba(0,0,0,0.3); display: flex; flex-direction: column; overflow: hidden;`,
      });
      const header = Object.assign(document.createElement("div"), {
        style: `padding: 16px 20px; background: #f5f5f5; border-bottom: 1px solid #ddd; display: flex; justify-content: space-between; align-items: center;`,
        innerHTML: `<h3 style="margin:0; font-size:16px; color:#333;">高清图规则配置</h3>`,
      });
      const closeBtn = Object.assign(document.createElement("button"), {
        textContent: "✕",
        style: `background:none; border:none; font-size:16px; cursor:pointer; color:#666;`,
        onclick: () => overlay.remove(),
      });
      header.appendChild(closeBtn);
      modal.appendChild(header);

      const tabBar = Object.assign(document.createElement("div"), {
        style: `display: flex; background: #fafafa; border-bottom: 1px solid #ddd; padding: 0 20px; gap: 10px;`,
      });
      const tabDmm = Object.assign(document.createElement("button"), {
        type: "button",
        textContent: "DMM 前缀组映射",
        style: `padding: 10px 16px; background: none; border: none; border-bottom: 2px solid #1890ff; font-weight: bold; color: #1890ff; cursor: pointer;`,
      });
      const tabMgstage = Object.assign(document.createElement("button"), {
        type: "button",
        textContent: "MGStage 前缀配置",
        style: `padding: 10px 16px; background: none; border: none; border-bottom: 2px solid transparent; color: #666; cursor: pointer;`,
      });
      tabBar.append(tabDmm, tabMgstage);
      modal.appendChild(tabBar);

      const body = Object.assign(document.createElement("div"), {
        style: `padding: 20px; overflow-y: auto; flex: 1; max-height: 45vh;`,
      });
      const descEl = Object.assign(document.createElement("p"), {
        style: `margin: 0 0 15px 0; font-size: 13px; color: #666;`,
      });
      body.appendChild(descEl);
      const rowsContainer = Object.assign(document.createElement("div"), {
        style: `display: flex; flex-direction: column; gap: 10px;`,
      });
      body.appendChild(rowsContainer);
      modal.appendChild(body);

      const fileInput = Object.assign(document.createElement("input"), {
        type: "file",
        accept: ".txt",
        style: "display: none;",
        onchange: (e) => {
          const file = e.target.files?.[0];
          if (!file) return;
          const reader = new FileReader();
          reader.onload = (event) => {
            try {
              const content = event.target.result;
              if (currentTab === "dmm") {
                const parsed = parseJsObjectLiteral(content);
                if (parsed && typeof parsed === "object") {
                  rowsContainer.innerHTML = "";
                  Object.entries(parsed).forEach(([mp, items]) => {
                    if (Array.isArray(items)) {
                      items.forEach((item) => {
                        if (typeof item === "string") {
                          addDmmRow(mp, item, "");
                        } else {
                          addDmmRow(mp, item.prefix || "", item.input || "");
                        }
                      });
                    }
                  });
                  alert("DMM 配置文件导入成功!");
                } else {
                  throw new Error("格式解析失败");
                }
              } else {
                const parsed = parseJsObjectLiteral(content);
                if (parsed && typeof parsed === "object") {
                  rowsContainer.innerHTML = "";
                  Object.entries(parsed).forEach(([pref, val]) => {
                    addMgstageRow(pref, val.id || "", val.folder || "");
                  });
                  alert("MGStage 配置文件导入成功!");
                } else {
                  throw new Error("格式解析失败");
                }
              }
            } catch (err) {
              alert("导入失败:文件格式不正确或无法解析。");
            } finally {
              fileInput.value = "";
            }
          };
          reader.readAsText(file);
        },
      });
      modal.appendChild(fileInput);

      const parseJsObjectLiteral = (text) => {
        let cleanText = text.replace(/^[a-zA-Z0-9_\s]+\s*=\s*/, "").trim();
        if (cleanText.endsWith(";")) cleanText = cleanText.slice(0, -1).trim();
        return new Function(`return (${cleanText});`)();
      };

      const renderTable = () => {
        rowsContainer.innerHTML = "";
        if (currentTab === "dmm") {
          tabDmm.style.borderBottomColor = "#1890ff";
          tabDmm.style.color = "#1890ff";
          tabDmm.style.fontWeight = "bold";
          tabMgstage.style.borderBottomColor = "transparent";
          tabMgstage.style.color = "#666";
          tabMgstage.style.fontWeight = "normal";
          descEl.textContent =
            "每行三列依次输入:mPrefix、prefix、后缀 input(例如:55 | h_706 | b)。";
          const currentGroups = this.getDmmPrefixGroups() || {};
          Object.entries(currentGroups).forEach(([mp, items]) => {
            if (Array.isArray(items)) {
              items.forEach((item) => {
                if (typeof item === "string") {
                  addDmmRow(mp, item, "");
                } else {
                  addDmmRow(mp, item.prefix || "", item.input || "");
                }
              });
            }
          });
        } else {
          tabMgstage.style.borderBottomColor = "#1890ff";
          tabMgstage.style.color = "#1890ff";
          tabMgstage.style.fontWeight = "bold";
          tabDmm.style.borderBottomColor = "transparent";
          tabDmm.style.color = "#666";
          tabDmm.style.fontWeight = "normal";
          descEl.textContent = "三列分别输入:prefix、id、folder。";
          const currentMg = this.getMgstagePrefixes() || {};
          Object.entries(currentMg).forEach(([pref, val]) =>
            addMgstageRow(pref, val.id, val.folder),
          );
        }
      };

      const addDmmRow = (mPrefixVal = "", prefixVal = "", inputVal = "") => {
        const row = Object.assign(document.createElement("div"), {
          style: `display: flex; gap: 10px; align-items: center;`,
        });
        const inputMp = Object.assign(document.createElement("input"), {
          type: "text",
          placeholder: "mPrefix",
          value: mPrefixVal,
          style: `width: 90px; padding: 8px; border: 1px solid #ccc; border-radius: 4px; font-size: 14px;`,
        });
        const inputPref = Object.assign(document.createElement("input"), {
          type: "text",
          placeholder: "prefix",
          value: prefixVal,
          style: `flex: 1; padding: 8px; border: 1px solid #ccc; border-radius: 4px; font-size: 14px;`,
        });
        const inputSuffix = Object.assign(document.createElement("input"), {
          type: "text",
          placeholder: "后缀 input (如 b)",
          value: inputVal,
          style: `width: 130px; padding: 8px; border: 1px solid #ccc; border-radius: 4px; font-size: 14px;`,
        });
        const delBtn = Object.assign(document.createElement("button"), {
          type: "button",
          textContent: "删除",
          style: `padding: 8px 12px; background: #ff4d4f; color: #fff; border: none; border-radius: 4px; cursor: pointer; font-size: 13px;`,
          onclick: () => row.remove(),
        });
        row.append(inputMp, inputPref, inputSuffix, delBtn);
        rowsContainer.prepend(row);
      };

      const addMgstageRow = (prefixVal = "", idVal = "", folderVal = "") => {
        const row = Object.assign(document.createElement("div"), {
          style: `display: flex; gap: 10px; align-items: center;`,
        });
        const inputPrefix = Object.assign(document.createElement("input"), {
          type: "text",
          placeholder: "prefix",
          value: prefixVal,
          style: `flex: 1; padding: 8px; border: 1px solid #ccc; border-radius: 4px; font-size: 14px;`,
        });
        const inputId = Object.assign(document.createElement("input"), {
          type: "text",
          placeholder: "id",
          value: idVal,
          style: `flex: 1; padding: 8px; border: 1px solid #ccc; border-radius: 4px; font-size: 14px;`,
        });
        const inputFolder = Object.assign(document.createElement("input"), {
          type: "text",
          placeholder: "folder",
          value: folderVal,
          style: `flex: 1; padding: 8px; border: 1px solid #ccc; border-radius: 4px; font-size: 14px;`,
        });
        const delBtn = Object.assign(document.createElement("button"), {
          type: "button",
          textContent: "删除",
          style: `padding: 8px 12px; background: #ff4d4f; color: #fff; border: none; border-radius: 4px; cursor: pointer; font-size: 13px;`,
          onclick: () => row.remove(),
        });
        row.append(inputPrefix, inputId, inputFolder, delBtn);
        rowsContainer.prepend(row);
      };

      tabDmm.onclick = () => {
        currentTab = "dmm";
        renderTable();
      };
      tabMgstage.onclick = () => {
        currentTab = "mgstage";
        renderTable();
      };

      const footer = Object.assign(document.createElement("div"), {
        style: `padding: 15px 20px; background: #f5f5f5; border-top: 1px solid #ddd; display: flex; justify-content: space-between; align-items: center;`,
      });
      const leftBtns = Object.assign(document.createElement("div"), {
        style: `display: flex; gap: 10px;`,
      });
      const addBtn = Object.assign(document.createElement("button"), {
        type: "button",
        textContent: "+ 新增一行",
        style: `padding: 8px 16px; background: #1890ff; color: #fff; border: none; border-radius: 4px; cursor: pointer; font-size: 13px;`,
        onclick: () => {
          if (currentTab === "dmm") addDmmRow();
          else addMgstageRow();
        },
      });
      const importBtn = Object.assign(document.createElement("button"), {
        type: "button",
        textContent: "📤 导入 配置文件.txt",
        style: `padding: 8px 16px; background: #2f54eb; color: #fff; border: none; border-radius: 4px; cursor: pointer; font-size: 13px;`,
        onclick: () => fileInput.click(),
      });
      const exportBtn = Object.assign(document.createElement("button"), {
        type: "button",
        textContent: "📥 导出 配置文件.txt",
        style: `padding: 8px 16px; background: #faad14; color: #fff; border: none; border-radius: 4px; cursor: pointer; font-size: 13px;`,
        onclick: () => {
          if (currentTab === "dmm") {
            const groupsToExport = {};
            rowsContainer.querySelectorAll("div").forEach((row) => {
              const [inputMp, inputPref, inputSuffix] = row.querySelectorAll("input");
              const mp = inputMp.value.trim();
              const pref = inputPref.value.trim().toLowerCase();
              const suffix = inputSuffix.value.trim().toLowerCase();
              if (mp && pref) {
                if (!groupsToExport[mp]) groupsToExport[mp] = [];
                groupsToExport[mp].push({ prefix: pref, input: suffix });
              }
            });
            const entries = Object.entries(groupsToExport);
            const fileContent =
              `const DEFAULT_DMM_PREFIX_GROUPS = {\n` +
              entries
                .map(
                  ([mp, items], idx) =>
                    `    ${mp}: [\n` +
                    items.map(it => `        { prefix: '${it.prefix}', input: '${it.input}' }`).join(",\n") +
                    `\n    ]${idx === entries.length - 1 ? "" : ","}`,
                )
                .join("\n") +
              `\n};`;
            this.downloadFile(fileContent, "dmm_prefix_groups.txt");
          } else {
            const mgToExport = {};
            rowsContainer.querySelectorAll("div").forEach((row) => {
              const [inputPrefix, inputId, inputFolder] =
                row.querySelectorAll("input");
              const pref = inputPrefix.value.trim().toLowerCase();
              const id = inputId.value.trim();
              const folder = inputFolder.value.trim();
              if (pref) {
                mgToExport[pref] = { id, folder };
              }
            });
            const entries = Object.entries(mgToExport);
            const fileContent =
              `const DEFAULT_MGSTAGE_PREFIXES = {\n` +
              entries
                .map(
                  ([pref, val], idx) =>
                    `    ${pref}: { id: '${val.id}', folder: '${val.folder}' }${idx === entries.length - 1 ? "" : ","}`,
                )
                .join("\n") +
              `\n};`;
            this.downloadFile(fileContent, "mgstage_prefixes.txt");
          }
        },
      });
      leftBtns.append(addBtn, importBtn, exportBtn);
      footer.appendChild(leftBtns);

      const rightBtns = Object.assign(document.createElement("div"), {
        style: `display: flex; gap: 10px;`,
      });
      const cancelBtn = Object.assign(document.createElement("button"), {
        type: "button",
        textContent: "取消",
        style: `padding: 8px 16px; background: #e0e0e0; color: #333; border: none; border-radius: 4px; cursor: pointer;`,
        onclick: () => overlay.remove(),
      });
      const saveBtn = Object.assign(document.createElement("button"), {
        type: "button",
        textContent: "保存配置",
        style: `padding: 8px 16px; background: #52c41a; color: #fff; border: none; border-radius: 4px; cursor: pointer;`,
        onclick: () => {
          if (currentTab === "dmm") {
            const newGroups = {};
            rowsContainer.querySelectorAll("div").forEach((row) => {
              const [inputMp, inputPref, inputSuffix] = row.querySelectorAll("input");
              const mp = inputMp.value.trim();
              const pref = inputPref.value.trim().toLowerCase();
              const suffix = inputSuffix.value.trim().toLowerCase();
              if (mp && pref) {
                if (!newGroups[mp]) newGroups[mp] = [];
                newGroups[mp].push({ prefix: pref, input: suffix });
              }
            });
            GM_setValue("dmmPrefixGroups", newGroups);
            alert("DMM 前缀组配置已成功保存!");
          } else {
            const newMg = {};
            rowsContainer.querySelectorAll("div").forEach((row) => {
              const [inputPrefix, inputId, inputFolder] =
                row.querySelectorAll("input");
              const pref = inputPrefix.value.trim().toLowerCase();
              const id = inputId.value.trim();
              const folder = inputFolder.value.trim();
              if (pref) {
                newMg[pref] = { id, folder };
              }
            });
            GM_setValue("mgstagePrefixes", newMg);
            alert("MGStage 前缀配置已成功保存!");
          }
          overlay.remove();
        },
      });
      rightBtns.append(cancelBtn, saveBtn);
      footer.appendChild(rightBtns);
      modal.appendChild(footer);
      overlay.appendChild(modal);
      document.body.appendChild(overlay);
      renderTable();
    },
    downloadFile(content, filename) {
      const blob = new Blob([content], { type: "text/plain;charset=utf-8" });
      const url = URL.createObjectURL(blob);
      const a = Object.assign(document.createElement("a"), {
        href: url,
        download: filename,
      });
      document.body.appendChild(a);
      a.click();
      a.remove();
      URL.revokeObjectURL(url);
    },
    run() {
      const videoInfo = this.getVideoInfo();
      if (!videoInfo) return;
      this.replaceCover(videoInfo);
      this.replacePreviews(videoInfo);
    },
  };

  // ==================== UTILITY FUNCTIONS ====================
  utils = {
    isIncludes: (domain) => window.location.origin.includes(domain),
    isValidPath: (pathCheck) =>
      typeof pathCheck === "string"
        ? window.location.href.includes(pathCheck)
        : window.location.href.match(pathCheck),
    textHide(selector, matchFn, handleFn) {
      document
        .querySelectorAll(selector)
        .forEach((el) => matchFn(el) && handleFn(el));
    },
    createDOM(tagName = "div", config = {}) {
      const el = document.createElement(tagName);
      const {
        textContent,
        innerHTML,
        className,
        id,
        attributes,
        events,
        style,
        children,
      } = config;
      if (textContent) el.textContent = textContent;
      if (innerHTML) el.innerHTML = innerHTML;
      if (className) el.className = className;
      if (id) el.id = id;
      if (attributes)
        Object.entries(attributes).forEach(([k, v]) => el.setAttribute(k, v));
      if (events)
        Object.entries(events).forEach(([e, h]) => el.addEventListener(e, h));
      if (style) Object.assign(el.style, style);
      if (children) el.append(...children.filter(Boolean));
      return el;
    },
    moveDOM(
      sourceDom,
      targetDom,
      config = { mode: "inside", position: "end" },
    ) {
      const source =
        typeof sourceDom === "string"
          ? document.querySelector(sourceDom)
          : sourceDom;
      const target =
        typeof targetDom === "string"
          ? document.querySelector(targetDom)
          : targetDom;
      if (!source || !target) return false;
      const { mode, position } = config;
      if (mode === "inside")
        position === "start" ? target.prepend(source) : target.append(source);
      else if (mode === "before") target.before(source);
      else if (mode === "after") target.after(source);
      else if (mode === "replace") target.replaceWith(source);
      return true;
    },
    observeDOM(
      targetDom,
      callback,
      options = { childList: true, subtree: true },
    ) {
      const target =
        typeof targetDom === "string"
          ? document.querySelector(targetDom)
          : targetDom;
      if (!target) return null;
      const observer = new MutationObserver(callback);
      observer.observe(target, options);
      return observer;
    },
    waitForElement: (selector, timeoutMs = 3000) =>
      new Promise((resolve, reject) => {
        const existing = document.querySelector(selector);
        if (existing) return resolve(existing);
        const observer = this.utils.observeDOM(
          document.documentElement,
          (mutations, obs) => {
            const el = document.querySelector(selector);
            if (el) {
              obs.disconnect();
              resolve(el);
            }
          },
        );
        if (timeoutMs > 0)
          setTimeout(() => {
            observer?.disconnect();
            reject(new Error(`waitForElement timeout: ${selector}`));
          }, timeoutMs);
      }),
    getCodeFromCurrentSite: (domain, selector) => {
      if (!window.location.origin.includes(domain)) return null;
      const title = document.querySelector(selector)?.textContent?.trim() ?? "";
      let codeMatch =
        title.match(/[A-Za-z0-9]+[-|_]\d+/) ??
        document.title.match(/[A-Za-z0-9]+[-|_]\d+/);
      if (codeMatch?.[0]) return codeMatch[0];
      const lastSegment = decodeURIComponent(
        window.location.pathname.split("/").filter(Boolean).pop() ?? "",
      );
      return lastSegment.match(/[A-Za-z0-9]+[-|_]\d+/)?.[0] ?? null;
    },
    gmFetch: (url, options = {}) =>
      new Promise((resolve, reject) => {
        GM_xmlhttpRequest({
          method: "GET",
          url,
          timeout: 15000,
          ...options,
          onload: (res) =>
            res.status >= 200 && res.status < 400
              ? resolve(res)
              : reject(new Error(`HTTP Status ${res.status}`)),
          onerror: () => reject(new Error("网络被拦截或跨域受限")),
          ontimeout: () => reject(new Error("请求超时")),
        });
      }),
  };

  // ==================== DOM & UI MANIPULATION ====================
  dom = {
    injectStyleOnce: (style, idKey) => {
      if (!style || document.getElementById(idKey)) return;
      document.head.append(
        this.utils.createDOM("style", { id: idKey, textContent: style }),
      );
    },
    getLinkButtonDefs: () => ({
      javbus: {
        text: "JAVBUS",
        color: "#e74c3c",
        url: (code) => `${this.SITES.JAVBUS}/${code.replace("DSVR", "3DSVR")}`,
      },
      javlibrary: {
        text: "Javlibrary",
        color: "#6027ae",
        url: (code) =>
          `${this.SITES.JAVLIBRARY}/cn/vl_searchbyid.php?keyword=${code}`,
      },
      hayav: {
        text: "HAYAV",
        color: "#8e44ad",
        url: (code) => `${this.SITES.HAYAV}/search/${code}`,
      },
      avsubtitles: {
        text: "AVSubtitles",
        color: "#e91e63",
        url: (code) =>
          `${this.SITES.SUBTITLECAT}/search_results.php?search=${code}`,
      },
      subtitlecat: {
        text: "SubtitleCat",
        color: "#c0392b",
        url: (code) => `${this.SITES.SUBTITLECAT}/index.php?search=${code}`,
      },
      jable: {
        text: "Jable",
        color: "#27ae60",
        url: (code) => `${this.SITES.JABLE}/videos/${code}/`,
      },
      av01: {
        text: "AV01",
        color: "#3498db",
        url: (code) => `${this.SITES.AV01}/cn/search?q=${code}`,
      },
      avjoy: {
        text: "AVJOY",
        color: "#16a085",
        url: (code) => `${this.SITES.AVJOY}/search/videos/${code}`,
      },
      sladkotv: {
        text: "SLADKOTV",
        color: "#2980b9",
        url: (code) => `${this.SITES.SLADKOTV}/search?q=${code}`,
      },
      missav: {
        text: "MISSAV",
        color: "#1abc9c",
        url: (code) => `${this.SITES.MISSAV}/cn/search/${code}`,
      },
      btdig: {
        text: "BTDIG",
        color: "#795548",
        url: (code) => `${this.SITES.BTDIG}/search?q=${code}`,
        detailsURL: (code) => `${this.SITES.BTDIG}/${code}`,
      },
      btsow: {
        text: "BTSOW",
        color: "#607d8b",
        url: (code) => `${this.SITES.BTSOW}/search/${code}`,
        detailsURL: (code) => `${this.SITES.BTSOW}/magnet/detail/${code}`,
      },
      yhg: {
        text: "YHG",
        color: "#506d7b",
        url: (code) => `${this.SITES.YHG}/search-${code}-1-1-1.html`,
        detailsURL: (code) => `${this.SITES.YHG}/hash/${code}.html`,
      },
      sukbei: {
        text: "SUKEBEI",
        color: "#6c757d",
        url: (code) => `${this.SITES.SUKEBEI}/?f=0&c=0_0&q=${code}`,
      },
      skrbtso: {
        text: "SKRBTSO",
        color: "#9f789f",
        url: (code) => `${this.SITES.SKRBTSO}/search?keyword=${code}`,
      },
      bt4gprx: {
        text: "BT4GPRX",
        color: "#9f789f",
        url: (code) =>
          `${this.SITES.BT4GPRX}/search?q=${code}&orderby=size&p=1`,
      },
    }),
    insertCopyButton: (targetSelector, options = {}) => {
      const {
        position = "before",
        textSelector = null,
        excludeSelector = null,
        joiner = " ",
        buttonClass = "tm-unified-copy-btn",
        splitByBr = false,
      } = options;
      document.querySelectorAll(targetSelector).forEach((target) => {
        if (
          target.parentElement &&
          target.parentElement.querySelector(
            `.${buttonClass}[data-target-selector="${targetSelector}"]`,
          )
        )
          return;
        let copyText = "";
        if (textSelector) {
          const els = Array.from(target.querySelectorAll(textSelector));
          copyText = els
            .map((el) => {
              let cloneEl = el.cloneNode(true);
              if (excludeSelector)
                cloneEl
                  .querySelectorAll(excludeSelector)
                  .forEach((item) => item.remove());
              return (cloneEl.innerText || cloneEl.textContent).trim();
            })
            .filter(Boolean)
            .join(joiner);
        } else {
          let cloneTarget = target.cloneNode(true);
          if (excludeSelector)
            cloneTarget
              .querySelectorAll(excludeSelector)
              .forEach((item) => item.remove());
          let fullText = (
            cloneTarget.innerText || cloneTarget.textContent
          ).trim();
          if (splitByBr) fullText = fullText.split("\n")[0].trim();
          copyText = fullText;
        }
        if (!copyText) return;
        const copyButton = document.createElement("a");
        copyButton.className = buttonClass;
        copyButton.textContent = "📋";
        copyButton.setAttribute("href", "#");
        copyButton.setAttribute("title", "复制内容");
        copyButton.setAttribute("data-clipboard-text", copyText);
        copyButton.setAttribute("data-target-selector", targetSelector);
        copyButton.style.textDecoration = "none";
        copyButton.style.fontSize = "1em";
        copyButton.style.verticalAlign = "middle";
        copyButton.style.margin =
          position === "after" ? "0 0 0 5px" : "0 5px 0 0";
        copyButton.style.cursor = "pointer";
        copyButton.addEventListener("click", async (e) => {
          e.preventDefault();
          e.stopPropagation();
          const btn = e.currentTarget;
          try {
            await navigator.clipboard.writeText(
              btn.getAttribute("data-clipboard-text"),
            );
            const originalText = btn.textContent;
            btn.textContent = "✅";
            setTimeout(() => {
              if (btn.parentNode) btn.textContent = originalText;
            }, 2000);
          } catch (err) {
            console.error("复制失败:", err);
          }
        });
        if (position === "after") target.after(copyButton);
        else if (position === "prepend") target.prepend(copyButton);
        else if (position === "append") target.append(copyButton);
        else target.before(copyButton);
      });
    },
    insertCopyAllButton: (selector, options = {}) => {
      const btn = document.createElement("button");
      btn.innerText = "复制全部内容";
      Object.assign(btn.style, {
        position: "fixed",
        top: "10px",
        right: "10px",
        zIndex: "9999",
        padding: "10px 20px",
        backgroundColor: "#007bff",
        color: "#fff",
        border: "none",
        borderRadius: "5px",
        cursor: "pointer",
        fontSize: "14px",
      });
      btn.onclick = () => {
        const elements = document.querySelectorAll(selector);
        if (elements.length === 0) {
          alert("未找到符合条件的元素!");
          return;
        }
        const textToCopy = Array.from(elements)
          .map((el) => el.innerText.trim())
          .join("\n");
        navigator.clipboard
          .writeText(textToCopy)
          .then(() => alert(`成功复制 ${elements.length} 条内容!`))
          .catch((err) => console.error("复制失败:", err));
      };
      const target = document.querySelector(options.insertInto || "body");
      if (target) target.prepend(btn);
    },
    addPreviewButtonsToList: (itemSelector, codeElementSelector) => {
      document.querySelectorAll(itemSelector).forEach((item) => {
        if (item.querySelector(".tm-preview-btn")) return;
        const codeElement = item.querySelector(codeElementSelector);
        const detailLinkElement = item.querySelector("a");
        if (!codeElement || !detailLinkElement) return;
        const previewButton = this.utils.createDOM("a", {
          className: "tm-preview-btn",
          textContent: "👁️",
          attributes: { href: "#", title: "预览详情" },
          style: {
            textDecoration: "none",
            fontSize: "1em",
            verticalAlign: "middle",
          },
          events: {
            click: async (e) => {
              e.preventDefault();
              e.stopPropagation();
              const btn = e.currentTarget;
              const originalText = btn.textContent;
              try {
                btn.textContent = "⏳";
                const response = await this.utils.gmFetch(
                  detailLinkElement.href,
                );
                const doc = new DOMParser().parseFromString(
                  response.responseText,
                  "text/html",
                );
                const videoDetailElement = doc.querySelector(".video-detail");
                if (videoDetailElement)
                  this.drawer.openWithContent(
                    videoDetailElement,
                    codeElement.textContent.trim(),
                  );
                else alert("无法加载预览内容。");
              } catch (err) {
                alert(`加载预览失败: ${err.message}`);
              } finally {
                if (btn.parentNode) btn.textContent = originalText;
              }
            },
          },
        });
        codeElement.before(previewButton);
      });
    },
    addLinkButtons: async (code, selector, buttonsConfig) => {
      const titleElement = await this.utils
        .waitForElement(selector)
        .catch(() => document.querySelector(selector));
      if (!code || !titleElement) return;
      const buttonContainer = this.utils.createDOM("div", {
        id: "cross-site-button-container",
        style: {
          display: "inline-block",
          zIndex: "10000",
          position: "fixed",
          top: "50px",
          left: "45px",
        },
      });
      if (buttonsConfig?.javdb) {
        try {
          const res = await this.utils.gmFetch(
            `${this.SITES.JAVDB}/search?q=${encodeURIComponent(code)}`,
          );
          const doc = new DOMParser().parseFromString(
            res.responseText,
            "text/html",
          );
          const videoLink = doc.querySelector('a[href*="/v/"]');
          const url = videoLink
            ? `${this.SITES.JAVDB}${videoLink.getAttribute("href")}`
            : `${this.SITES.JAVDB}/search?q=${encodeURIComponent(code)}`;
          buttonContainer.append(
            this.dom.createSingleButton(
              "JAVDB",
              videoLink ? "#e74c3c" : "#c0392b",
              url,
            ),
          );
        } catch {
          buttonContainer.append(
            this.dom.createSingleButton(
              "搜JAVDB",
              "#c0392b",
              `${this.SITES.JAVDB}/search?q=${encodeURIComponent(code)}`,
            ),
          );
        }
      }
      Object.entries(this.dom.getLinkButtonDefs()).forEach(([key, def]) => {
        if (buttonsConfig?.[key])
          buttonContainer.append(
            this.dom.createSingleButton(def.text, def.color, def.url(code)),
          );
      });
      titleElement.before(buttonContainer);
    },
    createSingleButton: (text, bgColor, url, target = "_self") =>
      this.utils.createDOM("a", {
        textContent: text,
        attributes: { href: url, target },
        style: {
          padding: "4px 8px",
          color: "#fff",
          background: bgColor,
          cursor: "pointer",
          textDecoration: "none",
          fontSize: "14px",
        },
      }),
    enhanceMagnetLinks: (config, detail = false) => {
      const processNode = (node) => {
        if (!node || node.dataset.tmMagnetEnhanced) return;
        const selectors = detail
          ? config.magnetDetailsSelectors
          : config.magnetSelectors;
        const hashLinkEl = node.querySelector(selectors.hashLink);
        if (!hashLinkEl) return;
        const hashMatch = (hashLinkEl.href || hashLinkEl.innerText).match(
          /[0-9a-fA-F]{40}/,
        );
        if (!hashMatch) return;
        const hash = hashMatch[0].toLowerCase();
        const title =
          node.querySelector(selectors.title)?.innerText.trim() ||
          `magnet-${hash.substring(0, 8)}`;
        const size = node.querySelector(selectors.size)?.innerText.trim() || "";
        const date = node.querySelector(selectors.date)?.innerText.trim() || "";
        const magnetUrl = `magnet:?xt=urn:btih:${hash}&dn=${title}🔞Size=${size}🔞Date=${date}`;
        const targetEl = node.querySelector(
          selectors.magnetUrl || selectors.title,
        );
        if (targetEl) targetEl.innerText = magnetUrl;
        const insertPoint = node.querySelector(selectors.insertPoint);
        if (!insertPoint) return;
        const parent = insertPoint.parentElement;
        const commonStyle = {
          height: "auto",
          backgroundColor: "transparent",
          borderColor: "transparent",
          marginRight: "5px",
          cursor: "pointer",
        };
        const copyBtn = this.utils.createDOM("a", {
          textContent: "📋",
          attributes: { title: "Copy Magnet Link" },
          style: commonStyle,
          events: {
            click: async (e) => {
              e.preventDefault();
              e.stopPropagation();
              const btn = e.currentTarget;
              await navigator.clipboard.writeText(
                decodeURIComponent(magnetUrl),
              );
              btn.textContent = "✅";
              setTimeout(
                () => btn.parentNode && (btn.textContent = "📋"),
                2000,
              );
            },
          },
        });
        const previewBtn = this.utils.createDOM("a", {
          textContent: "👁️",
          attributes: { title: "Preview Torrent via WhatsLink API" },
          style: commonStyle,
          events: {
            click: (e) => {
              e.preventDefault();
              e.stopPropagation();
              this.drawer.openWithMagnet(magnetUrl, title);
              previewBtn.textContent = "⏳";
            },
          },
        });
        const detailsBtn = this.utils.createDOM("a", {
          textContent: "🔗",
          style: commonStyle,
          attributes: {
            title: "Preview Torrent Details",
            href: `${this.SITES.BTSOW}/magnet/detail/${hash}`,
          },
        });
        parent.prepend(copyBtn, previewBtn, detailsBtn);
        node.dataset.tmMagnetEnhanced = "true";
      };
      const run = () =>
        document
          .querySelectorAll(
            detail
              ? config.magnetDetailsSelectors.list
              : config.magnetSelectors.list,
          )
          .forEach(processNode);
      run();
      this.utils.observeDOM(document.body, (mutations) => {
        if (mutations.some((m) => m.addedNodes.length)) run();
      });
    },
    preventUrlHashChange: (hashRegex, patchHistory = true) => {
      try {
        const baseUrl = window.location.pathname + window.location.search;
        const restore = () =>
          window.location.hash &&
          hashRegex.test(window.location.hash) &&
          history.replaceState(null, "", baseUrl);
        restore();
        window.addEventListener("hashchange", restore, false);
        if (patchHistory) {
          const origReplaceState = history.replaceState.bind(history);
          const origPushState = history.pushState.bind(history);
          const override = (orig) =>
            function (state, title, url) {
              if (
                typeof url === "string" &&
                /#/.test(url) &&
                hashRegex.test(url)
              )
                url = url.replace(/#.*$/, "");
              return orig(state, title, url);
            };
          history.replaceState = override(origReplaceState);
          history.pushState = override(origPushState);
        }
      } catch {}
    },
    batchReplaceTag:(selector, newTagName) => {
          const elements = document.querySelectorAll(selector);
          elements.forEach(oldEl => {
              const newEl = document.createElement(newTagName);
              Array.from(oldEl.attributes).forEach(attr => {
                  newEl.setAttribute(attr.name, attr.value);
              });
              newEl.append(...oldEl.childNodes);
              oldEl.replaceWith(newEl);
          });
      },
  };

  // ==================== DRAWER CLASS ====================
  drawer = (() => {
    let drawerInstance = null;
    const create = ({
      direction = "right",
      width = "50vw",
      title = "",
      url,
    }) => {
      drawerInstance?.element?.remove();

      const closeBtn = this.utils.createDOM("button", {
        textContent: "❌",
        style: {
          background: "none",
          border: "none",
          fontSize: "20px",
          cursor: "pointer",
          color: "#666",
        },
      });

      const titleEl = this.utils.createDOM("a", {
        textContent: title,
        attributes: { href: url || "#" },
        style: { fontSize: "16px", textDecoration: "none" },
      });

      const magnetInput = this.utils.createDOM("input", {
        attributes: {
          type: "text",
          placeholder: "输入完整磁力链接或文本 (magnetInput)",
        },
        style: {
          flex: "1",
          padding: "4px 8px",
          fontSize: "12px",
          border: "1px solid #ccc",
          borderRadius: "4px",
        },
      });

      const searchBtn = this.utils.createDOM("button", {
        textContent: "🔍 解析",
        style: {
          padding: "4px 8px",
          fontSize: "12px",
          background: "#1890ff",
          color: "#fff",
          border: "none",
          borderRadius: "4px",
          cursor: "pointer",
        },
      });

      const fetchAndRenderWhatsLink = async (inputVal) => {
        if (!inputVal) {
          alert("输入框内容不能为空!");
          return;
        }
        magnetInput.value = inputVal;
        searchBtn.textContent = "⏳";

        try {
          const whatslinkBase =
            this.SITES.WHATSLINK || "https://whatslink.info";
          const apiUrl = `${whatslinkBase}/api/v1/link?url=${encodeURIComponent(inputVal)}`;
          const response = await this.utils.gmFetch(apiUrl, {
            headers: {
              referer: `${whatslinkBase}/`,
              "Content-Type": "application/json",
            },
          });

          let json = JSON.parse(response.responseText);
          const data = json.data || json;

          const formatSize = (bytes) => {
            if (!bytes || bytes === 0) return "0 B";
            const k = 1024,
              sizes = ["B", "KB", "MB", "GB", "TB"],
              i = Math.floor(Math.log(bytes) / Math.log(k));
            return (
              parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i]
            );
          };

          let html = `
            <div style="background:#fff; border-radius:8px; padding:5px; box-shadow:0 1px 3px rgba(0,0,0,0.1);">
              <div style="margin:10px 0; word-break: break-all; font-size: 16px;"><strong><!--Resource Name:--></strong>${data.name || title}</div>
              <div style="display: grid; grid-template-columns: 1fr 2fr 1fr; gap: 10px; font-size: 14px; justify-items: stretch; align-items: center">
                <div><strong>Type:</strong> ${data.type || "unknown"}</div>
                <div><strong>Total Size:</strong> ${data.size ? data.size + " 字节 (" + formatSize(data.size) + ")" : "未知"}</div>
                <div><strong>Files:</strong> ${data.count || 0}</div>
              </div>
            </div>
          `;

          html += `<div style="display:flex; flex-direction:column; gap:10px; overflow-y:scroll; align-items:center; margin-top: 10px; height:80vh;">`;
          if (
            data.screenshots &&
            Array.isArray(data.screenshots) &&
            data.screenshots.length > 0
          ) {
            data.screenshots.forEach((imgUrl) => {
              html += `<img src="${imgUrl.screenshot}" style="max-width:100%; border-radius:4px; box-shadow:0 1px 3px rgba(0,0,0,0.1);" referrerpolicy="no-referrer" />`;
            });
          } else {
            html += `<div style="text-align:center; margin: auto; color: #888; font-size: 14px;">暂无预览截图</div>`;
          }
          html += `</div>`;

          content.innerHTML = html;
          titleEl.textContent = `WhatsLink 预览:${data.name || inputVal}`;
        } catch (err) {
          console.error("WhatsLink Error:", err);
          alert(`获取预览失败: ${err.message}`);
        } finally {
          searchBtn.textContent = "🔍 解析";
        }
      };

      searchBtn.onclick = () => {
        fetchAndRenderWhatsLink(magnetInput.value.trim());
      };

      const topBar = this.utils.createDOM("div", {
        style: {
          display: "flex",
          background: "#f0f2f5",
          borderBottom: "1px solid #ddd",
          alignItems: "center",
        },
        children: [magnetInput, searchBtn],
      });

      const header = this.utils.createDOM("div", {
        style: {
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          background: "#fff",
          borderBottom: "1px solid #eee",
          textAlign: "center",
        },
        children: [titleEl, closeBtn],
      });

      const content = this.utils.createDOM("div", {
        style: {
          padding: "10px",
          height: "calc(100vh - 100px)",
          overflowY: "auto",
        },
      });

      const element = this.utils.createDOM("div", {
        style: {
          position: "fixed",
          top: "0",
          [direction]: "0",
          width,
          height: "100vh",
          background: "white",
          boxShadow: "0 0 10px rgba(0,0,0,0.1)",
          transform: `translateX(${direction === "left" ? "-100%" : "100%"})`,
          transition: "transform 0.3s ease",
          zIndex: "9999",
          display: "flex",
          flexDirection: "column",
        },
        children: [header, topBar, content],
      });

      closeBtn.onclick = () => close();
      document.body.append(element);
      drawerInstance = {
        element,
        content,
        titleEl,
        fetchAndRenderWhatsLink,
        magnetInput,
      };
      return drawerInstance;
    };

    const open = (url, title, width, direction) => {
      const instance = create({ url, title, width, direction });
      instance.content.innerHTML = `<iframe src='${url}' style='display:block;height:100%;width:100%;border:none;'></iframe>`;
      requestAnimationFrame(
        () => (instance.element.style.transform = "translateX(0)"),
      );
    };

    const openWithContent = (element, title) => {
      const instance = create({ title });
      const wrapper = this.utils.createDOM("div", {
        style: { padding: "0", backgroundColor: "#f5f5f5", color: "#363636" },
      });
      wrapper.append(element);
      instance.content.append(wrapper);
      requestAnimationFrame(
        () => (instance.element.style.transform = "translateX(0)"),
      );
    };

    const openWithMagnet = (magnetUrl, title) => {
      const instance = create({ title });
      requestAnimationFrame(() => {
        instance.element.style.transform = "translateX(0)";
        instance.fetchAndRenderWhatsLink(magnetUrl);
      });
    };

    const close = () => {
      if (!drawerInstance) return;
      const { element } = drawerInstance;
      element.style.transform = "translateX(100%)";
      setTimeout(() => {
        drawerInstance?.element === element &&
          (drawerInstance.content.innerHTML = "");
        element.remove();
      }, 300);
    };

    return { open, openWithContent, openWithMagnet, close };
  })();

  // ==================== SUBTITLES MODULE ====================
  subtitles = {
    _inited: false,
    _state: {
      vttText: null,
      subtitleLabel: null,
      objectUrlsByVideo: new WeakMap(),
      hasLoadedSubtitle: false,
    },
    _isLikelyVtt: (text) =>
      (text || "").split(/\r?\n/)[0]?.trim().startsWith("WEBVTT"),
    _convertSrtToVtt: (srtText) => {
      let text = (srtText || "").replace(/\r\n?/g, "\n").replace(/^\uFEFF/, "");
      text = text.replace(/(\d\d:\d\d:\d\d),(\d\d\d)/g, "$1.$2");
      text = text.replace(/\s+-->\s+/g, " --> ");
      text = text.replace(/\n\d+\n(?=\d\d:\d\d:\d\d\.\d{3}\s+-->)/g, "\n");
      return "WEBVTT\n\n" + text.trim() + "\n";
    },
    _convertAssToVtt: (assText) => {
      let text = (assText || "").replace(/\r\n?/g, "\n").replace(/^\uFEFF/, "");
      const eventsMatch = text.match(/[Events][\s\S]*?(?=\[|$)/);
      if (!eventsMatch) return "WEBVTT\n\n";
      const dialogueLines = eventsMatch[0].match(/^Dialogue:.*$/gm) || [];
      let vttContent = "WEBVTT\n\n";
      dialogueLines.forEach((line) => {
        const parts = line.split(",");
        if (parts.length < 10) return;
        const startTime = parts[1];
        const endTime = parts[2];
        const textContent = parts.slice(9).join(",");
        const formatTime = (timeStr) => {
          const timeMatch = timeStr.match(/(\d+):(\d{2}):(\d{2})\.(\d{2})/);
          if (!timeMatch) return timeStr;
          const [, h, m, s, cs] = timeMatch;
          return `${h.padStart(2, "0")}:${m.padStart(2, "0")}:${s.padStart(2, "0")}.${(parseInt(cs) * 10).toString().padStart(3, "0")}`;
        };
        let cleanText = textContent
          .replace(/\{[^}]*\}/g, "")
          .replace(/\\N/g, "\n")
          .replace(/\\n/g, "\n")
          .replace(/\\h/g, " ")
          .trim();
        if (cleanText)
          vttContent += `${formatTime(startTime)} --> ${formatTime(endTime)}\n${cleanText}\n\n`;
      });
      return vttContent.trim() + "\n";
    },
    _isLikelyAss: (text) =>
      (text || "").split(/\r?\n/)[0]?.trim() === "[Script Info]" ||
      text.includes("[Events]") ||
      text.includes("Dialogue:"),
    _toVtt(text) {
      if (this._isLikelyVtt(text)) return text;
      if (this._isLikelyAss(text)) return this._convertAssToVtt(text);
      return this._convertSrtToVtt(text);
    },
    _revokeExistingObjectUrl(video) {
      try {
        const url = this._state.objectUrlsByVideo.get(video);
        if (url) {
          URL.revokeObjectURL(url);
          this._state.objectUrlsByVideo.delete(video);
        }
      } catch (_) {}
    },
    _removeExistingLocalTracks: (video) =>
      video
        .querySelectorAll('track[data-local-subtitle="1"]')
        .forEach((t) => t.remove()),
    _attachSubtitleToVideo(video) {
      if (!this._state.vttText) return;
      this._revokeExistingObjectUrl(video);
      this._removeExistingLocalTracks(video);
      const blob = new Blob([this._state.vttText], { type: "text/vtt" });
      const url = URL.createObjectURL(blob);
      this._state.objectUrlsByVideo.set(video, url);
      const track = this.utils.createDOM("track", {
        attributes: {
          kind: "subtitles",
          label: this._state.subtitleLabel || "Local Subtitle",
          srclang: "en",
          src: url,
          default: true,
          "data-local-subtitle": "1",
        },
        events: {
          load: () => {
            if (track.track) track.track.mode = "showing";
          },
        },
      });
      video.appendChild(track);
    },
    _attachToAllVideos() {
      const videoSelectors = [
        "video",
        'iframe[src*="player"]',
        'iframe[src*="video"]',
        ".video-player video",
        ".player video",
        "#player video",
        ".plyr video",
      ];
      let allVideos = [];
      videoSelectors.forEach((selector) => {
        allVideos = allVideos.concat(
          Array.from(document.querySelectorAll(selector)),
        );
      });
      const uniqueVideos = [...new Set(allVideos)];
      if (uniqueVideos.length === 0) return;
      let maxWidthVideo = uniqueVideos.reduce(
        (max, vid) =>
          vid.getBoundingClientRect().width > max.getBoundingClientRect().width
            ? vid
            : max,
        uniqueVideos[0],
      );
      if (maxWidthVideo) this._attachSubtitleToVideo(maxWidthVideo);
    },
    _ensureUi() {
      if (document.getElementById("tm-add-local-subtitle-btn")) return;
      const container = this.utils.createDOM("div", {
        id: "tm-add-local-subtitle-container",
        style: {
          position: "fixed",
          zIndex: "2147483647",
          bottom: "16px",
          left: "16px",
          display: "flex",
          gap: "8px",
          alignItems: "center",
        },
      });
      const input = this.utils.createDOM("input", {
        attributes: {
          type: "file",
          accept: ".vtt,.srt,.ass,text/vtt,text/plain,.sub",
        },
        style: { display: "none" },
      });
      const label = this.utils.createDOM("span", {
        id: "tm-add-local-subtitle-label",
        style: {
          fontSize: "12px",
          color: "#fff",
          textShadow: "0 1px 2px rgba(0,0,0,0.6)",
        },
      });
      const button = this.utils.createDOM("button", {
        id: "tm-add-local-subtitle-btn",
        textContent: "本地字幕",
        attributes: { title: "为页面视频加载本地字幕 (.srt/.vtt/.ass)" },
        style: {
          padding: "6px 10px",
          fontSize: "12px",
          color: "#fff",
          background: "rgba(0,0,0,0.6)",
          border: "1px solid rgba(255,255,255,0.2)",
          borderRadius: "6px",
          cursor: "pointer",
          backdropFilter: "saturate(150%) blur(6px)",
        },
        events: { click: () => input.click() },
      });
      input.addEventListener("change", async () => {
        const file = input.files?.[0];
        if (!file) return;
        this._state.subtitleLabel = file.name;
        try {
          const text = await file.text();
          this._state.vttText = this._toVtt(text);
          this._state.hasLoadedSubtitle = true;
          label.textContent = file.name;
          this._attachToAllVideos();
          setTimeout(() => this._attachToAllVideos(), 3000);
        } catch (err) {
          alert("读取字幕文件失败,请重试。");
        } finally {
          input.value = "";
        }
      });
      container.append(button, label, input);
      document.documentElement.appendChild(container);
    },
    init() {
      if (this._inited) return;
      this._inited = true;
      this._ensureUi();
    },
  };

  // ==================== SITE HANDLERS ====================
  handlers = {
    handleGenericSite: (siteKey, instance) => {
      const config = instance.SITE_CONFIG[siteKey];
      if (!config) return;
      if (config.style)
        instance.dom.injectStyleOnce(config.style, siteKey.replace(/\./g, "-"));
      const isDetailPage = instance.utils.isValidPath(config.pathCheck);

      switch (siteKey) {
        case instance.SITES.JAVBUS: {
          const avatarBox = document.querySelector(
            ".masonry-brick:has(.avatar-box)",
          );
          if (avatarBox)
            document.querySelector(".masonry #waterfall")?.prepend(avatarBox);
          document.querySelectorAll(".photo-frame img").forEach((img) => {
            if (img.src.includes("/pics/thumb/"))
              img.src = img.src
                .replace("/pics/thumb/", "/pics/cover/")
                .replace(".jpg", "_b.jpg");
          });
          if (config.magnetSelectors) instance.dom.enhanceMagnetLinks(config);
          break;
        }
        case instance.SITES.JAVDB: {
          if (isDetailPage) {
            instance.dom.preventUrlHashChange(/#gallery-\d+/, true);
            document.querySelector(".review-tab")?.click();
            instance.highRes.run();
          }
          if (config.magnetSelectors) instance.dom.enhanceMagnetLinks(config);
          break;
        }
        case instance.SITES.YHG: {
          instance.dom.insertCopyAllButton(
            ".zsky-result-meta > span:first-of-type",
          );
          break;
        }
        case instance.SITES.SUKEBEI: {
          instance.dom.insertCopyAllButton(
            "tbody > tr > td:nth-child(2) > a:last-child",
          );
          break;
        }
        case instance.SITES.BTSOW:
          {
            instance.dom.insertCopyAllButton("div.q-infinite-scroll a.file");
          }
          break;
      }

      if (config.isMagnetSite) {
        instance.dom.enhanceMagnetLinks(config);
        if (isDetailPage) instance.dom.enhanceMagnetLinks(config, true);
        return;
      }
      if (config.isVideoSite && isDetailPage) {
        instance.subtitles.init();
      }

      if (isDetailPage) {
        const code = instance.utils.getCodeFromCurrentSite(
          siteKey,
          config.titleSelector,
        );
        if (code)
          instance.dom.addLinkButtons(
            code,
            config.titleSelector,
            config.buttons,
          );
        return;
      }

      const executeListHandler = () => {
        if (siteKey === instance.SITES.JAVDB) {
          instance.dom.batchReplaceTag(".item div:not(.cover)",'span');
          instance.dom.insertCopyButton(".item .video-title", {position: "before"});
          instance.dom.addPreviewButtonsToList(".item", ".video-title");
          instance.dom.insertCopyAllButton(".video-title");
        }
      };
      executeListHandler();
    },
    setupMenus: (instance) => {
      GM_registerMenuCommand("设置站点与Cookie(多行表格)", () => {
        document.getElementById("tm-settings-modal")?.remove();
        const tbody = instance.utils.createDOM("tbody");
        const makeRow = (labelText, key, value, placeholder) =>
          instance.utils.createDOM("tr", {
            children: [
              instance.utils.createDOM("td", {
                textContent: labelText,
                style: { padding: "6px 8px", whiteSpace: "nowrap" },
              }),
              instance.utils.createDOM("td", {
                style: { padding: "6px 8px" },
                children: [
                  instance.utils.createDOM("input", {
                    attributes: {
                      type: "text",
                      "data-key": key,
                      placeholder: placeholder || "",
                    },
                    style: {
                      width: "100%",
                      padding: "6px 8px",
                      border: "1px solid #ddd",
                      borderRadius: "6px",
                    },
                  }),
                ],
              }),
            ],
          });
        Object.entries(instance.SITES).forEach(([key, val]) => {
          const row = makeRow(
            key,
            `SITES.${key}`,
            val,
            JableLinker.defaultSites[key],
          );
          row.querySelector("input").value = val || "";
          tbody.append(row);
        });
        const overlay = instance.utils.createDOM("div", {
          id: "tm-settings-modal",
          style: {
            position: "fixed",
            inset: "0",
            background: "rgba(0,0,0,0.45)",
            zIndex: "2147483647",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
          },
          children: [
            instance.utils.createDOM("div", {
              style: {
                width: "min(800px, 96vw)",
                maxHeight: "80vh",
                overflow: "auto",
                background: "#fff",
                borderRadius: "10px",
                padding: "16px",
              },
              children: [
                instance.utils.createDOM("div", {
                  textContent: "站点与Cookie设置",
                  style: {
                    fontSize: "16px",
                    fontWeight: "600",
                    marginBottom: "10px",
                  },
                }),
                instance.utils.createDOM("table", {
                  style: {
                    width: "100%",
                    borderCollapse: "collapse",
                    fontSize: "13px",
                  },
                  children: [tbody],
                }),
                instance.utils.createDOM("div", {
                  style: {
                    marginTop: "12px",
                    display: "flex",
                    gap: "8px",
                    justifyContent: "flex-end",
                  },
                  children: [
                    instance.utils.createDOM("button", {
                      textContent: "取消",
                      events: { click: () => overlay.remove() },
                    }),
                    instance.utils.createDOM("button", {
                      textContent: "保存",
                      style: {
                        background: "#1677ff",
                        color: "#fff",
                        border: "none",
                        padding: "6px 12px",
                        borderRadius: "6px",
                      },
                      events: {
                        click: () => {
                          tbody
                            .querySelectorAll("input[data-key]")
                            .forEach((input) => {
                              const key = input.dataset.key;
                              const val = input.value.trim();
                              GM_setValue(key, val);
                              if (key.startsWith("SITES.")) {
                                const siteKey = key.slice(6);
                                if (instance.SITES.hasOwnProperty(siteKey))
                                  instance.SITES[siteKey] =
                                    val || JableLinker.defaultSites[siteKey];
                              }
                            });
                          overlay.remove();
                          alert("已保存配置,请刷新页面生效。");
                        },
                      },
                    }),
                  ],
                }),
              ],
            }),
          ],
        });
        document.documentElement.append(overlay);
      });

      GM_registerMenuCommand("⚙️ 配置 DMM 与 MGStage 高清图映射", () =>
        instance.highRes.openConfigModal(),
      );
    },
  };

  init() {
    this.handlers.setupMenus(this);
    const currentSiteKey = Object.keys(this.SITE_CONFIG).find((site) =>
      this.utils.isIncludes(site),
    );
    if (currentSiteKey) this.handlers.handleGenericSite(currentSiteKey, this);
    else console.log("JableLinker: No handler for current site.");
  }
}

(function () {
  "use strict";
  new JableLinker().init();
})();