☰

Dual-Websites Crosslinker

Add a button which crosslinks two websites via user-defined URLs.

您需要先安裝使用者腳本管理器擴展,如 Tampermonkey、Greasemonkey 或 Violentmonkey 之後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 Tampermonkey 或 Violentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 Tampermonkey或 Violentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 Tampermonkey或 Userscripts 後才能安裝該腳本。

你需要先安裝一款使用者腳本管理器擴展,比如 Tampermonkey,才能安裝此腳本

您需要先安裝使用者腳本管理器擴充功能後才能安裝該腳本。

(我已經安裝了使用者腳本管理器,讓我安裝!)

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

(我已經安裝了使用者樣式管理器,讓我安裝!)

// ==UserScript==
// @name         Dual-Websites Crosslinker
// @namespace    https://greasyfork.org/zh-TW/scripts/581048-dual-websites-crosslinker
// @version      8.6.21
// @description  Add a button which crosslinks two websites via user-defined URLs.
// @author       php
// @match        *://nhentai.net/*
// @match        *://e-hentai.org/g/*
// @match        *://www.wnacg.com/photos-index-*
// @match        *://jable.tv/videos/*
// @match        *://missav.ai/*
// @match        *://missav.ws/*
// @grant        GM_registerMenuCommand
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_addStyle
// @license      MIT
// ==/UserScript==

(function() {
    'use strict';

    /**
     * =========================================================================
     * CROSSLINKER APP MODULE
     * Finer modularization: Separates State, Logic (Services), and Layout (UI).
     * =========================================================================
     */
    const CrosslinkerApp = {

        // ---------------------------------------------------------------------
        // MODULE 1: CONFIGURATION & CONSTANTS
        // ---------------------------------------------------------------------
        Config: {
            SCRIPT_ID: GM_info.script.name.replace(/[^a-zA-Z0-9]/g, '-'),
            STORAGE_KEY: 'Dual-Websites_Crosslinker',

            VAR_BLUEPRINT: { varSourceSelector: '',
                            extractMode: 'full',
                            fallbackValue: '',
                            regexPattern: '',
                            regexIndex: '0',
                            splitChar: '',
                            splitIndex: '0',
                            stripBracketsWithContent: false,
                            stripNonAscii: false,
                            stripNumber: false,
                            stripBoundarySpecials: false,
                            replaceRules: [],
                            prefix: '',
                            suffix: '',
                            casing: 'none',
                            useCustomStripReplace: true,
                            stripReplaceChar: ''
                           },

            PROFILE_BLUEPRINT: {
                enabled: true, direction: 'both',
                siteA: { hostUrl: '', buttonLabel: '', destUrl: '', btnContainerSelector: '', variables: {} },
                siteB: { hostUrl: '', buttonLabel: '', destUrl: '', btnContainerSelector: '', variables: {} }
            },

            INITIAL_DATA: {
    "nhentai <-> e-hentai": {
        "enabled": true,
        "direction": "both",
        "siteA": {
            "hostUrl": "https:\\/\\/nhentai\\.net\\/g\\/\\d+\\/?",
            "buttonLabel": "e-hentai",
            "destUrl": "https://e-hentai.org/?f_search={title}",
            "btnContainerSelector": "#info > div",
            "variables": {
                "title": {
                    "varSourceSelector": "#info > h1 > span.pretty",
                    "extractMode": "regex",
                    "fallbackValue": "",
                    "regexPattern": "[^||丨]+",
                    "regexIndex": "0",
                    "splitChar": "",
                    "splitIndex": "0",
                    "stripBracketsWithContent": true,
                    "stripNonAscii": false,
                    "stripNumber": false,
                    "stripBoundarySpecials": false,
                    "replaceRules": [
                        {
                            "find": "(?<=\\s)-|-(?=\\s)",
                            "replace": " "
                        },
                        {
                            "find": "(?<=[\\p{L}\\p{N}])(['’']+[\\p{L}\\p{N}]+)",
                            "replace": " "
                        },
                        {
                            "find": "(?<=\\s)~|~(?=\\s)",
                            "replace": " "
                        }
                    ],
                    "prefix": "",
                    "suffix": "",
                    "casing": "none",
                    "useCustomStripReplace": true,
                    "stripReplaceChar": ""
                }
            }
        },
        "siteB": {
            "hostUrl": "https:\\/\\/e-hentai\\.org\\/g\\/\\d+\\/[a-zA-Z0-9]+\\/?",
            "buttonLabel": "nhentai",
            "destUrl": "https://nhentai.net/search?q={title}",
            "btnContainerSelector": "#gd5",
            "variables": {
                "title": {
                    "varSourceSelector": "#gn",
                    "extractMode": "regex",
                    "fallbackValue": "",
                    "regexPattern": "[^||丨]+",
                    "regexIndex": "0",
                    "splitChar": "",
                    "splitIndex": "0",
                    "stripBracketsWithContent": true,
                    "stripNonAscii": false,
                    "stripNumber": false,
                    "stripBoundarySpecials": false,
                    "replaceRules": [
                        {
                            "find": "(?<=\\s)-|-(?=\\s)",
                            "replace": " "
                        },
                        {
                            "find": "(?<=[\\p{L}\\p{N}])(['’']+[\\p{L}\\p{N}]+)",
                            "replace": " "
                        },
                        {
                            "find": "(?<=\\s)~|~(?=\\s)",
                            "replace": " "
                        }
                    ],
                    "prefix": "",
                    "suffix": "",
                    "casing": "none",
                    "useCustomStripReplace": true,
                    "stripReplaceChar": ""
                }
            }
        }
    },
    "nhentai -> WNACG + WNACG (mobile) -> nhentai": {
        "enabled": true,
        "direction": "both",
        "siteA": {
            "hostUrl": "https:\\/\\/nhentai\\.net\\/g\\/\\d+\\/?",
            "buttonLabel": "WNACG",
            "destUrl": "https://www.wnacg.com/{isMobile}/?q={title}&f=_all&s=create_time_DESC&syn=yes",
            "btnContainerSelector": "#info > div",
            "variables": {
                "title": {
                    "varSourceSelector": "#info > h2",
                    "extractMode": "regex",
                    "fallbackValue": "CSS:#info > h1 > span.pretty",
                    "regexPattern": "[^||丨]+",
                    "regexIndex": "-1",
                    "splitChar": "",
                    "splitIndex": "0",
                    "stripBracketsWithContent": true,
                    "stripNonAscii": false,
                    "stripNumber": false,
                    "stripBoundarySpecials": false,
                    "replaceRules": [],
                    "prefix": "",
                    "suffix": "",
                    "casing": "none",
                    "useCustomStripReplace": true,
                    "stripReplaceChar": ""
                },
                "isMobile": {
                    "varSourceSelector": "$isMobile",
                    "extractMode": "full",
                    "fallbackValue": "",
                    "regexPattern": "",
                    "regexIndex": "0",
                    "splitChar": "",
                    "splitIndex": "0",
                    "stripBracketsWithContent": false,
                    "stripNonAscii": false,
                    "stripNumber": false,
                    "stripBoundarySpecials": false,
                    "replaceRules": [
                        {
                            "find": "true",
                            "replace": "q"
                        },
                        {
                            "find": "false",
                            "replace": "search"
                        }
                    ],
                    "prefix": "",
                    "suffix": "",
                    "casing": "none",
                    "useCustomStripReplace": true,
                    "stripReplaceChar": ""
                }
            }
        },
        "siteB": {
            "hostUrl": "https:\\/\\/www\\.wnacg\\.com\\/photos-index-aid-\\d+(\\.html)?",
            "buttonLabel": "nhentai",
            "destUrl": "https://nhentai.net/search?q={title}",
            "btnContainerSelector": "div.Introduct > div:nth-child(4)",
            "variables": {
                "title": {
                    "varSourceSelector": "#comicName",
                    "extractMode": "regex",
                    "fallbackValue": "",
                    "regexPattern": "[^||丨]+",
                    "regexIndex": "0",
                    "splitChar": "",
                    "splitIndex": "0",
                    "stripBracketsWithContent": true,
                    "stripNonAscii": false,
                    "stripNumber": false,
                    "stripBoundarySpecials": false,
                    "replaceRules": [],
                    "prefix": "",
                    "suffix": "",
                    "casing": "none",
                    "useCustomStripReplace": true,
                    "stripReplaceChar": ""
                }
            }
        }
    },
    "e-hentai -> WNACG + WNACG (mobile) -> e-hentai": {
        "enabled": true,
        "direction": "both",
        "siteA": {
            "hostUrl": "https:\\/\\/e-hentai\\.org\\/g\\/\\d+\\/[a-zA-Z0-9]+\\/?",
            "buttonLabel": "WNACG",
            "destUrl": "https://www.wnacg.com/{isMobile}/?q={title}&f=_all&s=create_time_DESC&syn=yes",
            "btnContainerSelector": "#gd5",
            "variables": {
                "title": {
                    "varSourceSelector": "#gj",
                    "extractMode": "regex",
                    "fallbackValue": "CSS:gd2",
                    "regexPattern": "[^||丨]+",
                    "regexIndex": "-1",
                    "splitChar": "",
                    "splitIndex": "0",
                    "stripBracketsWithContent": true,
                    "stripNonAscii": false,
                    "stripNumber": false,
                    "stripBoundarySpecials": false,
                    "replaceRules": [],
                    "prefix": "",
                    "suffix": "",
                    "casing": "none",
                    "useCustomStripReplace": true,
                    "stripReplaceChar": ""
                },
                "isMobile": {
                    "varSourceSelector": "$isMobile",
                    "extractMode": "full",
                    "fallbackValue": "",
                    "regexPattern": "",
                    "regexIndex": "0",
                    "splitChar": "",
                    "splitIndex": "0",
                    "stripBracketsWithContent": false,
                    "stripNonAscii": false,
                    "stripNumber": false,
                    "stripBoundarySpecials": false,
                    "replaceRules": [
                        {
                            "find": "true",
                            "replace": "q"
                        },
                        {
                            "find": "false",
                            "replace": "search"
                        }
                    ],
                    "prefix": "",
                    "suffix": "",
                    "casing": "none",
                    "useCustomStripReplace": true,
                    "stripReplaceChar": ""
                }
            }
        },
        "siteB": {
            "hostUrl": "https:\\/\\/www\\.wnacg\\.com\\/photos-index-aid-\\d+(\\.html)?",
            "buttonLabel": "e-hentai",
            "destUrl": "https://e-hentai.org/?f_search={title}",
            "btnContainerSelector": "div.Introduct > div:nth-child(4)",
            "variables": {
                "title": {
                    "varSourceSelector": "#comicName",
                    "extractMode": "regex",
                    "fallbackValue": "",
                    "regexPattern": "[^||丨]+",
                    "regexIndex": "0",
                    "splitChar": "",
                    "splitIndex": "0",
                    "stripBracketsWithContent": true,
                    "stripNonAscii": false,
                    "stripNumber": false,
                    "stripBoundarySpecials": false,
                    "replaceRules": [],
                    "prefix": "",
                    "suffix": "",
                    "casing": "none",
                    "useCustomStripReplace": true,
                    "stripReplaceChar": ""
                }
            }
        }
    },
    "MissAV <-> Jable": {
        "enabled": true,
        "direction": "both",
        "siteA": {
            "hostUrl": "https:\\/\\/jable\\.tv\\/videos\\/[a-zA-Z0-9-]+\\/?",
            "buttonLabel": "MissAV",
            "destUrl": "https://missav.ai/{code} | https://missav.ws/{code}",
            "btnContainerSelector": "#site-content > div > div > div:nth-child(1) > section.video-info.pb-3 > div.text-center > div",
            "variables": {
                "code": {
                    "varSourceSelector": "$currentUrl",
                    "extractMode": "regex",
                    "fallbackValue": "",
                    "regexPattern": "[a-zA-Z0-9]+-[a-zA-Z0-9]+",
                    "regexIndex": "0",
                    "splitChar": "",
                    "splitIndex": "0",
                    "stripBracketsWithContent": true,
                    "stripNonAscii": true,
                    "stripNumber": false,
                    "stripBoundarySpecials": false,
                    "replaceRules": [],
                    "prefix": "",
                    "suffix": "",
                    "casing": "none",
                    "useCustomStripReplace": true,
                    "stripReplaceChar": ""
                }
            }
        },
        "siteB": {
            "hostUrl": "https:\\/\\/missav\\.ai\\/[a-zA-Z0-9-]+\\/? | https:\\/\\/missav\\.ws\\/[a-zA-Z0-9-]+\\/?",
            "buttonLabel": "Jable",
            "destUrl": "https://jable.tv/videos/{code}/",
            "btnContainerSelector": "body > div:nth-child(3) > div.sm\\:container.mx-auto.px-4.content-without-search.pb-12 > div > div.flex-1.order-first > div.mt-4 > div",
            "variables": {
                "code": {
                    "varSourceSelector": "$currentUrl",
                    "extractMode": "regex",
                    "fallbackValue": "",
                    "regexPattern": "[a-zA-Z0-9]+-[a-zA-Z0-9]+",
                    "regexIndex": "0",
                    "splitChar": "",
                    "splitIndex": "0",
                    "stripBracketsWithContent": true,
                    "stripNonAscii": true,
                    "stripNumber": false,
                    "stripBoundarySpecials": false,
                    "replaceRules": [],
                    "prefix": "",
                    "suffix": "",
                    "casing": "none",
                    "useCustomStripReplace": true,
                    "stripReplaceChar": ""
                }
            }
        }
    },
    "e-hentai - Find Alt": {
        "enabled": true,
        "direction": "a2b",
        "siteA": {
            "hostUrl": "https:\\/\\/e-hentai\\.org\\/g\\/\\d+\\/[a-zA-Z0-9]+\\/?",
            "buttonLabel": "Find Alt",
            "destUrl": "https://e-hentai.org/?f_search={artist} {group} {title}",
            "btnContainerSelector": "#gd5",
            "variables": {
                "title": {
                    "varSourceSelector": "#gn",
                    "extractMode": "regex",
                    "fallbackValue": "",
                    "regexPattern": "[^||丨]+",
                    "regexIndex": "0",
                    "splitChar": "",
                    "splitIndex": "0",
                    "stripBracketsWithContent": true,
                    "stripNonAscii": false,
                    "stripNumber": false,
                    "stripBoundarySpecials": true,
                    "replaceRules": [
                        {
                            "find": "\\([^()]*\\)|([^()]*)|\\[[^[\\]]*\\]|[[^[]]*]|【[^【】]*】|\\{[^{}]*\\}|{[^{}]*}|<[^<>]*>|《[^《》]*》|\\p{Ps}.*?\\p{Pe}",
                            "replace": " "
                        },
                        {
                            "find": "(?<=[\\p{L}\\p{N}]+)(['’']+[\\p{L}\\p{N}]+)",
                            "replace": " "
                        },
                        {
                            "find": "([\\p{Pd}=\\u007e\\uff5e])(.*?)\\1.*$",
                            "replace": " "
                        },
                        {
                            "find": "-",
                            "replace": " "
                        },
                        {
                            "find": "(?<=[\\p{L}\\p{N}]+[^\\p{L}\\p{N}]+?)(ch|chap|chapter|vol|volume|ep|episode|season|part)[^\\p{L}\\p{N}]*?(\\p{N}+|zero|one|two|three|four|five|six|seven|eight|nine|ten).*$",
                            "replace": " "
                        },
                        {
                            "find": "(?<=[^\\p{N}]{3,}[^\\p{L}\\p{N}]+?|(^|\\s)\\p{L}{3,}?)\\p{N}+.*$",
                            "replace": " "
                        },
                        {
                            "find": "(?<=[\\p{L}\\p{N}]+?)[^\\p{L}\\p{N}]+(k[oō]u?hen|chuuhen|zenpen|soushuuhen).*$",
                            "replace": " "
                        },
                        {
                            "find": "(?<=[\\p{L}\\p{N}]+[^\\p{L}\\p{N}]+?)[\\p{L}\\p{N}]+[^\\p{L}\\p{N}]+hen([^\\p{L}\\p{N}]+|$).*$",
                            "replace": " "
                        },
                        {
                            "find": "(?<=[\\p{L}\\p{N}]+[^\\p{L}\\p{N}]*?)[^\\p{L}\\p{N}]+((zoku)+|after|bangaihen)([^\\p{L}\\p{N}]+|$).*$",
                            "replace": " "
                        },
                        {
                            "find": "^([^\\p{L}\\p{N}]*(zoku|k[oō]u?hen|chuuhen|zenpen|soushuuhen|after|bangaihen)+[^\\p{L}\\p{N}]+)(?=[\\p{L}\\p{N}]+)",
                            "replace": " "
                        }
                    ],
                    "prefix": "",
                    "suffix": "",
                    "casing": "none",
                    "useCustomStripReplace": true,
                    "stripReplaceChar": ""
                },
                "artist": {
                    "varSourceSelector": "a[id^=\"ta_artist\"]@id",
                    "extractMode": "split",
                    "fallbackValue": "",
                    "regexPattern": "",
                    "regexIndex": "",
                    "splitChar": ":",
                    "splitIndex": "1",
                    "stripBracketsWithContent": false,
                    "stripNonAscii": false,
                    "stripNumber": false,
                    "stripBoundarySpecials": false,
                    "replaceRules": [],
                    "prefix": "artist:\"",
                    "suffix": "\"",
                    "casing": "none",
                    "useCustomStripReplace": true,
                    "stripReplaceChar": ""
                },
                "group": {
                    "varSourceSelector": "a[id^=\"ta_group\"]@id",
                    "extractMode": "split",
                    "fallbackValue": "",
                    "regexPattern": "",
                    "regexIndex": "",
                    "splitChar": ":",
                    "splitIndex": "1",
                    "stripBracketsWithContent": false,
                    "stripNonAscii": false,
                    "stripNumber": false,
                    "stripBoundarySpecials": false,
                    "replaceRules": [],
                    "prefix": "group:\"",
                    "suffix": "\"",
                    "casing": "none",
                    "useCustomStripReplace": true,
                    "stripReplaceChar": ""
                }
            }
        },
        "siteB": {
            "hostUrl": "",
            "buttonLabel": "",
            "destUrl": "",
            "btnContainerSelector": "",
            "variables": {}
        }
    },
    "nhentai - Find Alt": {
        "enabled": true,
        "direction": "a2b",
        "siteA": {
            "hostUrl": "https:\\/\\/nhentai\\.net\\/g\\/\\d+\\/?",
            "buttonLabel": "Find Alt",
            "destUrl": "https://nhentai.net/search?q={artist} {group} {title}",
            "btnContainerSelector": "#info > div",
            "variables": {
                "title": {
                    "varSourceSelector": "#info > h1 > span.pretty",
                    "extractMode": "regex",
                    "fallbackValue": "",
                    "regexPattern": "[^||丨]+",
                    "regexIndex": "0",
                    "splitChar": "",
                    "splitIndex": "0",
                    "stripBracketsWithContent": true,
                    "stripNonAscii": false,
                    "stripNumber": false,
                    "stripBoundarySpecials": true,
                    "replaceRules": [
                        {
                            "find": "\\([^()]*\\)|([^()]*)|\\[[^[\\]]*\\]|[[^[]]*]|【[^【】]*】|\\{[^{}]*\\}|{[^{}]*}|<[^<>]*>|《[^《》]*》|\\p{Ps}.*?\\p{Pe}",
                            "replace": " "
                        },
                        {
                            "find": "(?<=[\\p{L}\\p{N}]+)(['’']+[\\p{L}\\p{N}]+)",
                            "replace": " "
                        },
                        {
                            "find": "([\\p{Pd}=\\u007e\\uff5e])(.*?)\\1.*$",
                            "replace": " "
                        },
                        {
                            "find": "-",
                            "replace": " "
                        },
                        {
                            "find": "(?<=[\\p{L}\\p{N}]+[^\\p{L}\\p{N}]+?)(ch|chap|chapter|vol|volume|ep|episode|season|part)[^\\p{L}\\p{N}]*?(\\p{N}+|zero|one|two|three|four|five|six|seven|eight|nine|ten).*$",
                            "replace": " "
                        },
                        {
                            "find": "(?<=[^\\p{N}]{3,}[^\\p{L}\\p{N}]+?|(^|\\s)\\p{L}{3,}?)\\p{N}+.*$",
                            "replace": " "
                        },
                        {
                            "find": "(?<=[\\p{L}\\p{N}]+?)[^\\p{L}\\p{N}]+(k[oō]u?hen|chuuhen|zenpen|soushuuhen).*$",
                            "replace": " "
                        },
                        {
                            "find": "(?<=[\\p{L}\\p{N}]+[^\\p{L}\\p{N}]+?)[\\p{L}\\p{N}]+[^\\p{L}\\p{N}]+hen([^\\p{L}\\p{N}]+|$).*$",
                            "replace": " "
                        },
                        {
                            "find": "(?<=[\\p{L}\\p{N}]+[^\\p{L}\\p{N}]*?)[^\\p{L}\\p{N}]+((zoku)+|after|bangaihen)([^\\p{L}\\p{N}]+|$).*$",
                            "replace": " "
                        },
                        {
                            "find": "^([^\\p{L}\\p{N}]*(zoku|k[oō]u?hen|chuuhen|zenpen|soushuuhen|after|bangaihen)+[^\\p{L}\\p{N}]+)(?=[\\p{L}\\p{N}]+)",
                            "replace": " "
                        }
                    ],
                    "prefix": "",
                    "suffix": "",
                    "casing": "none",
                    "useCustomStripReplace": true,
                    "stripReplaceChar": ""
                },
                "artist": {
                    "varSourceSelector": "a[href^=\"/artist/\"] > span.name",
                    "extractMode": "full",
                    "fallbackValue": "",
                    "regexPattern": "",
                    "regexIndex": "",
                    "splitChar": "",
                    "splitIndex": "",
                    "stripBracketsWithContent": false,
                    "stripNonAscii": false,
                    "stripNumber": false,
                    "stripBoundarySpecials": false,
                    "replaceRules": [],
                    "prefix": "artist:\"",
                    "suffix": "\"",
                    "casing": "none",
                    "useCustomStripReplace": true,
                    "stripReplaceChar": ""
                },
                "group": {
                    "varSourceSelector": "a[href^=\"/group/\"] > span.name",
                    "extractMode": "full",
                    "fallbackValue": "",
                    "regexPattern": "",
                    "regexIndex": "",
                    "splitChar": "",
                    "splitIndex": "",
                    "stripBracketsWithContent": false,
                    "stripNonAscii": false,
                    "stripNumber": false,
                    "stripBoundarySpecials": false,
                    "replaceRules": [],
                    "prefix": "group:\"",
                    "suffix": "\"",
                    "casing": "none",
                    "useCustomStripReplace": true,
                    "stripReplaceChar": ""
                }
            }
        },
        "siteB": {
            "hostUrl": "",
            "buttonLabel": "",
            "destUrl": "",
            "btnContainerSelector": "",
            "variables": {}
        }
    },
    "WNACG (desktop) -> e-hentai": {
        "enabled": true,
        "direction": "a2b",
        "siteA": {
            "hostUrl": "https:\\/\\/www\\.wnacg\\.com\\/photos-index(-page-\\d+)?-aid-\\d+(\\.html)?",
            "buttonLabel": "e-hentai",
            "destUrl": "https://e-hentai.org/?f_search={title}",
            "btnContainerSelector": "div.asTBcell.uwconn",
            "variables": {
                "title": {
                    "varSourceSelector": "#bodywrap > h2",
                    "extractMode": "full",
                    "fallbackValue": "",
                    "regexPattern": "",
                    "regexIndex": "0",
                    "splitChar": "",
                    "splitIndex": "0",
                    "stripBracketsWithContent": true,
                    "stripNonAscii": false,
                    "stripNumber": false,
                    "stripBoundarySpecials": false,
                    "replaceRules": [],
                    "prefix": "",
                    "suffix": "",
                    "casing": "none",
                    "useCustomStripReplace": true,
                    "stripReplaceChar": ""
                }
            }
        },
        "siteB": {
            "hostUrl": "",
            "buttonLabel": "",
            "destUrl": "",
            "btnContainerSelector": "",
            "variables": {}
        }
    },
    "WNACG (desktop) -> nhentai": {
        "enabled": true,
        "direction": "a2b",
        "siteA": {
            "hostUrl": "https:\\/\\/www\\.wnacg\\.com\\/photos-index(-page-\\d+)?-aid-\\d+(\\.html)?",
            "buttonLabel": "nhentai",
            "destUrl": "https://nhentai.net/search?q={title}",
            "btnContainerSelector": "div.asTBcell.uwconn",
            "variables": {
                "title": {
                    "varSourceSelector": "#bodywrap > h2",
                    "extractMode": "full",
                    "fallbackValue": "",
                    "regexPattern": "",
                    "regexIndex": "0",
                    "splitChar": "",
                    "splitIndex": "0",
                    "stripBracketsWithContent": true,
                    "stripNonAscii": false,
                    "stripNumber": false,
                    "stripBoundarySpecials": false,
                    "replaceRules": [],
                    "prefix": "",
                    "suffix": "",
                    "casing": "none",
                    "useCustomStripReplace": true,
                    "stripReplaceChar": ""
                }
            }
        },
        "siteB": {
            "hostUrl": "",
            "buttonLabel": "",
            "destUrl": "",
            "btnContainerSelector": "",
            "variables": {}
        }
    }
},

            // Centralized CSS Configuration
            CSS_STYLES: {
                INJECTED_BUTTON: {
                    backgroundColor: '#f8f9fa', color: '#212529', border: '1px solid #dee2e6',
                    padding: '4px 10px', margin: '5px 8px', borderRadius: '4px', cursor: 'pointer',
                    fontSize: '13px', fontWeight: '600', boxShadow: '0 1px 2px rgba(0,0,0,0.1)',
                    display: 'inline-block', width: 'auto', minWidth: 'fit-content',
                    fontFamily: 'sans-serif', zIndex: '9999', lineHeight: '1.2'
                },
                PANEL_GLOBAL: `
                    /* Base Modal & Overlays */
                    #linker-overlay { position: fixed; top:0; left:0; width:100%; height:100%; background: rgba(0, 0, 0, 0.35); backdrop-filter: blur(6px); -webkit-backdrop-filter: blur(6px); z-index: 20000; display: flex; align-items: center; justify-content: center; padding: 15px; box-sizing: border-box; font-family: system-ui, -apple-system, sans-serif; }
                    #linker-modal { background: rgba(245, 245, 245, 0.85); backdrop-filter: blur(24px) saturate(150%); -webkit-backdrop-filter: blur(24px) saturate(150%); width: 95%; max-width: 580px; max-height: 92vh; display: flex; flex-direction: column; border-radius: 12px; box-shadow: 0 24px 48px rgba(0,0,0,0.2); overflow: hidden; border: 1px solid rgba(255, 255, 255, 0.6); }
                    @media (max-width: 768px) {
                        .l-flex-row, .l-grid-three { flex-direction: column; gap: 8px; }
                        .l-footer { flex-direction: row; gap: 10px; }
                        .l-io-row { flex-direction: column; }
                        .l-header { padding: 12px 16px; font-size: 16px; }
                        .l-content { padding: 15px; }
                        .l-form-group label { white-space: normal !important; word-break: break-word !important; overflow-wrap: anywhere !important; }
                        .l-form-group > div[style*="display: flex"] { flex-direction: column !important; align-items: flex-start !important; gap: 8px !important; padding: 10px 12px !important; }

                        /* Mobile layout: Dropdown + Button on Row 1, Input on Row 2 */
                        #ui-profile-select-row, #ui-var-select-row {
                            flex-wrap: wrap !important;
                            gap: 5px !important;
                        }
                        /* Row 1: Dropdown takes remaining space */
                        #ui-profile-select, #ui-var-select {
                            flex: 1 1 calc(100% - 50px) !important;
                            width: calc(100% - 50px) !important;
                        }
                        /* Row 2: Input takes 100% width, forcing it to the next line */
                        #ui-new-profile-input, #ui-new-var-input {
                            flex: 1 1 100% !important;
                            width: 100% !important;
                            order: 3;
                        }
                        /* Ensure the buttons stay on Row 1 next to dropdown */
                        #ui-profile-select-row button, #ui-var-select-row button {
                            flex: 0 0 auto !important;
                        }

                        /* Ensure the buttons stay on Row 1 next to dropdown */
                        #ui-profile-select-row button, #ui-var-select-row button {
                            flex: 0 0 auto !important;
                        }

                        /* Mobile layout: Find & Replace Rules */
                        .l-replacement-row {
                            flex-wrap: wrap !important;
                            gap: 8px 5px !important; /* 8px vertical gap, 5px horizontal gap */
                        }
                        /* Row 1: Find Input (takes up remaining space next to 30px arrow) */
                        .l-replacement-row .f-rule-find {
                            flex: 1 1 calc(100% - 35px) !important;
                            min-width: 0 !important;
                        }
                        /* Row 1: Arrow Sign (fixed 30px width) */
                        .l-replacement-row > span {
                            display: flex !important;
                            align-items: center !important;
                            justify-content: center !important;
                            flex: 0 0 30px !important;
                            padding: 0 !important;
                            margin: 0 !important;
                        }
                        /* Row 2: Replace Input (takes up remaining space next to 30px delete button) */
                        .l-replacement-row .f-rule-replace {
                            flex: 1 1 calc(100% - 35px) !important;
                            min-width: 0 !important;
                        }
                        /* Row 2: Delete Button (fixed 30px width) */
                        .l-replacement-row .l-btn-rule-del {
                            flex: 0 0 30px !important;
                            padding: 0 !important;
                            margin: 0 !important;
                            display: flex !important;
                            align-items: center !important;
                            justify-content: center !important;
                            height: 32px !important; /* Matches standard input height */
                        }

                        /* Mobile layout: Quick Strip option */
                        div:has(> label > #f-useCustomStripReplace) {
                            flex-direction: column;
                        }
                    }
                    /* Typography & Containers */
                    .l-header { background: rgba(255, 255, 255, 0.4); padding: 16px 20px; border-bottom: 1px solid rgba(0,0,0,0.08); text-align: center; font-size: 18px; font-weight: 600; color: #222; text-shadow: 0 1px 1px rgba(255,255,255,0.8); }
                    .l-content { flex-grow: 1; overflow-y: auto; padding: 20px; }
                    .l-footer { background: rgba(255, 255, 255, 0.4); padding: 15px 20px; border-top: 1px solid rgba(0,0,0,0.08); display: flex; justify-content: space-between; align-items: center; }
                    .l-card { background: rgba(255, 255, 255, 0.65); padding: 15px; border-radius: 8px; border: 1px solid rgba(255,255,255,0.7); margin-bottom: 15px; box-shadow: 0 2px 8px rgba(0,0,0,0.04); }
                    .l-card-title { font-size: 12px; font-weight: 700; text-transform: uppercase; margin-bottom: 12px; letter-spacing: 0.5px; }
                    .l-form-group { margin-bottom: 12px; }
                    .l-form-group label { display: block; font-size: 11px; font-weight: 700; color: #444; text-transform: uppercase; margin-bottom: 5px; justify-self: left !important;}
                    .l-flex-row { display: flex; gap: 12px; }
                    .l-flex-item { flex: 1; min-width: 0; }
                    .l-grid-three { display: grid; grid-template-columns: 1.2fr 1fr 1fr; gap: 12px; align-items: end; margin-bottom: 15px; }
                    .l-profile-row { display: flex; gap: 8px; margin-bottom: 15px; align-items: center; }
                    .l-form-group input[type="text"], .l-form-group input[type="number"], .l-form-group select, .l-profile-row select { width: 100%; padding: 8px; border: 1px solid rgba(0,0,0,0.15); border-radius: 5px; font-size: 13px; box-sizing: border-box; background: rgba(255,255,255,0.9); outline: none; }
                    .l-form-group input:focus, .l-form-group select:focus { border-color: #80bdff; box-shadow: 0 0 0 0.2rem rgba(0,123,255,.25); }
                    .l-hint { font-size: 11px; color: #666; margin-top: 4px; line-height: 1.4; justify-self: center;}
                    .l-hint li {
                        display: list-item !important;
                        list-style-type: disc !important;
                    }
                    code { background: rgba(0,0,0,0.05); border: 1px solid rgba(0,0,0,0.1); padding: 1px 4px; border-radius: 3px; font-family: monospace; color: #d63384; }
                    .l-checkbox-label { display: flex; align-items: center; gap: 6px; font-size: 13px; color: #333; cursor: pointer; margin-top: 5px; font-weight: 500; }
                    .l-btn { padding: 9px 18px; border-radius: 6px; border: none; font-weight: 600; cursor: pointer; font-size: 14px; transition: all 0.2s; box-shadow: 0 2px 4px rgba(0,0,0,0.08); }
                    .l-btn:hover { transform: translateY(-1px); box-shadow: 0 4px 6px rgba(0,0,0,0.12); opacity: 0.95; }
                    .l-btn:active { transform: translateY(0); box-shadow: 0 1px 2px rgba(0,0,0,0.1); }
                    .l-btn-reset { background: rgba(220, 53, 69, 0.1); color: #dc3545; border: 1px solid rgba(220, 53, 69, 0.3); box-shadow: none; font-size: 13px; }
                    .l-btn-reset:hover { background: rgba(220, 53, 69, 0.2); }
                    .l-btn-cancel { background: #f8f9fa; color: #333; border: 1px solid #ced4da; }
                    .l-btn-save { background: #007bff; color: white; border: 1px solid #0062cc; }
                    .l-btn-icon { background: #dc3545; color: white; border: none; border-radius: 6px; width: 34px; height: 34px; cursor: pointer; display: flex; align-items: center; justify-content: center; font-size: 16px; transition: background 0.2s; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
                    .l-btn-icon:hover { background: #c82333; }
                    .l-io-row { display: flex; gap: 10px; }
                    .l-btn-io { flex: 1; padding: 8px; border-radius: 6px; border: 1px solid rgba(0,0,0,0.05); font-weight: 600; font-size: 13px; cursor: pointer; display: flex; justify-content: center; align-items: center; gap: 5px; box-shadow: 0 2px 4px rgba(0,0,0,0.05); transition: opacity 0.2s; }
                    .l-btn-export { background: #17a2b8; color: white; }
                    .l-btn-import { background: #6c757d; color: white; }
                    .l-btn-io:hover { opacity: 0.85; }
                    .l-profile-status-bar { display: flex; align-items: center; justify-content: space-between; margin-bottom: 12px; background: rgba(0,0,0,0.03); padding: 8px 12px; border-radius: 6px; }
                    .l-toggle-container { display: flex; align-items: center; gap: 8px; cursor: pointer; user-select: none; font-size: 13px; font-weight: 600; }
                    .l-switch { position: relative; display: inline-block; width: 36px; height: 20px; }
                    .l-switch input { opacity: 0; width: 0; height: 0; }
                    .l-slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #ccc; transition: .2s; border-radius: 20px; }
                    .l-slider:before { position: absolute; content: ""; height: 14px; width: 14px; left: 3px; bottom: 3px; background-color: white; transition: .2s; border-radius: 50%; }
                    input:checked + .l-slider { background-color: #28a745; }
                    input:checked + .l-slider:before { transform: translateX(16px); }
                    .l-segment-control { display: flex; background: rgba(0,0,0,0.06); padding: 2px; border-radius: 6px; margin-bottom: 15px; }
                    .l-segment-btn { flex: 1; text-align: center; font-size: 12px; font-weight: 600; padding: 6px 4px; border: none; background: transparent; color: #495057; border-radius: 5px; cursor: pointer; transition: all 0.15s ease-in-out; }
                    .l-segment-btn.active { background: white; color: #007bff; box-shadow: 0 1px 3px rgba(0,0,0,0.1); }
                    .l-profile-disabled-view { opacity: 0.55; pointer-events: none; transition: opacity 0.2s ease; }
                    .l-tabs { display: flex; background: rgba(0,0,0,0.05); border-radius: 8px; padding: 4px; margin-bottom: 15px; box-shadow: inset 0 1px 3px rgba(0,0,0,0.05); }
                    .l-tab { flex: 1; text-align: center; padding: 8px; cursor: pointer; border-radius: 6px; font-weight: 600; font-size: 14px; color: #444; transition: 0.2s; }
                    .l-tab.active { background: #fff; color: #0056b3; box-shadow: 0 2px 4px rgba(0,0,0,0.08); }
                    .l-input-wrapper { display: flex; align-items: center; background: rgba(255,255,255,0.9); border: 1px solid rgba(0,0,0,0.15); border-radius: 5px; overflow: hidden; }
                    .l-input-addon { background: rgba(0,0,0,0.05); padding: 8px 12px; font-size: 11px; font-weight: 700; color: #444; text-transform: uppercase; border-right: 1px solid rgba(0,0,0,0.1); user-select: none; }
                    .l-input-wrapper input { border: none !important; background: transparent !important; padding: 8px !important; margin: 0 !important; flex: 1; min-width: 0; box-shadow: none !important; }
                    .l-card-sub-section { background: rgba(0,0,0,0.02); border: 1px dashed rgba(0,0,0,0.15); border-radius: 8px; padding: 12px; margin-bottom: 15px; }
                    .l-replacement-row { display: flex; align-items: center; gap: 8px; margin-bottom: 6px; background: rgba(0, 0, 0, 0.03); border-radius: 6px; padding: 8px; border: 1px solid rgba(0,0,0,0.05)}
                    .l-btn-mini-add { background: #007bff; color: white; border: none; padding: 4px 8px; border-radius: 4px; font-size: 11px; font-weight: 600; cursor: pointer; }
                    .l-btn-mini-add:hover { background: #0056b3; }
                    .l-btn-rule-del { background: transparent; border: none; color: #dc3545; cursor: pointer; font-size: 12px; padding: 4px; opacity: 0.6; }
                    .l-btn-rule-del:hover { opacity: 1; }
                    .l-replacement-row input { padding: 6px 8px !important; font-size: 12px !important; border-radius: 4px !important; border: 1px solid transparent !important; background: transparent !important; transition: all 0.2s ease-in-out; box-shadow: none !important; }
                    .l-replacement-row input:hover { border: 1px solid rgba(0,0,0,0.1) !important; background: rgba(255,255,255,0.4) !important; }
                    .l-replacement-row input:focus { border: 1px solid rgba(0,0,0,0.2) !important; background: rgba(255,255,255,0.9) !important; outline: none !important; }
                    .l-preview-container { background: rgba(231, 243, 255, 0.7); border: 1px solid rgba(184, 218, 255, 0.8); padding: 12px; border-radius: 6px; margin-top: 15px; }
                    .l-preview-title { font-size: 9px; color: #004085; text-transform: uppercase; font-weight: bold; margin-bottom: 4px; }
                    .l-preview-value { font-family: monospace; font-size: 13px; font-weight:bold; word-break: break-all; }

                    /* Segmented Radio Buttons for Casing */
                    .l-segment-label { flex: 1; margin: 0; cursor: pointer; }
                    .l-segment-label input[type="radio"] { display: none; }
                    .l-segment-label span { display: block; text-align: center; font-size: 12px; font-weight: 600; padding: 6px 4px; color: #495057; border-radius: 5px; transition: all 0.15s ease-in-out; }
                    .l-segment-label input[type="radio"]:checked + span { background: white; color: #007bff; box-shadow: 0 1px 3px rgba(0,0,0,0.1); }
                `
            },

            // Centralized HTML String/Template Functions
            HTML_TEMPLATES: {
                getModalShell: () => `
                    <div id="linker-overlay">
                        <div id="linker-modal">
                            <div class="l-header">Configuration</div>
                            <div class="l-content">
                                <div class="l-card" style="background: rgba(230, 240, 252, 0.8); border: 1px solid rgba(195, 215, 240, 0.7);">
                                    <div class="l-card-title" style="color: #6c757d;">Profile Selector</div>
                                    <div class="l-profile-row" id="ui-profile-select-row">
                                        <select id="ui-profile-select"></select>
                                        <input type="text" id="ui-new-profile-input" style="display:none; flex: 1; padding: 9px; border-radius: 6px; border: 1px solid rgba(0,0,0,0.15); font-size: 14px;" placeholder="Profile Name...">
                                        <button class="l-btn-icon" id="ui-btn-confirm-prof" style="display:none; background:#28a745;" title="Confirm Name">✔️</button>
                                        <button class="l-btn-icon" id="ui-btn-del" title="Delete Profile">🗑️</button>
                                    </div>
                                    <div class="l-profile-status-bar">
                                        <div style="font-size: 11px; text-transform: uppercase; font-weight: 700; color: #6c757d;">Activation State</div>
                                        <label class="l-toggle-container">
                                            <span id="ui-status-text" style="color: #6c757d;">Disabled</span>
                                            <span class="l-switch">
                                                <input type="checkbox" id="ui-profile-enabled-toggle">
                                                <span class="l-slider"></span>
                                            </span>
                                        </label>
                                    </div>
                                    <div class="l-io-row" style="flex-direction: row;">
                                        <button class="l-btn-io l-btn-export" id="ui-btn-export">📤 Export</button>
                                        <label class="l-btn-io l-btn-import" style="cursor:pointer;">
                                            📥 Import <input type="file" id="ui-btn-import" accept=".json" style="display:none;">
                                        </label>
                                    </div>
                                </div>
                                <div id="ui-profile-workspace">
                                    <div style="font-size: 11px; text-transform: uppercase; font-weight: 700; color: #6c757d; margin-bottom: 4px; margin-top: 5px;">Crosslink Direction</div>
                                    <div class="l-segment-control" id="ui-direction-control">
                                        <button type="button" class="l-segment-btn" data-dir="both"> A ⇆ B</button>
                                        <button type="button" class="l-segment-btn" data-dir="a2b"> A ➔ B</button>
                                        <button type="button" class="l-segment-btn" data-dir="b2a"> B ➔ A</button>
                                    </div>
                                    <div class="l-tabs">
                                        <div class="l-tab active" id="tab-siteA">Website A</div>
                                        <div class="l-tab" id="tab-siteB">Website B</div>
                                    </div>
                                    <div id="ui-site-form-container"></div>
                                    <div class="l-card" style="margin-top: 15px; background: rgba(255,255,255,0.85);">
                                        <div class="l-card-title" style="color: #856404;">3. VARIABLE EXTRACTION AND PROCESSING</div>
                                        <div class="l-card" style="background: rgba(230, 240, 252, 0.8); margin-bottom: 12px; padding: 12px; border: 1px solid rgba(195, 215, 240, 0.7);">
                                            <div class="l-card-title" style="color: #6c757d; font-size: 11px;">Variable Selector</div>
                                            <div class="l-profile-row" id="ui-var-select-row" style="margin-bottom: 0;">
                                                <select id="ui-var-select"></select>
                                                <input type="text" id="ui-new-var-input" style="display:none; flex: 1; padding: 8px; border-radius: 5px; border: 1px solid rgba(0,0,0,0.15); font-size: 13px;" placeholder="Variable Name...">
                                                <button class="l-btn-icon" id="ui-btn-confirm-var" style="display:none; background:#28a745;" title="Confirm Name">✔️</button>
                                                <button class="l-btn-icon" id="ui-btn-del-var" title="Delete Variable">🗑️</button>
                                            </div>
                                        </div>
                                        <div id="ui-var-form-container" style="padding-top: 20px;"></div>
                                    </div>
                                </div>
                            </div>
                            <div class="l-footer">
                                <button class="l-btn l-btn-reset" id="ui-btn-reset">Reset All</button>
                                <div style="display: flex; gap: 10px;">
                                    <button class="l-btn l-btn-cancel" id="ui-btn-cancel">Cancel</button>
                                    <button class="l-btn l-btn-save" id="ui-btn-save">Save & Reload</button>
                                </div>
                            </div>
                        </div>
                    </div>
                `,
                getSiteForm: () => `
                    <div class="l-card">
                        <div class="l-card-title" style="color: #007bff;">1. SITE URL</div>
                        <div class="l-form-group">
                            <label>Host Website URL (Where to inject the button) (Regex/Plain Text)</label>
                            <input type="text" id="f-hostUrl">
                            <div class="l-hint">Separate mirror sites with <code>|</code>.</div>
                        </div>
                        <div class="l-form-group">
                            <label>Destination Website URL (Where the button directs to) (Plain Text)</label>
                            <input type="text" id="f-destUrl">
                            <div class="l-hint" id="ui-hint-var-list"></div>
                        </div>
                        <div class="l-preview-container">
                            <div class="l-preview-title">Final Destination URL Preview</div>
                            <div id="f-final-url-preview" class="l-preview-value">Loading...</div>
                        </div>
                    </div>
                    <div class="l-card">
                        <div class="l-card-title" style="color: #6c757d;">2. BUTTON SETTING</div>
                        <div class="l-form-group l-flex-row">
                            <div class="l-flex-item">
                                <label>Button Label</label>
                                <input type="text" id="f-buttonLabel">
                            </div>
                            <div class="l-flex-item">
                                <label>Button Insert Point (CSS-Selector)</label>
                                <input type="text" id="f-btnContainerSelector">
                            </div>
                        </div>
                    </div>
                `,
                getVarForm: (varCfg) => `
                    <div>
                        <div class="l-form-group">
                            <label>Source of Variable (CSS-Selector@Attr)</label>
                            <input type="text" id="f-varSourceSelector" placeholder="Default: fallback value">
                            <div class="l-hint">Use <code>@ATTR</code> for HTML Attribute (e.g., <code>@src</code>).  Omit <code>@ATTR</code> to use innerText.</div>
                            <div class="l-hint"> Use specified string for browser data:
                                <ul style="list-style-type: disc; padding-left: 20px;">
                                    <li> <code>$currentUrl</code> (e.g., https://example.com/)</li>
                                    <li> <code>$isMobile</code> (true/false) </li>
                                    <li> <code>$language</code> (e.g., en-US) </li>
                                    <li> <code>$screenWidth</code> (e.g., 1080) </li>
                                </ul>
                            </div>
                        </div>

                        <div class="l-form-group">
                            <label>Fallback value (If source of variable is not found):</label>
                            <input type="text" id="f-fallbackValue" placeholder="Default: ''">
                            <div class="l-hint">Enter plain text, or prefix with <code>CSS:</code> to try another selector (e.g., <code>CSS:#subtitle</code>).</div>
                        </div>

                        <div class="l-form-group">
                            <label>Text Extraction Mode</label>
                            <select id="f-extractMode">
                                <option value="full" ${varCfg.extractMode === 'full' ? 'selected' : ''}>Full Text</option>
                                <option value="regex" ${varCfg.extractMode === 'regex' ? 'selected' : ''}>Regex</option>
                                <option value="split" ${varCfg.extractMode === 'split' ? 'selected' : ''}>Split</option>
                            </select>
                        </div>

                        <div id="mode-regex-panel" style="display: ${varCfg.extractMode === 'regex' ? 'block' : 'none'}; background: rgba(0,0,0,0.03); padding: 10px; border-radius: 6px; margin-bottom: 12px;">
                            <div class="l-form-group l-flex-row" style="margin-bottom: 0;">
                                <div class="l-flex-item">
                                    <label>Regex Pattern</label>
                                    <input type="text" id="f-regexPattern" style="font-family:monospace;">
                                </div>
                                <div class="l-flex-item">
                                    <label>Keep Match(es) (Start from 0)</label>
                                    <input type="text" id="f-regexIndex" placeholder="e.g., 0 or 2, 1, 3">
                                </div>
                            </div>
                            <div class="l-hint">Regex pattern supports capture groups <code>(...)</code><br>
                            Enter a single number (e.g., <code>0</code>) to keep only a match.<br>
                            Enter a comma-separated array (e.g., <code>2, 1, 3</code>) to concatenate matches in order.</div>
                        </div>

                        <div id="mode-split-panel" style="display: ${varCfg.extractMode === 'split' ? 'block' : 'none'}; background: rgba(0,0,0,0.03); padding: 10px; border-radius: 6px; margin-bottom: 12px;">
                            <div class="l-form-group l-flex-row" style="margin-bottom: 0;">
                                <div class="l-flex-item">
                                    <label>Split Delimiter</label>
                                    <input type="text" id="f-splitChar" placeholder="e.g., - or space">
                                </div>
                                <div class="l-flex-item">
                                    <label>Keep Segment(s) (Start from 0)</label>
                                    <input type="text" id="f-splitIndex" placeholder="e.g., 0 or 2, 1, 3">
                                </div>
                            </div>
                            <div class="l-hint">Enter a single number (e.g., <code>0</code>) to keep only a segment.<br>
                            Enter a comma-separated array (e.g., <code>2, 1, 3</code>) to concatenate segments in order.</div>
                        </div>

                        <div id="mode-split-panel" style="display: ${varCfg.extractMode === 'split' ? 'block' : 'none'}; background: rgba(0,0,0,0.03); padding: 10px; border-radius: 6px; margin-bottom: 12px;">
                            <div class="l-form-group l-flex-row" style="margin-bottom: 0;">
                                <div class="l-flex-item">
                                    <label>Split Delimiter</label>
                                    <input type="text" id="f-splitChar" placeholder="e.g., - or space">
                                </div>
                                <div class="l-flex-item">
                                    <label>Keep Segment(s) (Start from 0)</label>
                                    <input type="text" id="f-splitIndex" placeholder="e.g., 0 or 2, 1, 3">
                                </div>
                            </div>
                            <div class="l-hint">Enter a single number (e.g., <code>0</code>) to keep only a segment. <br>
                            Enter a comma-separated array (e.g., <code>2, 1, 3</code>) to concatenate segments in order.</div>
                        </div>
                        <details style="margin-bottom: 15px;">
                            <summary style="font-size: 12px; font-weight: 600; color: #0056b3; cursor: pointer; padding: 5px 0;">More Text Cleaners & Modifiers</summary>
                            <div style="padding-top: 10px;">
                                <div class="l-form-group">
                                    <label>Find & Replace</label>
                                    <div class="l-card-sub-section" style="margin-bottom: 15px;">
                                        <div style="display: flex; justify-content: flex-end; margin-bottom: 8px;">
                                            <button id="ui-btn-add-rule" type="button" class="l-btn-mini-add">+ Add Rule</button>
                                        </div>
                                        <div id="ui-replacement-rules-list"></div>
                                    </div>
                                </div>
                                <div class="l-form-group">
                                    <label>Quick Strip Options</label>
                                    <div style="display: flex; flex-direction: column; gap: 10px; background: rgba(0,0,0,0.02); padding: 10px 12px; border-radius: 5px; border: 1px solid rgba(0,0,0,0.05);">

                                        <div style="width: 100%; display: flex; align-items: center; gap: 8px; margin-bottom: 2px;">
                                            <label class="l-checkbox-label" style="margin:0; user-select:none;">
                                                <input type="checkbox" id="f-useCustomStripReplace" style="appearance: none; width: 14px; height: 14px; border-radius: 50%; border: 1px solid #adb5bd; outline: none; cursor: pointer; box-shadow: inset 0 0 0 2px #f8f9fa; background: ${(varCfg.useCustomStripReplace !== false) ? '#007bff' : 'transparent'};" onchange="this.style.background = this.checked ? '#007bff' : 'transparent'" ${(varCfg.useCustomStripReplace !== false) ? 'checked' : ''}>
                                                <span style="font-size: 12px; font-weight: 600; color: #495057;">Replace stripped text with:</span>
                                            </label>
                                            <input type="text" id="f-stripReplaceChar" value="${varCfg.stripReplaceChar || ''}" placeholder="Default: single space" ${(varCfg.useCustomStripReplace !== false) ? '' : 'disabled'} style="flex: 1; padding: 2px 8px; font-size: 12px; border: 1px solid #ced4da; border-radius: 4px; height: 24px; background: ${(varCfg.useCustomStripReplace !== false) ? '#fff' : '#e9ecef'};">
                                        </div>
                                        <hr style="width: 100%; border: 0; border-top: 1px solid rgba(0,0,0,0.08); margin: 0;">

                                        <label class="l-checkbox-label" style="margin:0;"><input type="checkbox" id="f-stripBracketsWithContent" ${varCfg.stripBracketsWithContent ? 'checked' : ''}> 1. Strip Brackets (with enclosed content)</label>
                                        <label class="l-checkbox-label" style="margin:0;"><input type="checkbox" id="f-stripBoundarySpecials" ${varCfg.stripBoundarySpecials ? 'checked' : ''}> 2. Strip Special Characters (at word boundary)</label>
                                        <label class="l-checkbox-label" style="margin:0;"><input type="checkbox" id="f-stripNonAscii" ${varCfg.stripNonAscii ? 'checked' : ''}> 3. Strip Non-ASCII Characters</label>
                                        <label class="l-checkbox-label" style="margin:0;"><input type="checkbox" id="f-stripNumber" ${varCfg.stripNumber ? 'checked' : ''}> 4. Strip Numbers</label>
                                    </div>
                                </div>
                                <div class="l-form-group">
                                    <label>Text Casing</label>
                                    <div class="l-segment-control">
                                        <label class="l-segment-label"><input type="radio" name="f-casing" value="none" ${varCfg.casing === 'none' ? 'checked' : ''}><span>Original</span></label>
                                        <label class="l-segment-label"><input type="radio" name="f-casing" value="lower" ${varCfg.casing === 'lower' ? 'checked' : ''}><span>lower</span></label>
                                        <label class="l-segment-label"><input type="radio" name="f-casing" value="upper" ${varCfg.casing === 'upper' ? 'checked' : ''}><span>UPPER</span></label>
                                        <label class="l-segment-label"><input type="radio" name="f-casing" value="title" ${varCfg.casing === 'title' ? 'checked' : ''}><span>Title Case</span></label>
                                    </div>
                                </div>
                                <div class="l-form-group">
                                    <label>Add Prefix & Suffix</label>
                                    <div style="display: flex; gap: 10px; background: rgba(0,0,0,0.02); padding: 10px; border-radius: 5px; border: 1px solid rgba(0,0,0,0.05); flex-wrap: wrap;">
                                        <div class="l-flex-item l-input-wrapper" style="margin:0;">
                                            <span class="l-input-addon">Prefix</span>
                                            <input type="text" id="f-prefix">
                                        </div>
                                        <div class="l-flex-item l-input-wrapper" style="margin:0;">
                                            <span class="l-input-addon">Suffix</span>
                                            <input type="text" id="f-suffix">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </details>
                        <div class="l-preview-container">
                            <div class="l-preview-title">Final Variable Preview</div>
                            <div id="f-preview-value" class="l-preview-value">Loading...</div>
                        </div>
                    </div>
                `,
                getRuleRow: (rule, idx) => `
                    <input type="text" class="f-rule-find" data-idx="${idx}" placeholder="Find (Regex Pattern)..." style="flex: 1; font-family:monospace;">
                    <span style="color: rgba(0,0,0,0.3);">➔</span>
                    <input type="text" class="f-rule-replace" data-idx="${idx}" placeholder="Replace with..." style="flex: 1; font-family:monospace;">
                    <button class="l-btn-rule-del" data-idx="${idx}" title="Remove Rule">❌</button>
                `,
                getVarHintTag: (k) => `<code class="ui-hint-var-tag" style="cursor: pointer; background: rgba(0,123,255,0.1); color: #007bff; padding: 2px 5px; border-radius: 4px; display: inline-block; margin: 2px;" title="Click to insert">{${k}}</code>`
            }
        },

        // ---------------------------------------------------------------------
        // MODULE 2: BACKGROUND SERVICES
        // ---------------------------------------------------------------------
        Services: {

            // Sub-module: Local Storage Management
            DataStore: {
                load() {
                    let data = GM_getValue(CrosslinkerApp.Config.STORAGE_KEY, null);
                    if (!data) {
                        data = JSON.parse(JSON.stringify(CrosslinkerApp.Config.INITIAL_DATA));
                        GM_setValue(CrosslinkerApp.Config.STORAGE_KEY, data);
                    }
                    return data;
                },
                save(data) {
                    GM_setValue(CrosslinkerApp.Config.STORAGE_KEY, data);
                },
                downloadJSON(data) {
                    const d = new Date();
                    const pad = (n) => n.toString().padStart(2, '0');
                    const dateStr = `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())}_${pad(d.getHours())}-${pad(d.getMinutes())}-${pad(d.getSeconds())}`;

                    const cleanedData = structuredClone(data);
                    const blob = new Blob([JSON.stringify(cleanedData, null, 4)], { type: 'application/json;charset=utf-8' });
                    const url = URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = `Dual-Websites_Crosslinker_backup_${dateStr}.json`;
                    a.style.display = 'none';
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                    URL.revokeObjectURL(url);
                },
                importJSON(file, onSuccess) {
                    const reader = new FileReader();
                    reader.onload = (e) => {
                        try {
                            const parsed = JSON.parse(e.target.result);
                            if (parsed._meta && parsed.profiles) onSuccess(parsed.profiles); // Old export format support
                            else onSuccess(parsed);
                        } catch(err) { alert("Failed to read JSON."); }
                    };
                    reader.readAsText(file);
                }
            },

            // Sub-module: Variable Extraction and Text Cleaning Pipeline
            TextProcessor: {
                applyReplacements(text, rulesArray) {
                    if (!rulesArray || rulesArray.length === 0) return text;
                    rulesArray.forEach(rule => {
                        if (rule.find !== '') {
                            try {
                                const re = new RegExp(rule.find, 'giu');
                                text = text.replace(re, rule.replace);
                            } catch(e) {}
                        }
                    });
                    return text;
                },
                process(rawText, varCfg) {
                    if (!rawText) return null;
                    let extracted = "";

                    // 0. Extraction (full, split, regex)
                    if (varCfg.extractMode === 'regex') {
                        try {
                            const re = new RegExp(varCfg.regexPattern, 'g');
                            const matches = [...rawText.matchAll(re)];
                            const indices = String(varCfg.regexIndex || "0").split(',').map(n => parseInt(n.trim()));
                            extracted = indices.map(i => {
                                const m = matches.at(i);
                                return m ? (m[1] !== undefined ? m[1] : m[0]) : '';
                            }).join('');
                        } catch(e) { return null; }
                    } else if (varCfg.extractMode === 'split') {
                        const parts = rawText.split(varCfg.splitChar);
                        const indices = String(varCfg.splitIndex || "0").split(',').map(n => parseInt(n.trim()));
                        extracted = indices.map(i => parts[i] || '').join('');
                    } else {
                        extracted = rawText;
                    }

                    if (!extracted) return null;

                    // 1. Find & Replace Rules (Executes first on the raw extracted text)
                    extracted = this.applyReplacements(extracted, varCfg.replaceRules);

                    // 2. Quick Strip Options (Sanitizes the text after replacements are done)
                    const useCustom = varCfg.useCustomStripReplace !== false; // Defaults to ON
                    // Fallback to a single space ' ' if the option is active but the field value is empty or undefined
                    const stripRep = useCustom ? (varCfg.stripReplaceChar ? varCfg.stripReplaceChar : ' ') : '';

                    // Step 2.1: Strip Brackets with Content (Must stay first to protect structural pairs)
                    if (varCfg.stripBracketsWithContent) {
                        extracted = extracted.replace(/\([^()]*\)|([^()]*)|\[[^[\]]*\]|[[^[]]*]|【[^【】]*】|\{[^{}]*\}|{[^{}]*}|<[^<>]*>|《[^《》]*》|\p{Ps}.*?\p{Pe}/gu, stripRep);
                    }

                    // Step 2.2: Strip Boundary Specials (Evaluates context while numbers and non-ASCII are still intact)
                    if (varCfg.stripBoundarySpecials) extracted = extracted.replace(/(?<![\p{L}\p{N}])[^\p{L}\p{N}\s]+|[^\p{L}\p{N}\s]+(?![\p{L}\p{N}])/gu, stripRep);

                    // Step 2.3: Strip Non-ASCII
                    if (varCfg.stripNonAscii) extracted = extracted.replace(/[^\x00-\x7F]+/g, stripRep);

                    // Step 2.4: Strip Numbers
                    if (varCfg.stripNumber) extracted = extracted.replace(/\d+/g, stripRep);

                    // 3. Space Cleanup (Trims extra spaces left over from stripping/replacing)
                    extracted = extracted.replace(/\s+/g, ' ').trim();

                    // 4. Text Casing
                    if (varCfg.casing === 'lower') extracted = extracted.toLowerCase();
                    if (varCfg.casing === 'upper') extracted = extracted.toUpperCase();
                    if (varCfg.casing === 'title') extracted = extracted.toLowerCase().split(' ').map(s => s.charAt(0).toUpperCase() + s.substring(1)).join(' ');

                    // 5. Add Prefix & Suffix
                    return (varCfg.prefix || "") + extracted + (varCfg.suffix || "");
                },
                extractVariablesMap(siteConfig) {
                    let results = {};
                    if (!siteConfig.variables) return results;

                    for (const [varName, varConfig] of Object.entries(siteConfig.variables)) {
                        let sourceText = "";
                        if (varConfig.varSourceSelector) {
                            try {
                                const src = varConfig.varSourceSelector.trim();

                                // NEW: Intercept Magic Metadata Variables
                                if (src === '$isMobile') {
                                    sourceText = /Mobi|Android/i.test(navigator.userAgent) ? 'true' : 'false';
                                } else if (src === '$language') {
                                    sourceText = navigator.language || navigator.userLanguage || '';
                                } else if (src === '$screenWidth') {
                                    sourceText = String(window.innerWidth || window.screen.width);
                                } else if (src === '$currentUrl') {
                                    sourceText = window.location.href;
                                } else {
                                    // EXISTING: Standard DOM Extraction
                                    const [selector, attr] = src.split('@');
                                    const el = document.querySelector(selector);
                                    if (el) sourceText = attr ? el.getAttribute(attr) : (el.innerText || el.textContent);
                                }

                                // NEW: Unified Fallback Handler (Supports Plain Text & CSS Selectors)
                                if (!sourceText && varConfig.fallbackValue) {
                                    const fb = varConfig.fallbackValue.trim();
                                    if (fb.startsWith('CSS:')) {
                                        const [fSel, fAttr] = fb.substring(4).split('@');
                                        const fEl = document.querySelector(fSel);
                                        if (fEl) sourceText = fAttr ? fEl.getAttribute(fAttr) : (fEl.innerText || fEl.textContent);
                                    } else {
                                        sourceText = fb;
                                    }
                                }

                                // If target STILL has no text after trying fallback, warn.
                                if (!sourceText) {
                                    results[varName] = "⚠️ Not Found / Empty";
                                    continue;
                                }
                            } catch (e) { results[varName] = "❌ Invalid CSS Selector"; continue; }
                        } else {
                            // When the Source input is left completely empty:
                            sourceText = varConfig.fallbackValue || "";
                            if (!sourceText) {
                                results[varName] = "⚠️ Source & Fallback empty";
                                continue;
                            }
                        }
                        results[varName] = this.process(sourceText, varConfig) || "";
                    }
                    return results;
                }
            },

            // Sub-module: Evaluates URLs and Injects Buttons dynamically
            InjectionEngine: {
                checkSiteMatch(url, patternStr) {
                    if (!patternStr) return false;
                    return patternStr.split('|').some(p => {
                        const trimmed = p.trim();
                        if (!trimmed) return false;
                        const isRegex = /[\\[\]{}+*^$]/.test(trimmed);
                        if (isRegex) {
                            try { return new RegExp(trimmed).test(url); } catch (e) { return false; }
                        }
                        return url.includes(trimmed);
                    });
                },
                renderButton(profileName, activeSiteConfig) {
                    if (!activeSiteConfig.btnContainerSelector || !activeSiteConfig.destUrl) return;

                    const targetContainer = document.querySelector(activeSiteConfig.btnContainerSelector);
                    if (!targetContainer) return;

                    const safeProfileName = profileName.replace(/[^a-zA-Z0-9]/g, '');
                    const currentBtnId = `crosslinker-${safeProfileName}`;
                    const varsMap = CrosslinkerApp.Services.TextProcessor.extractVariablesMap(activeSiteConfig);
                    const cleanVarsForUrl = {};
                    let stringifiedFingerprint = "";

                    for (const [vName, vVal] of Object.entries(varsMap)) {
                        let safeVal = vVal;
                        if (!safeVal || safeVal.includes('⚠️') || safeVal.includes('❌')) safeVal = "";
                        cleanVarsForUrl[vName] = safeVal;
                        stringifiedFingerprint += safeVal;
                    }

                    const existing = document.getElementById(currentBtnId);
                    if (stringifiedFingerprint.trim() === "") {
                        if (existing) existing.remove();
                        return;
                    }
                    if (existing) {
                        if (existing.dataset.linkedFingerprint !== stringifiedFingerprint) existing.remove();
                        else return;
                    }

                    const btn = document.createElement('button');
                    btn.id = currentBtnId;
                    btn.dataset.linkedFingerprint = stringifiedFingerprint;
                    btn.innerText = `${activeSiteConfig.buttonLabel}`;

                    // Native static styling pulled cleanly from Module 1
                    Object.assign(btn.style, CrosslinkerApp.Config.CSS_STYLES.INJECTED_BUTTON);

                    btn.onclick = (e) => {
                        e.preventDefault();
                        let finalUrl = activeSiteConfig.destUrl.split('|')[0].trim();
                        for (const [vName, vVal] of Object.entries(cleanVarsForUrl)) {
                            finalUrl = finalUrl.replace(new RegExp(`{${vName}}`, 'g'), encodeURIComponent(vVal));
                        }
                        window.location.href = finalUrl;
                    };
                    targetContainer.appendChild(btn);
                },
                inject() {
                    const profiles = CrosslinkerApp.Services.DataStore.load();
                    const url = window.location.href;
                    for (const [profileName, profile] of Object.entries(profiles)) {
                        if (profile.enabled === false) continue;
                        const direction = profile.direction || 'both';
                        if (direction === 'both' || direction === 'a2b') {
                            if (this.checkSiteMatch(url, profile.siteA.hostUrl)) this.renderButton(profileName, profile.siteA);
                        }
                        if (direction === 'both' || direction === 'b2a') {
                            if (this.checkSiteMatch(url, profile.siteB.hostUrl)) this.renderButton(profileName, profile.siteB);
                        }
                    }
                }
            }
        },

        // ---------------------------------------------------------------------
        // MODULE 3: USER INTERFACE SYSTEM
        // ---------------------------------------------------------------------
        UI: {

            // Sub-module: CSS Injector
            StyleManager: {
                injectStyles() {
                    GM_addStyle(CrosslinkerApp.Config.CSS_STYLES.PANEL_GLOBAL);
                }
            },

            // Sub-module: Form Generic Synchronizer
            FormManager: {
                /** Automatically binds all input/select fields starting with "f-" to data object properties */
                syncFields(containerId, dataObject, callback) {
                    const container = document.getElementById(containerId);
                    if (!container) return;
                    container.querySelectorAll('input, select').forEach(el => {
                        // Support both f- IDs (text/checkboxes) and f- Names (radio groups)
                        let key = '';
                        if (el.id && el.id.startsWith('f-')) key = el.id.replace('f-', '');
                        else if (el.name && el.name.startsWith('f-')) key = el.name.replace('f-', '');
                        else return;

                        // Initial State Sync
                        if (dataObject[key] !== undefined) {
                            if (el.type === 'checkbox') el.checked = !!dataObject[key];
                            else if (el.type === 'radio') el.checked = (el.value === dataObject[key]);
                            else el.value = dataObject[key];
                        }

                        // Event Listener Bindings
                        const eventType = (el.type === 'checkbox' || el.type === 'radio' || el.tagName === 'SELECT') ? 'change' : 'input';
                        el.addEventListener(eventType, () => {
                            if (el.type === 'checkbox') dataObject[key] = el.checked;
                            else if (el.type === 'number') dataObject[key] = parseInt(el.value) || 0;
                            else dataObject[key] = el.value; // Automatically handles text, select, and radio!

                            if (callback) callback(key, dataObject[key]);
                        });
                    });
                }
            },

            // Sub-module: Modal Render and Controller
            ModalController: {
                state: {
                    draftProfiles: {},
                    currentProfileKey: '',
                    currentTab: 'siteA',
                    currentVarKey: ''
                },

                open() {
                    this.state.draftProfiles = CrosslinkerApp.Services.DataStore.load();
                    this.state.currentProfileKey = Object.keys(this.state.draftProfiles)[0];
                    this.state.currentTab = 'siteA';

                    // Prepare internal variable fallback
                    const initVars = this.state.draftProfiles[this.state.currentProfileKey][this.state.currentTab].variables || {};
                    this.state.currentVarKey = Object.keys(initVars).length > 0 ? Object.keys(initVars)[0] : '__TEMP_NEW_VAR__';
                    if (this.state.currentVarKey === '__TEMP_NEW_VAR__') {
                        this.state.draftProfiles[this.state.currentProfileKey][this.state.currentTab].variables = { '__TEMP_NEW_VAR__': JSON.parse(JSON.stringify(CrosslinkerApp.Config.VAR_BLUEPRINT)) };
                    }

                    const overlay = document.createElement('div');
                    overlay.id = 'linker-overlay-wrapper';
                    overlay.innerHTML = CrosslinkerApp.Config.HTML_TEMPLATES.getModalShell();
                    document.body.appendChild(overlay);

                    this.updateProfileDropdown();
                    this.renderMasterForm();
                    this.bindEvents(overlay);
                },

                updateProfileDropdown() {
                    const selEl = document.getElementById('ui-profile-select');
                    if (!selEl) return;
                    selEl.innerHTML = '';
                    Object.keys(this.state.draftProfiles).forEach(k => {
                        if (k === '__TEMP_NEW_PROFILE__') return;
                        const opt = document.createElement('option');
                        opt.value = k;
                        opt.textContent = (this.state.draftProfiles[k].enabled === false ? ' [⏸] ' : ' [●] ') + k;
                        if (k === this.state.currentProfileKey) opt.selected = true;
                        selEl.appendChild(opt);
                    });
                    const newOpt = document.createElement('option');
                    newOpt.value = 'ADD_NEW';
                    newOpt.innerText = '+ Add New Profile...';
                    if (this.state.currentProfileKey === '__TEMP_NEW_PROFILE__') newOpt.selected = true;
                    selEl.appendChild(newOpt);
                },

                updateVarDropdown() {
                    const selEl = document.getElementById('ui-var-select');
                    const nvIn = document.getElementById('ui-new-var-input');
                    const cvBtn = document.getElementById('ui-btn-confirm-var');
                    const dvBtn = document.getElementById('ui-btn-del-var');
                    if(!selEl) return;

                    selEl.innerHTML = '';
                    const siteVars = this.state.draftProfiles[this.state.currentProfileKey][this.state.currentTab].variables || {};
                    Object.keys(siteVars).forEach(k => {
                        if (k === '__TEMP_NEW_VAR__') return;
                        const opt = document.createElement('option');
                        opt.value = k;
                        opt.innerText = `{${k}}`;
                        if (k === this.state.currentVarKey) opt.selected = true;
                        selEl.appendChild(opt);
                    });

                    const newOpt = document.createElement('option');
                    newOpt.value = 'ADD_NEW';
                    newOpt.innerText = '+ Add New Variable...';
                    if (this.state.currentVarKey === '__TEMP_NEW_VAR__') newOpt.selected = true;
                    selEl.appendChild(newOpt);

                    if (this.state.currentVarKey === '__TEMP_NEW_VAR__') {
                        nvIn.style.display = 'block'; cvBtn.style.display = 'flex'; dvBtn.style.display = 'none';
                    } else {
                        nvIn.style.display = 'none'; nvIn.value = ''; cvBtn.style.display = 'none'; dvBtn.style.display = 'flex';
                    }
                },

                renderMasterForm() {
                    const profile = this.state.draftProfiles[this.state.currentProfileKey];
                    const isEnabled = profile.enabled !== false;

                    document.getElementById('ui-profile-enabled-toggle').checked = isEnabled;
                    document.getElementById('ui-status-text').textContent = isEnabled ? 'Active' : 'Disabled';
                    document.getElementById('ui-status-text').style.color = isEnabled ? '#28a745' : '#6c757d';

                    const workspace = document.getElementById('ui-profile-workspace');
                    if (isEnabled) workspace.classList.remove('l-profile-disabled-view');
                    else workspace.classList.add('l-profile-disabled-view');

                    const activeDir = profile.direction || 'both';
                    document.querySelectorAll('#ui-direction-control .l-segment-btn').forEach(btn => {
                        if (btn.getAttribute('data-dir') === activeDir) btn.classList.add('active');
                        else btn.classList.remove('active');
                    });

                    document.getElementById('tab-siteA').classList.toggle('active', this.state.currentTab === 'siteA');
                    document.getElementById('tab-siteB').classList.toggle('active', this.state.currentTab === 'siteB');

                    this.renderSiteForm();
                    this.updateVarDropdown();
                    this.renderVarForm();
                },

                renderSiteForm() {
                    const siteCfg = this.state.draftProfiles[this.state.currentProfileKey][this.state.currentTab];
                    const container = document.getElementById('ui-site-form-container');
                    container.innerHTML = CrosslinkerApp.Config.HTML_TEMPLATES.getSiteForm(siteCfg);

                    CrosslinkerApp.UI.FormManager.syncFields('ui-site-form-container', siteCfg, () => {
                        this.updatePreview();
                    });

                    this.updateVariableHint();
                    this.updatePreview();
                },

                renderVarForm() {
                    const varCfg = this.state.draftProfiles[this.state.currentProfileKey][this.state.currentTab].variables[this.state.currentVarKey];
                    const container = document.getElementById('ui-var-form-container');

                    if (!varCfg) {
                        container.innerHTML = `<div style="padding: 10px; color:#666; font-size:12px;">No variables defined. Add one above!</div>`;
                        return;
                    }
                    container.innerHTML = CrosslinkerApp.Config.HTML_TEMPLATES.getVarForm(varCfg);

                    CrosslinkerApp.UI.FormManager.syncFields('ui-var-form-container', varCfg, (key) => {
                        if (key === 'extractMode') {
                            const modeSelect = document.getElementById('f-extractMode');
                            document.getElementById('mode-regex-panel').style.display = modeSelect.value === 'regex' ? 'block' : 'none';
                            document.getElementById('mode-split-panel').style.display = modeSelect.value === 'split' ? 'block' : 'none';
                        }
                        if (key === 'useCustomStripReplace') {
                            const replaceInput = document.getElementById('f-stripReplaceChar');
                            if (replaceInput) {
                                replaceInput.disabled = !varCfg.useCustomStripReplace;
                                replaceInput.style.background = varCfg.useCustomStripReplace ? '#fff' : '#e9ecef';
                            }
                        }
                        this.updatePreview();
                    });
                    this.renderRules();
                    this.updatePreview();
                },

                renderRules() {
                    const listEl = document.getElementById('ui-replacement-rules-list');
                    if (!listEl) return;
                    const varCfg = this.state.draftProfiles[this.state.currentProfileKey][this.state.currentTab].variables[this.state.currentVarKey];
                    const rules = varCfg.replaceRules || [];
                    listEl.innerHTML = '';

                    rules.forEach((rule, idx) => {
                        const row = document.createElement('div');
                        row.className = 'l-replacement-row';
                        row.innerHTML = CrosslinkerApp.Config.HTML_TEMPLATES.getRuleRow(rule, idx);
                        row.querySelector('.f-rule-find').value = rule.find;
                        row.querySelector('.f-rule-replace').value = rule.replace;
                        listEl.appendChild(row);
                    });
                },

                updatePreview() {
                    const siteCfg = this.state.draftProfiles[this.state.currentProfileKey][this.state.currentTab];
                    let compiledUrl = (siteCfg.destUrl || '').split('|')[0].trim();
                    const varsMap = CrosslinkerApp.Services.TextProcessor.extractVariablesMap(siteCfg);

                    for (const [vName, vVal] of Object.entries(varsMap)) {
                        if (vName === '__TEMP_NEW_VAR__') continue;
                        let displayVal = vVal;
                        if (!displayVal || displayVal.includes('⚠️') || displayVal.includes('❌')) displayVal = "";
                        compiledUrl = compiledUrl.replace(new RegExp(`{${vName}}`, 'g'), encodeURIComponent(displayVal));

                        if (vName === this.state.currentVarKey) {
                            const pEl = document.getElementById('f-preview-value');
                            if (pEl) {
                                if (vVal && (vVal.includes('❌') || vVal.includes('⚠️'))) pEl.style.color = '#dc3545';
                                else if (!vVal) pEl.style.color = '#6c757d';
                                else pEl.style.color = '#0056b3';
                                pEl.innerText = vVal || "(empty / not found)";
                            }
                        }
                    }
                    const urlPreviewEl = document.getElementById('f-final-url-preview');
                    if (urlPreviewEl) urlPreviewEl.innerText = compiledUrl;
                },

                updateVariableHint() {
                    const hintContainer = document.getElementById('ui-hint-var-list');
                    if (!hintContainer) return;
                    const siteVars = this.state.draftProfiles[this.state.currentProfileKey][this.state.currentTab].variables || {};
                    const varTags = Object.keys(siteVars).filter(k => k !== '__TEMP_NEW_VAR__')
                        .map(k => CrosslinkerApp.Config.HTML_TEMPLATES.getVarHintTag(k)).join(' ');
                    hintContainer.innerHTML = `Separate mirror sites with <code>|</code>.<br>Available variables (Click to insert): ${varTags || 'None'}.`;
                },

                bindEvents(overlay) {
                    const self = this; // Maintain reference inside delegation handlers

                    // EVENT DELEGATION: CHANGE events
                    overlay.addEventListener('change', (e) => {
                        const target = e.target;

                        // Profile Enable Toggle
                        if (target.id === 'ui-profile-enabled-toggle') {
                            self.state.draftProfiles[self.state.currentProfileKey].enabled = target.checked;
                            self.updateProfileDropdown();
                            self.renderMasterForm();
                        }
                        // Profile Selector Dropdown
                        else if (target.id === 'ui-profile-select') {
                            const newProfInput = document.getElementById('ui-new-profile-input');
                            const confirmProfBtn = document.getElementById('ui-btn-confirm-prof');
                            const delBtn = document.getElementById('ui-btn-del');

                            if (target.value === 'ADD_NEW') {
                                newProfInput.style.display = 'block'; confirmProfBtn.style.display = 'flex'; delBtn.style.display = 'none';
                                self.state.draftProfiles['__TEMP_NEW_PROFILE__'] = JSON.parse(JSON.stringify(CrosslinkerApp.Config.PROFILE_BLUEPRINT));
                                self.state.currentProfileKey = '__TEMP_NEW_PROFILE__';
                                newProfInput.focus();
                                self.state.currentVarKey = '__TEMP_NEW_VAR__';
                                self.state.draftProfiles[self.state.currentProfileKey][self.state.currentTab].variables = { '__TEMP_NEW_VAR__': JSON.parse(JSON.stringify(CrosslinkerApp.Config.VAR_BLUEPRINT)) };
                                self.renderMasterForm();
                            } else {
                                newProfInput.style.display = 'none'; newProfInput.value = ''; confirmProfBtn.style.display = 'none'; delBtn.style.display = 'flex';
                                self.state.currentProfileKey = target.value;
                                const siteVars = self.state.draftProfiles[self.state.currentProfileKey][self.state.currentTab].variables || {};
                                self.state.currentVarKey = Object.keys(siteVars).length > 0 ? Object.keys(siteVars)[0] : '__TEMP_NEW_VAR__';
                                if (self.state.currentVarKey === '__TEMP_NEW_VAR__') {
                                    self.state.draftProfiles[self.state.currentProfileKey][self.state.currentTab].variables = { '__TEMP_NEW_VAR__': JSON.parse(JSON.stringify(CrosslinkerApp.Config.VAR_BLUEPRINT)) };
                                }
                                self.renderMasterForm();
                            }
                        }
                        // Variable Selector Dropdown
                        else if (target.id === 'ui-var-select') {
                            const newVarInput = document.getElementById('ui-new-var-input');
                            const confirmVarBtn = document.getElementById('ui-btn-confirm-var');
                            const delVarBtn = document.getElementById('ui-btn-del-var');

                            if (target.value === 'ADD_NEW') {
                                newVarInput.style.display = 'block'; confirmVarBtn.style.display = 'flex'; delVarBtn.style.display = 'none';
                                if (!self.state.draftProfiles[self.state.currentProfileKey][self.state.currentTab].variables) {
                                    self.state.draftProfiles[self.state.currentProfileKey][self.state.currentTab].variables = {};
                                }
                                self.state.draftProfiles[self.state.currentProfileKey][self.state.currentTab].variables['__TEMP_NEW_VAR__'] = JSON.parse(JSON.stringify(CrosslinkerApp.Config.VAR_BLUEPRINT));
                                self.state.currentVarKey = '__TEMP_NEW_VAR__';
                                newVarInput.focus();
                                self.renderVarForm();
                            } else {
                                newVarInput.style.display = 'none'; newVarInput.value = ''; confirmVarBtn.style.display = 'none'; delVarBtn.style.display = 'flex';
                                self.state.currentVarKey = target.value;
                                self.renderVarForm();
                            }
                        }
                        // Import File Action
                        else if (target.id === 'ui-btn-import') {
                            if (target.files.length > 0) {
                                CrosslinkerApp.Services.DataStore.importJSON(target.files[0], (data) => {
                                    self.state.draftProfiles = data;
                                    if (self.state.draftProfiles['__TEMP_NEW_PROFILE__']) delete self.state.draftProfiles['__TEMP_NEW_PROFILE__'];
                                    self.state.currentProfileKey = Object.keys(self.state.draftProfiles)[0];
                                    self.updateProfileDropdown();
                                    self.renderMasterForm();
                                    alert("Profiles imported successfully! Click 'Save & Reload' to apply.");
                                });
                            }
                        }
                    });

                    // EVENT DELEGATION: INPUT events (For dynamic replacement rule arrays)
                    overlay.addEventListener('input', (e) => {
                        const target = e.target;
                        if (target.classList.contains('f-rule-find') || target.classList.contains('f-rule-replace')) {
                            const idx = target.getAttribute('data-idx');
                            const field = target.classList.contains('f-rule-find') ? 'find' : 'replace';
                            self.state.draftProfiles[self.state.currentProfileKey][self.state.currentTab].variables[self.state.currentVarKey].replaceRules[idx][field] = target.value;
                            self.updatePreview();
                        }
                    });

                    // EVENT DELEGATION: CLICK events
                    overlay.addEventListener('click', (e) => {
                        const target = e.target;

                        // Tab Switching
                        if (target.closest('#tab-siteA') && self.state.currentTab !== 'siteA') {
                            self.state.currentTab = 'siteA';
                            self.checkTabInitialVars();
                            self.renderMasterForm();
                        } else if (target.closest('#tab-siteB') && self.state.currentTab !== 'siteB') {
                            self.state.currentTab = 'siteB';
                            self.checkTabInitialVars();
                            self.renderMasterForm();
                        }

                        // Direction Segments
                        const segmentBtn = target.closest('.l-segment-btn');
                        if (segmentBtn) {
                            self.state.draftProfiles[self.state.currentProfileKey].direction = segmentBtn.getAttribute('data-dir');
                            self.renderMasterForm();
                        }

                        // Profile Actions
                        else if (target.closest('#ui-btn-confirm-prof')) {
                            const newProfInput = document.getElementById('ui-new-profile-input');
                            const newName = newProfInput.value.trim().replace(/[^a-zA-Z0-9_\- ]/g, '');
                            if (!newName) { alert("Please enter a valid profile name."); newProfInput.focus(); return; }
                            if (self.state.draftProfiles[newName]) { alert("A profile with this name already exists."); newProfInput.focus(); return; }

                            self.state.draftProfiles[newName] = self.state.draftProfiles['__TEMP_NEW_PROFILE__'];
                            delete self.state.draftProfiles['__TEMP_NEW_PROFILE__'];
                            self.state.currentProfileKey = newName;

                            newProfInput.style.display = 'none'; newProfInput.value = '';
                            document.getElementById('ui-btn-confirm-prof').style.display = 'none';
                            document.getElementById('ui-btn-del').style.display = 'flex';

                            self.checkTabInitialVars();
                            self.updateProfileDropdown();
                            self.renderMasterForm();
                        } else if (target.closest('#ui-btn-del')) {
                            if (confirm(`Are you sure you want to delete profile: "${self.state.currentProfileKey}"?`)) {
                                delete self.state.draftProfiles[self.state.currentProfileKey];
                                if (Object.keys(self.state.draftProfiles).length === 0) self.state.draftProfiles = JSON.parse(JSON.stringify(CrosslinkerApp.Config.INITIAL_DATA));
                                self.state.currentProfileKey = Object.keys(self.state.draftProfiles)[0];
                                self.updateProfileDropdown();
                                self.renderMasterForm();
                            }
                        }

                        // Variable Actions
                        else if (target.closest('#ui-btn-confirm-var')) {
                            const newVarInput = document.getElementById('ui-new-var-input');
                            const newName = newVarInput.value.trim().replace(/[^a-zA-Z0-9_]/g, '');
                            if (!newName) { alert("Please enter a valid variable name."); newVarInput.focus(); return; }
                            if (self.state.draftProfiles[self.state.currentProfileKey][self.state.currentTab].variables[newName]) {
                                alert("A variable with this name already exists in this site tab."); newVarInput.focus(); return;
                            }

                            self.state.draftProfiles[self.state.currentProfileKey][self.state.currentTab].variables[newName] = self.state.draftProfiles[self.state.currentProfileKey][self.state.currentTab].variables['__TEMP_NEW_VAR__'];
                            delete self.state.draftProfiles[self.state.currentProfileKey][self.state.currentTab].variables['__TEMP_NEW_VAR__'];
                            self.state.currentVarKey = newName;

                            newVarInput.style.display = 'none'; newVarInput.value = '';
                            document.getElementById('ui-btn-confirm-var').style.display = 'none';
                            document.getElementById('ui-btn-del-var').style.display = 'flex';

                            self.updateVarDropdown();
                            self.renderVarForm();
                            self.updateVariableHint();
                        } else if (target.closest('#ui-btn-del-var')) {
                            if (confirm(`Are you sure you want to delete the variable: {${self.state.currentVarKey}}?`)) {
                                delete self.state.draftProfiles[self.state.currentProfileKey][self.state.currentTab].variables[self.state.currentVarKey];
                                const remainingVars = Object.keys(self.state.draftProfiles[self.state.currentProfileKey][self.state.currentTab].variables);
                                if (remainingVars.length > 0) {
                                    self.state.currentVarKey = remainingVars[0];
                                } else {
                                    self.state.currentVarKey = '__TEMP_NEW_VAR__';
                                    self.state.draftProfiles[self.state.currentProfileKey][self.state.currentTab].variables = { '__TEMP_NEW_VAR__': JSON.parse(JSON.stringify(CrosslinkerApp.Config.VAR_BLUEPRINT)) };
                                }
                                self.updateVarDropdown();
                                self.renderVarForm();
                                self.updatePreview();
                                self.updateVariableHint();
                            }
                        }

                        // Rule Actions
                        else if (target.closest('#ui-btn-add-rule')) {
                            const activeVarCfg = self.state.draftProfiles[self.state.currentProfileKey][self.state.currentTab].variables[self.state.currentVarKey];
                            if (!activeVarCfg.replaceRules) activeVarCfg.replaceRules = [];
                            activeVarCfg.replaceRules.push({find: '', replace: ''});
                            self.renderRules();
                            self.updatePreview();
                        } else if (target.closest('.l-btn-rule-del')) {
                            const idx = target.closest('.l-btn-rule-del').getAttribute('data-idx');
                            self.state.draftProfiles[self.state.currentProfileKey][self.state.currentTab].variables[self.state.currentVarKey].replaceRules.splice(idx, 1);
                            self.renderRules();
                            self.updatePreview();
                        }

                        // Hint Token click
                        else if (target.closest('.ui-hint-var-tag')) {
                            const urlInput = document.getElementById('f-destUrl');
                            if (urlInput) {
                                const startPos = urlInput.selectionStart;
                                const endPos = urlInput.selectionEnd;
                                const textToInsert = target.closest('.ui-hint-var-tag').innerText;
                                urlInput.value = urlInput.value.substring(0, startPos) + textToInsert + urlInput.value.substring(endPos, urlInput.value.length);
                                const newPos = startPos + textToInsert.length;
                                urlInput.focus();
                                urlInput.setSelectionRange(newPos, newPos);
                                urlInput.dispatchEvent(new Event('input'));
                            }
                        }

                        // IO Actions
                        else if (target.closest('#ui-btn-export')) CrosslinkerApp.Services.DataStore.downloadJSON(self.state.draftProfiles);
                        else if (target.closest('#ui-btn-reset')) {
                            if(confirm("Wipe all user profiles and restore the default profiles?")) {
                                CrosslinkerApp.Services.DataStore.save(CrosslinkerApp.Config.INITIAL_DATA);
                                location.reload();
                            }
                        }
                        else if (target.closest('#ui-btn-cancel')) document.getElementById('linker-overlay-wrapper').remove();
                        else if (target.closest('#ui-btn-save')) {
                            if (self.state.draftProfiles[self.state.currentProfileKey] && self.state.draftProfiles[self.state.currentProfileKey][self.state.currentTab].variables && self.state.draftProfiles[self.state.currentProfileKey][self.state.currentTab].variables['__TEMP_NEW_VAR__']) {
                                alert("You have an unsaved variable. Please confirm its name (✔) or delete it before saving."); return;
                            }
                            if (self.state.draftProfiles['__TEMP_NEW_PROFILE__']) {
                                alert("You have an unsaved profile. Please confirm its name (✔) or delete it before saving."); return;
                            }
                            CrosslinkerApp.Services.DataStore.save(self.state.draftProfiles);
                            location.reload();
                        }
                    });
                },

                checkTabInitialVars() {
                    const siteVars = this.state.draftProfiles[this.state.currentProfileKey][this.state.currentTab].variables || {};
                    this.state.currentVarKey = Object.keys(siteVars).length > 0 ? Object.keys(siteVars)[0] : '__TEMP_NEW_VAR__';
                    if (this.state.currentVarKey === '__TEMP_NEW_VAR__') {
                        this.state.draftProfiles[this.state.currentProfileKey][this.state.currentTab].variables = { '__TEMP_NEW_VAR__': JSON.parse(JSON.stringify(CrosslinkerApp.Config.VAR_BLUEPRINT)) };
                    }
                }
            }
        },

        // ---------------------------------------------------------------------
        // MAIN INITIALIZER
        // ---------------------------------------------------------------------
        init() {
            CrosslinkerApp.UI.StyleManager.injectStyles();
            GM_registerMenuCommand("Configuration", () => CrosslinkerApp.UI.ModalController.open());

            let debounceTimer;
            const observer = new MutationObserver(() => {
                clearTimeout(debounceTimer);
                debounceTimer = setTimeout(() => CrosslinkerApp.Services.InjectionEngine.inject(), 150);
            });
            observer.observe(document.body, { childList: true, subtree: true });

            CrosslinkerApp.Services.InjectionEngine.inject();
        }
    };

    CrosslinkerApp.init();

})();