☰

Ex/E-Hentai Comfort

Adds a reader overlay with Picture, Webtoon, and Manga modes, infinite loading, searchable tag tools, saved tag favourites, Quick Favourite gallery bookmarking, native page color control, and optional transparent native borders.

Vous devrez installer une extension telle que Tampermonkey, Greasemonkey ou Violentmonkey pour installer ce script.

Vous devrez installer une extension telle que Tampermonkey ou Violentmonkey pour installer ce script.

Vous devrez installer une extension telle que Tampermonkey ou Violentmonkey pour installer ce script.

Vous devrez installer une extension telle que Tampermonkey ou Userscripts pour installer ce script.

Vous devrez installer une extension telle que Tampermonkey pour installer ce script.

Vous devrez installer une extension de gestionnaire de script utilisateur pour installer ce script.

(J'ai déjà un gestionnaire de scripts utilisateur, laissez-moi l'installer !)

Vous devrez installer une extension telle que Stylus pour installer ce style.

Vous devrez installer une extension telle que Stylus pour installer ce style.

Vous devrez installer une extension telle que Stylus pour installer ce style.

Vous devrez installer une extension du gestionnaire de style pour utilisateur pour installer ce style.

Vous devrez installer une extension du gestionnaire de style pour utilisateur pour installer ce style.

Vous devrez installer une extension du gestionnaire de style pour utilisateur pour installer ce style.

(J'ai déjà un gestionnaire de style utilisateur, laissez-moi l'installer!)

// ==UserScript==
// @name               Ex/E-Hentai Comfort
// @namespace          http://tampermonkey.net/
// @version            1.2.1
// @author             L1Z4RD
// @description        Adds a reader overlay with Picture, Webtoon, and Manga modes, infinite loading, searchable tag tools, saved tag favourites, Quick Favourite gallery bookmarking, native page color control, and optional transparent native borders.
// @license            MIT
// @match              https://e-hentai.org/*
// @match              https://exhentai.org/*
// @grant              GM_addStyle
// @grant              GM_getValue
// @grant              GM_xmlhttpRequest
// @grant              GM_registerMenuCommand
// @grant              GM_setValue
// @connect            ehwiki.org
// ==/UserScript==

(function () {
  'use strict';

  const d=new Set;const importCSS = async e=>{d.has(e)||(d.add(e),(t=>{typeof GM_addStyle=="function"?GM_addStyle(t):(document.head||document.documentElement).appendChild(document.createElement("style")).append(t);})(e));};


  const stylesCss = '.page-batch{width:100%;display:flex;flex-direction:column;align-items:center;margin-bottom:60px}.r-img{display:block;width:auto;max-width:100%;margin-bottom:20px;background:transparent;box-shadow:0 0 20px #00000080}.r-ph{color:#555;margin-bottom:50px;text-align:center;min-height:400px;display:flex;align-items:center;justify-content:center;font-family:"Manrope","Inter","Segoe UI",system-ui,sans-serif;font-size:18px;border:1px dashed #333;width:100%;flex-direction:column;gap:10px}.r-ph.loading{color:#888;border-color:#555}.r-ph.error{color:#d44;border-color:#d44}.retry-btn{padding:8px 16px;background:#333;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:14px;margin-top:10px}.retry-btn:hover{background:#555}';
  importCSS(stylesCss);
  var _GM_getValue = (() => typeof GM_getValue != "undefined" ? GM_getValue : void 0)();
  var _GM_xmlhttpRequest = (() => typeof GM_xmlhttpRequest != "undefined" ? GM_xmlhttpRequest : void 0)();
  var _GM_registerMenuCommand = (() => typeof GM_registerMenuCommand != "undefined" ? GM_registerMenuCommand : void 0)();
  var _GM_setValue = (() => typeof GM_setValue != "undefined" ? GM_setValue : void 0)();
  const CFG = {
    prefetchDistance: 5e3,
    maxRetries: 3,
    retryDelay: 1e3,
    maxConcurrent: 3,
    requestSpacing: 100
  };
  const EHP_SUITE_SETTINGS_KEY = "ehpComfortSuiteSettingsV1";
  const EHP_SUITE_SETTINGS_VERSION = 1;
  const DEFAULT_EHP_SUITE_SETTINGS = {
    version: EHP_SUITE_SETTINGS_VERSION,
    modules: {
      reader: true,
      infiniteLoader: true,
      tagging: true,
      quickFavourite: true
    },
    nativeTheme: {
      pageColor: true,
      borderlessContainers: true
    },
    tagging: {
      activeGalleryTagging: true,
      liveLookup: true
    }
  };

  const EHP_STATIC_SCRIPT_UI = {
    color: "#f5f1e8",
    surface: "rgba(245, 241, 232, 0.96)",
    text: "#2d3137",
    fill: "#303843",
    input: "rgba(255, 255, 255, 0.72)",
    soft: "rgba(255, 255, 255, 0.52)"
  };

  function ehpIsPlainObject(value) {
    return !!value && typeof value === "object" && !Array.isArray(value);
  }

  function ehpDeepMerge(defaults, saved) {
    const output = Array.isArray(defaults) ? [...defaults] : { ...defaults };
    if (!ehpIsPlainObject(saved)) return output;
    Object.keys(saved).forEach((key) => {
      if (!(key in output)) return;
      const savedValue = saved[key];
      const defaultValue = output[key];
      if (ehpIsPlainObject(defaultValue) && ehpIsPlainObject(savedValue)) {
        output[key] = ehpDeepMerge(defaultValue, savedValue);
      } else if (savedValue !== undefined) {
        output[key] = savedValue;
      }
    });
    return output;
  }

  function ehpGetPath(root, path, fallback) {
    const parts = String(path || "").split(".").filter(Boolean);
    let node = root;
    for (const part of parts) {
      if (!node || typeof node !== "object" || !(part in node)) return fallback;
      node = node[part];
    }
    return node === undefined ? fallback : node;
  }

  function ehpSetPath(root, path, value) {
    const parts = String(path || "").split(".").filter(Boolean);
    if (!parts.length) return root;
    let node = root;
    while (parts.length > 1) {
      const part = parts.shift();
      if (!ehpIsPlainObject(node[part])) node[part] = {};
      node = node[part];
    }
    node[parts[0]] = value;
    return root;
  }

  function normalizeEhpSuiteSettings(settings) {
    return ehpIsPlainObject(settings) ? settings : ehpDeepMerge(DEFAULT_EHP_SUITE_SETTINGS, {});
  }

  function getEhpSuiteSettings() {
    let saved = {};
    try {
      saved = JSON.parse(_GM_getValue(EHP_SUITE_SETTINGS_KEY, "{}") || "{}");
    } catch (err) {
      saved = {};
    }
    return normalizeEhpSuiteSettings(ehpDeepMerge(DEFAULT_EHP_SUITE_SETTINGS, saved));
  }

  function saveEhpSuiteSettings(settings) {
    const merged = normalizeEhpSuiteSettings(ehpDeepMerge(DEFAULT_EHP_SUITE_SETTINGS, settings || {}));
    merged.version = EHP_SUITE_SETTINGS_VERSION;
    _GM_setValue(EHP_SUITE_SETTINGS_KEY, JSON.stringify(merged));
    return merged;
  }

  function getEhpSetting(path, fallback) {
    return ehpGetPath(getEhpSuiteSettings(), path, fallback);
  }

  function setEhpSetting(path, value) {
    const settings = getEhpSuiteSettings();
    ehpSetPath(settings, path, value);
    saveEhpSuiteSettings(settings);
    return settings;
  }

  function resetEhpSuiteSettings() {
    saveEhpSuiteSettings(DEFAULT_EHP_SUITE_SETTINGS);
  }

  function isEhpFeatureEnabled(path, fallback = true) {
    return !!getEhpSetting(path, fallback);
  }

  function loadSettings() {
    const validModes = new Set(["picture", "webtoon", "manga"]);
    const savedMode = _GM_getValue("readerMode", "picture");
    return {
      readerMode: validModes.has(savedMode) ? savedMode : "picture",
      pageGap: Number(_GM_getValue("pageGap", 5)) || 0,
      zoomPercent: Number(_GM_getValue("zoomPercent", 0)) || 0,
      themeColor: _GM_getValue("themeColor", "#f5f1e8"),
      readerUiSide: _GM_getValue("readerUiSide", "right") === "left" ? "left" : "right"
    };
  }
  class Store {
constructor() {
      this.listeners = new Map();
      this.currPage = 1;
      this.totalPage = 1;
      this.perPage = 20;
      this.imageOffset = 0;
      this.nextUrl = null;
      this.prevUrl = null;
      this.isFetching = false;
      this.nextPagePrefetched = false;
      this.currentImageIndex = 0;
      this.allImages = [];
      this.totalImages = 0;
      this.zoomGestureActive = false;
      this._settings = loadSettings();
    }
    get settings() {
      return this._settings;
    }
    updateSetting(key, value) {
      this._settings[key] = value;
      _GM_setValue(key, value);
      this.emit("settingsChanged");
    }
    on(event, listener) {
      if (!this.listeners.has(event)) {
        this.listeners.set(event, new Set());
      }
      this.listeners.get(event).add(listener);
    }
    emit(event) {
      var _a;
      (_a = this.listeners.get(event)) == null ? void 0 : _a.forEach((fn) => fn());
    }
  }
  const store = new Store();
  const q = (selector, root = document) => root.querySelector(selector);
  const qa = (selector, root = document) => root.querySelectorAll(selector);
  function isImageReady(img) {
    return !!(img && img.src && !img.src.includes("data:") && img.complete && img.naturalWidth > 0);
  }
  const sharedParser = new DOMParser();
  function fetchPageLinks(url) {
    return fetch(url).then((r) => r.text()).then((html) => {
      const doc = sharedParser.parseFromString(html, "text/html");
      const links = Array.from(qa("#gdt a", doc)).map((a) => a.href);
      return { doc, links };
    });
  }
  function calcTotal(doc, fallbackLinkCount) {
    const gpc = q(".gpc", doc);
    if (gpc) {
      const txt = gpc.textContent ?? "";
      const m = txt.match(/of\s+([\d,]+)\s+images/);
      if (m && m[1]) {
        const totalImgs = parseInt(m[1].replace(/,/g, ""));
        const perPage = fallbackLinkCount || 20;
        return Math.ceil(totalImgs / perPage);
      }
    }
    const allLinks = Array.from(qa(".ptt td a", doc));
    const lastA = allLinks.pop();
    if (lastA) {
      const t = parseInt(lastA.textContent ?? "");
      if (!isNaN(t)) return t;
    }
    return 1;
  }
  function parseImageRange(doc) {
    const gpc = q(".gpc", doc);
    if (!gpc) return null;
    const txt = gpc.textContent ?? "";
    const m = txt.match(/Showing\s+([\d,]+)\s*-\s*([\d,]+)\s+of\s+([\d,]+)/);
    if (!m) return null;
    return {
      start: parseInt(m[1].replace(/,/g, "")),
      total: parseInt(m[3].replace(/,/g, ""))
    };
  }
  function getNextUrl(doc) {
    const ptt = q(".ptt", doc);
    if (!ptt) return null;
    const nextBtn = Array.from(qa("td a", ptt)).find((a) => (a.textContent ?? "").includes(">"));
    return nextBtn ? nextBtn.href : null;
  }
  function getPrevUrl(doc) {
    const ptt = q(".ptt", doc);
    if (!ptt) return null;
    const prevBtn = Array.from(qa("td a", ptt)).find((a) => (a.textContent ?? "").includes("<"));
    return prevBtn ? prevBtn.href : null;
  }
  class RequestQueue {
    constructor() {
      this.queue = [];
      this.running = 0;
    }
    enqueue(task) {
      return new Promise((resolve, reject) => {
        this.queue.push({ execute: task, resolve, reject });
        this.run();
      });
    }
    run() {
      while (this.running < CFG.maxConcurrent && this.queue.length > 0) {
        const task = this.queue.shift();
        this.running++;
        const next = () => {
          this.running--;
          setTimeout(() => this.run(), CFG.requestSpacing);
        };
        task.execute().then((value) => {
          task.resolve(value);
          next();
        }).catch((reason) => {
          task.reject(reason);
          next();
        });
      }
    }
  }
  const requestQueue = new RequestQueue();
  const parser = new DOMParser();
  const imageCache = new Map();
  async function fetchImageSrc(url, retries = 0) {
    try {
      const response = await fetch(url);
      if (response.status === 429 || response.status === 503) {
        throw { rateLimited: true };
      }
      if (!response.ok) throw new Error(`HTTP ${response.status}`);
      const html = await response.text();
      const doc = parser.parseFromString(html, "text/html");
      const imgEl = q("#img", doc);
      const imgSrc = imgEl == null ? void 0 : imgEl.src;
      if (!imgSrc) throw new Error("Image not found");
      return imgSrc;
    } catch (err) {
      if (retries < CFG.maxRetries) {
        const isRateLimited = err && typeof err === "object" && "rateLimited" in err;
        const delay = isRateLimited ? 5e3 : CFG.retryDelay * Math.pow(2, retries);
        await new Promise((resolve) => setTimeout(resolve, delay));
        return fetchImageSrc(url, retries + 1);
      }
      return null;
    }
  }
  function loadImageWithRetry(url) {
    const cached = imageCache.get(url);
    if (cached) return Promise.resolve(cached);
    return requestQueue.enqueue(() => fetchImageSrc(url)).then((src) => {
      if (src) imageCache.set(url, src);
      return src;
    });
  }
  function createRetryHandler(url, placeholder, pIndex, index) {
    return () => {
      placeholder.className = "r-ph loading";
      placeholder.textContent = `P${pIndex}-${index + 1} Reloading...`;
      imageCache.delete(url);
      loadImageWithRetry(url).then((newSrc) => {
        var _a;
        if (newSrc) {
          const newImg = document.createElement("img");
          newImg.src = newSrc;
          newImg.className = "r-img";
          (_a = placeholder.parentNode) == null ? void 0 : _a.replaceChild(newImg, placeholder);
        }
      });
    };
  }
  const prefetchedUrls = new Set();
  function prefetchNextPage() {
    if (!store.nextUrl || store.nextPagePrefetched || prefetchedUrls.has(store.nextUrl)) return;
    const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
    const windowHeight = window.innerHeight;
    const documentHeight = document.documentElement.scrollHeight;
    const distanceToBottom = documentHeight - (scrollTop + windowHeight);
    if (distanceToBottom < CFG.prefetchDistance) {
      store.nextPagePrefetched = true;
      prefetchedUrls.add(store.nextUrl);
      fetchPageLinks(store.nextUrl).then(({ links }) => {
        links.forEach((url) => {
          loadImageWithRetry(url).then((imgSrc) => {
            if (imgSrc) {
              const preloadImg = new Image();
              preloadImg.src = imgSrc;
            }
          }).catch(() => null);
        });
      }).catch((err) => {
        console.error("[Prefetch Failed]", err);
        store.nextPagePrefetched = false;
        if (store.nextUrl) prefetchedUrls.delete(store.nextUrl);
      });
    }
  }
  function setupPrefetchListener() {
    let scrollTimer;
    window.addEventListener("scroll", () => {
      clearTimeout(scrollTimer);
      scrollTimer = setTimeout(prefetchNextPage, 200);
    }, { passive: true });
  }
  function setErrorState(placeholder, url, pIndex, index) {
    placeholder.className = "r-ph error";
    placeholder.innerHTML = `
    <div>P${pIndex}-${index + 1} Failed</div>
    <button class="retry-btn">Retry</button>
  `;
    const retryBtn = placeholder.querySelector(".retry-btn");
    retryBtn.onclick = createRetryHandler(url, placeholder, pIndex, index);
  }
  function processBatch(links, pIndex, prepend = false) {
    const container = document.querySelector("#gdt-hidden") || document.querySelector("#gdt");
    if (!container) return;
    const batchDiv = document.createElement("div");
    batchDiv.className = "page-batch";
    const fragment = document.createDocumentFragment();
    links.forEach((url, index) => {
      const placeholder = document.createElement("div");
      placeholder.className = "r-ph loading";
      placeholder.textContent = `P${pIndex}-${index + 1} Loading...`;
      fragment.appendChild(placeholder);
      loadImageWithRetry(url).then((imgSrc) => {
        var _a;
        if (imgSrc) {
          const img = document.createElement("img");
          img.className = "r-img";
          img.onerror = () => {
            if (placeholder.parentNode) {
              setErrorState(placeholder, url, pIndex, index);
              placeholder.parentNode.replaceChild(placeholder, img);
            }
          };
          img.src = imgSrc;
          (_a = placeholder.parentNode) == null ? void 0 : _a.replaceChild(img, placeholder);
        } else {
          setErrorState(placeholder, url, pIndex, index);
        }
      }).catch(() => {
        placeholder.className = "r-ph error";
        placeholder.textContent = `P${pIndex}-${index + 1} Network Error`;
      });
    });
    batchDiv.appendChild(fragment);
    if (prepend && container.firstChild) {
      container.insertBefore(batchDiv, container.firstChild);
    } else {
      container.appendChild(batchDiv);
    }
  }
  /************************************************************
   * Overlay reader replaces the old page takeover scroll/autoplay stack.
   ************************************************************/

  function createSinglePageOverlay(deps) {
    ensureEhpReaderStyle();

    const overlay = document.createElement("div");
    overlay.id = "ehp-reader-overlay";
    overlay.className = "ehp-reader-overlay";

    const progressBar = document.createElement("div");
    progressBar.className = "ehp-progress-bar";

    const pageIndicator = document.createElement("div");
    pageIndicator.className = "ehp-page-indicator";

    const thumbnailPanel = document.createElement("div");
    thumbnailPanel.id = "ehp-reader-thumbs";
    thumbnailPanel.className = "ehp-reader-thumbs";
    const thumbnailViewport = document.createElement("div");
    thumbnailViewport.className = "ehp-thumb-viewport";
    const thumbnailList = document.createElement("div");
    thumbnailList.className = "ehp-thumb-list";
    thumbnailViewport.appendChild(thumbnailList);
    thumbnailPanel.appendChild(thumbnailViewport);
    thumbnailPanel.appendChild(pageIndicator);

    const reader = document.createElement("div");
    reader.className = "ehp-reader-stage";

    overlay.appendChild(progressBar);
    overlay.appendChild(thumbnailPanel);
    overlay.appendChild(reader);
    document.body.appendChild(overlay);

    let currentImageEl = null;
    let thumbnailRenderedCount = -1;
    let scrollObserver = null;
    let mutationObserver = null;
    let loadPollTimer = null;
    let wheelTimeout = 0;
    let wheelDelta = 0;
    let wheelProcessing = false;
    let zoomRenderFrame = 0;
    let pointerZoom = null;

    const ui = mountEhpOverlayUI(overlay, {
      setMode,
      setGap,
      setZoom,
      jumpToPage,
      close: () => close(true),
      topOrFirst,
      bottomOrLast
    });

    function totalImageCount() {
      return store.totalImages || Math.max(store.imageOffset + store.allImages.length, store.totalPage * store.perPage);
    }

    function syncImages() {
      const box = document.querySelector("#gdt-hidden") || document.querySelector("#gdt");
      if (!box) return false;
      const fresh = Array.from(qa(".r-img", box));
      const changed = fresh.length !== store.allImages.length || fresh.some((img, i) => img !== store.allImages[i]);
      if (changed) store.allImages = fresh;
      return changed;
    }

    function activateIndex(index, behavior = "smooth") {
      syncImages();
      const safeIndex = Math.max(0, Math.min(index, Math.max(0, store.allImages.length - 1)));
      store.currentImageIndex = safeIndex;
      if (store.settings.readerMode === "picture") {
        updatePictureImage();
      } else {
        scrollIndexIntoView(safeIndex, behavior);
      }
      updateThumbnailPanel(true);
      checkAndLoadAroundCurrent();
    }

    function updateThumbnailPanel(keepActiveVisible = false) {
      if (!thumbnailPanel || !thumbnailList) return;
      const total = totalImageCount();
      const imageCount = store.allImages.length;
      thumbnailPanel.style.display = overlay.classList.contains("active") && imageCount > 0 ? "flex" : "none";

      if (thumbnailRenderedCount !== imageCount) {
        thumbnailRenderedCount = imageCount;
        thumbnailList.innerHTML = "";
        store.allImages.forEach((sourceImg, index) => {
          const item = document.createElement("button");
          item.type = "button";
          item.className = "ehp-thumb-item";
          item.dataset.index = String(index);
          item.title = `Page ${store.imageOffset + index + 1}`;

          if (sourceImg && isImageReady(sourceImg)) {
            const img = document.createElement("img");
            img.className = "ehp-thumb-img";
            img.src = sourceImg.src;
            item.appendChild(img);
          } else {
            const ph = document.createElement("span");
            ph.className = "ehp-thumb-ph";
            ph.textContent = String(store.imageOffset + index + 1);
            item.appendChild(ph);
          }

          const label = document.createElement("span");
          label.className = "ehp-thumb-label";
          label.textContent = String(store.imageOffset + index + 1);
          item.appendChild(label);

          item.addEventListener("click", (event) => {
            event.preventDefault();
            event.stopPropagation();
            activateIndex(index, "smooth");
          });

          thumbnailList.appendChild(item);
        });
      }

      const activeIndex = store.settings.readerMode === "manga" ? getSpreadFirstFromIndex(store.currentImageIndex) : store.currentImageIndex;
      thumbnailList.querySelectorAll(".ehp-thumb-item").forEach((item) => {
        const idx = parseInt(item.dataset.index || "0", 10);
        const isActive = store.settings.readerMode === "manga"
          ? idx === activeIndex || idx === activeIndex + 1
          : idx === activeIndex;
        item.classList.toggle("is-active", isActive);
      });

      const active = thumbnailList.querySelector(".ehp-thumb-item.is-active");
      if (active && keepActiveVisible) {
        const panelRect = thumbnailViewport.getBoundingClientRect();
        const itemRect = active.getBoundingClientRect();
        if (itemRect.top < panelRect.top || itemRect.bottom > panelRect.bottom) {
          active.scrollIntoView({ block: "nearest", behavior: "smooth" });
        }
      }

      thumbnailPanel.dataset.total = String(total);
    }

    thumbnailPanel.addEventListener("wheel", (event) => {
      event.stopPropagation();
    }, { passive: true });

    function clearRenderTimers() {
      if (scrollObserver) {
        scrollObserver.disconnect();
        scrollObserver = null;
      }
      if (loadPollTimer) {
        clearInterval(loadPollTimer);
        loadPollTimer = null;
      }
    }

    function startMutationObserver() {
      const box = document.querySelector("#gdt-hidden") || document.querySelector("#gdt");
      if (!box || mutationObserver) return;
      mutationObserver = new MutationObserver(() => {
        const changed = syncImages();
        if (!overlay.classList.contains("active") || !changed) return;

        if (store.settings.readerMode === "picture") {
          updatePictureImage();
        } else {
          const current = store.currentImageIndex;
          renderReader(current, false);
        }
        updateThumbnailPanel(false);
      });
      mutationObserver.observe(box, { childList: true, subtree: true });
    }

    function open() {
      syncImages();
      startMutationObserver();

      if (store.allImages.length === 0) {
        alert("Please wait for images to load");
        return;
      }

      store.currentImageIndex = Math.max(0, Math.min(store.currentImageIndex || 0, store.allImages.length - 1));
      overlay.classList.add("active");
      document.documentElement.classList.add("ehp-reader-open");
      document.body.style.overflow = "hidden";
      applyEhpThemeColor();
      applyEhpZoom();
      renderReader(store.currentImageIndex, false);
      store.emit("readerModeChanged");
    }

    function close(updateNativePage) {
      clearRenderTimers();
      overlay.classList.remove("active");
      document.documentElement.classList.remove("ehp-reader-open");
      document.body.style.overflow = "";
      store.zoomGestureActive = false;
      overlay.classList.remove("ehp-zoom-gesture-active");
      store.emit("readerModeChanged");

      if (updateNativePage) {
        syncNativePageToCurrentImage();
      }
    }

    function syncNativePageToCurrentImage() {
      const globalIndex = store.imageOffset + store.currentImageIndex;
      const targetPage = Math.floor(globalIndex / Math.max(1, store.perPage));
      const url = new URL(window.location.href);
      const currentPage = parseInt(url.searchParams.get("p") || "0", 10);
      url.searchParams.set("p", String(targetPage));
      url.hash = `page-${globalIndex + 1}`;

      if (targetPage !== currentPage) {
        window.location.href = url.toString();
      }
    }

    function renderReader(targetIndex = store.currentImageIndex, preserveScroll = true) {
      clearRenderTimers();
      syncImages();
      store.currentImageIndex = Math.max(0, Math.min(targetIndex, Math.max(0, store.allImages.length - 1)));

      const mode = normalizeEhpMode(store.settings.readerMode);
      overlay.dataset.mode = mode;
      overlay.classList.toggle("ehp-mode-picture", mode === "picture");
      overlay.classList.toggle("ehp-mode-webtoon", mode === "webtoon");
      overlay.classList.toggle("ehp-mode-manga", mode === "manga");

      reader.className = `ehp-reader-stage ehp-stage-${mode}`;
      reader.innerHTML = "";
      currentImageEl = null;

      if (mode === "picture") {
        renderPictureMode();
      } else if (mode === "manga") {
        renderMangaMode(preserveScroll);
      } else {
        renderWebtoonMode(preserveScroll);
      }

      applyEhpGap();
      applyEhpZoom();
      updateProgressBar();
      updatePageIndicator();
      updateThumbnailPanel(true);
      syncEhpUI(ui);
    }

    function renderPictureMode() {
      const frame = document.createElement("div");
      frame.className = "ehp-picture-frame";
      const img = document.createElement("img");
      img.className = "ehp-current-image";
      img.alt = `Page ${store.imageOffset + store.currentImageIndex + 1}`;
      const placeholder = document.createElement("div");
      placeholder.className = "ehp-placeholder";
      frame.appendChild(placeholder);
      frame.appendChild(img);
      reader.appendChild(frame);
      currentImageEl = img;
      updatePictureImage();
    }

    function updatePictureImage() {
      if (!currentImageEl || !overlay.classList.contains("active")) return;
      syncImages();
      const frame = currentImageEl.parentElement;
      const placeholder = frame && frame.querySelector(".ehp-placeholder");
      const img = store.allImages[store.currentImageIndex];
      const label = `${store.imageOffset + store.currentImageIndex + 1} / ${totalImageCount()}`;

      if (placeholder) placeholder.textContent = img ? `Loading ${label}` : `Waiting ${label}`;
      currentImageEl.classList.remove("loaded");
      currentImageEl.removeAttribute("src");

      if (img && isImageReady(img)) {
        if (placeholder) placeholder.style.display = "none";
        currentImageEl.src = img.src;
        currentImageEl.onload = () => {
          currentImageEl.classList.add("loaded");
          applyEhpZoom();
          updateThumbnailPanel(false);
        };
        if (currentImageEl.complete) {
          currentImageEl.classList.add("loaded");
          applyEhpZoom();
        }
      } else {
        if (placeholder) placeholder.style.display = "flex";
        waitForPictureImage(store.currentImageIndex);
      }

      checkAndLoadAroundCurrent();
      updateProgressBar();
      updatePageIndicator();
      updateThumbnailPanel(true);
      syncEhpUI(ui);
    }

    function waitForPictureImage(index) {
      if (loadPollTimer) clearInterval(loadPollTimer);
      loadPollTimer = setInterval(() => {
        if (!overlay.classList.contains("active") || store.settings.readerMode !== "picture" || store.currentImageIndex !== index) {
          clearInterval(loadPollTimer);
          loadPollTimer = null;
          return;
        }
        syncImages();
        const img = store.allImages[index];
        if (img && isImageReady(img)) {
          clearInterval(loadPollTimer);
          loadPollTimer = null;
          updatePictureImage();
        }
      }, 300);
    }

    function makeImageNode(sourceImg, index, extraClass = "") {
      const wrap = document.createElement("div");
      wrap.className = `ehp-page ${extraClass}`.trim();
      wrap.dataset.index = String(index);
      wrap.dataset.page = String(store.imageOffset + index + 1);

      if (sourceImg && isImageReady(sourceImg)) {
        const img = document.createElement("img");
        img.className = "ehp-reader-image loaded";
        img.src = sourceImg.src;
        img.alt = `Page ${store.imageOffset + index + 1}`;
        img.addEventListener("load", () => {
          img.classList.add("loaded");
          applyEhpZoom();
          updateThumbnailPanel(false);
        }, { once: true });
        if (img.complete) {
          img.classList.add("loaded");
          setTimeout(applyEhpZoom, 0);
        }
        wrap.appendChild(img);
      } else {
        const ph = document.createElement("div");
        ph.className = "ehp-placeholder";
        ph.textContent = `Loading ${store.imageOffset + index + 1} / ${totalImageCount()}`;
        wrap.appendChild(ph);
      }

      return wrap;
    }

    function renderWebtoonMode(preserveScroll) {
      const oldTop = preserveScroll ? overlay.scrollTop : 0;
      store.allImages.forEach((img, index) => {
        reader.appendChild(makeImageNode(img, index));
      });
      observePages();
      if (preserveScroll) {
        overlay.scrollTop = oldTop;
      } else {
        scrollIndexIntoView(store.currentImageIndex, "auto");
      }
      checkAndLoadAroundCurrent();
    }

    function renderMangaMode(preserveScroll) {
      const oldTop = preserveScroll ? overlay.scrollTop : 0;
      for (let i = 0; i < store.allImages.length; i += 2) {
        const spread = document.createElement("div");
        spread.className = "ehp-spread";
        spread.dataset.index = String(i);
        spread.dataset.page = String(store.imageOffset + i + 1);
        spread.appendChild(makeImageNode(store.allImages[i], i, "ehp-manga-slot"));
        if (i + 1 < store.allImages.length) {
          spread.appendChild(makeImageNode(store.allImages[i + 1], i + 1, "ehp-manga-slot"));
        } else {
          const empty = document.createElement("div");
          empty.className = "ehp-page ehp-manga-slot is-empty";
          spread.appendChild(empty);
        }
        reader.appendChild(spread);
      }
      observePages();
      if (preserveScroll) {
        overlay.scrollTop = oldTop;
      } else {
        scrollIndexIntoView(getSpreadFirstFromIndex(store.currentImageIndex), "auto");
      }
      checkAndLoadAroundCurrent();
    }

    function observePages() {
      scrollObserver = new IntersectionObserver((entries) => {
        let best = null;
        for (const entry of entries) {
          if (!entry.isIntersecting) continue;
          if (!best || entry.intersectionRatio > best.intersectionRatio) best = entry;
        }
        if (!best) return;
        const idx = parseInt(best.target.dataset.index || best.target.closest(".ehp-spread")?.dataset.index || "0", 10);
        if (!Number.isNaN(idx)) {
          store.currentImageIndex = Math.max(0, Math.min(idx, store.allImages.length - 1));
          updatePageIndicator();
          updateProgressBar();
          updateThumbnailPanel(true);
          syncEhpUI(ui);
          checkAndLoadAroundCurrent();
        }
      }, { root: overlay, threshold: [0.15, 0.35, 0.6, 0.85] });

      const targets = store.settings.readerMode === "manga" ? Array.from(reader.querySelectorAll(".ehp-spread")) : Array.from(reader.querySelectorAll(".ehp-page"));
      targets.forEach((el) => scrollObserver.observe(el));
    }

    function getSpreadFirstFromIndex(index) {
      return index % 2 === 0 ? index : index - 1;
    }

    function scrollIndexIntoView(index, behavior = "smooth") {
      const mode = normalizeEhpMode(store.settings.readerMode);
      if (mode === "picture") {
        store.currentImageIndex = Math.max(0, Math.min(index, store.allImages.length - 1));
        updatePictureImage();
        return;
      }
      const targetIndex = mode === "manga" ? getSpreadFirstFromIndex(index) : index;
      const target = reader.querySelector(`[data-index="${targetIndex}"]`);
      if (target) {
        target.scrollIntoView({ behavior, block: "center" });
      }
    }

    function isMangaFitNavigation() {
      return store.settings.readerMode === "manga" && Math.max(0, Math.min(100, Number(store.settings.zoomPercent) || 0)) === 0;
    }

    function nextImage() {
      syncImages();
      if (isMangaFitNavigation()) {
        const currentSpread = getSpreadFirstFromIndex(store.currentImageIndex);
        const target = currentSpread + 2;
        if (target < store.allImages.length) {
          store.currentImageIndex = target;
          scrollIndexIntoView(target);
          updateThumbnailPanel(true);
        } else {
          loadNextPage();
        }
        checkAndLoadAroundCurrent();
        return;
      }

      if (store.currentImageIndex < store.allImages.length - 1) {
        store.currentImageIndex++;
        if (store.settings.readerMode === "picture") updatePictureImage();
        else scrollIndexIntoView(store.currentImageIndex);
        updateThumbnailPanel(true);
      } else {
        loadNextPage();
      }
      checkAndLoadAroundCurrent();
    }

    function previousImage() {
      syncImages();
      if (isMangaFitNavigation()) {
        const currentSpread = getSpreadFirstFromIndex(store.currentImageIndex);
        const target = currentSpread - 2;
        if (target >= 0) {
          store.currentImageIndex = target;
          scrollIndexIntoView(target);
          updateThumbnailPanel(true);
        } else {
          loadPrevPage();
        }
        checkAndLoadAroundCurrent();
        return;
      }

      if (store.currentImageIndex > 0) {
        store.currentImageIndex--;
        if (store.settings.readerMode === "picture") updatePictureImage();
        else scrollIndexIntoView(store.currentImageIndex);
        updateThumbnailPanel(true);
      } else {
        loadPrevPage();
      }
      checkAndLoadAroundCurrent();
    }

    function checkAndLoadAroundCurrent() {
      if (store.currentImageIndex >= store.allImages.length - 8) loadNextPage();
      if (store.currentImageIndex <= 3) loadPrevPage();
    }

    function loadNextPage() {
      if (!store.nextUrl || store.isFetching) return;
      store.isFetching = true;
      fetchPageLinks(store.nextUrl).then(({ doc, links }) => {
        deps.onLoadNextPage(links, doc);
        store.nextUrl = getNextUrl(doc);
        store.isFetching = false;
        store.nextPagePrefetched = false;
        setTimeout(() => {
          syncImages();
          thumbnailRenderedCount = -1;
          updateThumbnailPanel(false);
          applyEhpZoom();
        }, 0);
      }).catch((err) => {
        console.error("[Reader] Load next failed", err);
        store.isFetching = false;
      });
    }

    function loadPrevPage() {
      if (!store.prevUrl || store.isFetching || store.imageOffset <= 0) return;
      store.isFetching = true;
      const oldLen = store.allImages.length;
      fetchPageLinks(store.prevUrl).then(({ doc, links }) => {
        const addCount = links.length;
        deps.onLoadPrevPage(links, doc);
        store.prevUrl = getPrevUrl(doc);
        store.imageOffset = Math.max(0, store.imageOffset - addCount);
        store.currentImageIndex += addCount;
        store.isFetching = false;
        setTimeout(() => {
          syncImages();
          if (store.allImages.length !== oldLen) {
            thumbnailRenderedCount = -1;
            if (store.settings.readerMode !== "picture") renderReader(store.currentImageIndex, true);
            else updatePictureImage();
            updateThumbnailPanel(true);
          }
        }, 0);
      }).catch((err) => {
        console.error("[Reader] Load prev failed", err);
        store.isFetching = false;
      });
    }

    function setMode(mode) {
      const next = normalizeEhpMode(mode);
      if (store.settings.readerMode === next) return;
      store.updateSetting("readerMode", next);
      renderReader(store.currentImageIndex, false);
    }

    function setGap(gap) {
      store.updateSetting("pageGap", Math.max(0, Math.min(80, Number(gap) || 0)));
      applyEhpGap();
      syncEhpUI(ui);
    }

    function setZoom(zoom, shouldSave = true) {
      const value = Math.max(0, Math.min(100, Number(zoom) || 0));
      store.settings.zoomPercent = value;
      if (shouldSave) _GM_setValue("zoomPercent", value);

      if (ui && ui.zoomSlider) ui.zoomSlider.value = String(value);
      if (ui && ui.zoomValue) ui.zoomValue.textContent = `${value}%`;

      if (zoomRenderFrame) cancelAnimationFrame(zoomRenderFrame);
      const render = () => {
        zoomRenderFrame = 0;
        applyEhpZoom();
        syncEhpUI(ui);
      };

      if (shouldSave) render();
      else zoomRenderFrame = requestAnimationFrame(render);
    }

    function jumpToPage(value, behavior = "smooth") {
      const pageNo = parseInt(value, 10);
      if (Number.isNaN(pageNo)) return;
      const globalIndex = Math.max(0, Math.min(totalImageCount() - 1, pageNo - 1));
      const localIndex = globalIndex - store.imageOffset;
      if (localIndex >= 0 && localIndex < store.allImages.length) {
        store.currentImageIndex = localIndex;
        if (store.settings.readerMode === "picture") updatePictureImage();
        else scrollIndexIntoView(localIndex, behavior);
        return;
      }

      const targetGalleryPage = Math.floor(globalIndex / Math.max(1, store.perPage));
      const currentGalleryPage = store.currPage - 1;
      const url = new URL(window.location.href);
      url.searchParams.set("p", String(targetGalleryPage));
      url.hash = `page-${globalIndex + 1}`;
      if (targetGalleryPage !== currentGalleryPage) {
        window.location.href = url.toString();
      }
    }

    function topOrFirst() {
      if (store.settings.readerMode === "picture") {
        store.currentImageIndex = 0;
        updatePictureImage();
      } else {
        overlay.scrollTo({ top: 0, behavior: "smooth" });
      }
    }

    function bottomOrLast() {
      if (store.settings.readerMode === "picture") {
        syncImages();
        store.currentImageIndex = Math.max(0, store.allImages.length - 1);
        updatePictureImage();
      } else {
        overlay.scrollTo({ top: overlay.scrollHeight, behavior: "smooth" });
      }
    }

    function updateProgressBar() {
      if (store.settings.readerMode === "picture") {
        const total = Math.max(1, totalImageCount());
        progressBar.style.width = `${((store.imageOffset + store.currentImageIndex + 1) / total) * 100}%`;
        return;
      }
      const maxScroll = overlay.scrollHeight - overlay.clientHeight;
      const progress = maxScroll <= 0 ? 0 : overlay.scrollTop / maxScroll * 100;
      progressBar.style.width = `${Math.max(0, Math.min(100, progress))}%`;
    }

    function updatePageIndicator() {
      const total = totalImageCount();
      const current = Math.min(total, store.imageOffset + store.currentImageIndex + 1);
      if (store.settings.readerMode === "manga") {
        const first = current % 2 === 0 ? current - 1 : current;
        const second = Math.min(total, first + 1);
        pageIndicator.textContent = `Pages ${first}${second !== first ? "-" + second : ""} / ${total}`;
      } else {
        pageIndicator.textContent = `Page ${current} / ${total}`;
      }
    }

    overlay.addEventListener("scroll", () => {
      if (!overlay.classList.contains("active")) return;
      updateProgressBar();
      if (store.settings.readerMode !== "picture") {
        const nearBottom = overlay.scrollTop + overlay.clientHeight >= overlay.scrollHeight - 1800;
        const nearTop = overlay.scrollTop <= 800;
        if (nearBottom) loadNextPage();
        if (nearTop) loadPrevPage();
      }
    }, { passive: true });

    overlay.addEventListener("wheel", (e) => {
      if (!overlay.classList.contains("active")) return;
      const shouldStepByWheel = store.settings.readerMode === "picture" || isMangaFitNavigation();
      if (!shouldStepByWheel) return;
      if (isEhpUiTarget(e.target)) return;

      e.preventDefault();
      wheelDelta += e.deltaY;
      if (!wheelProcessing) {
        wheelProcessing = true;
        const processWheel = () => {
          const threshold = 100;
          if (Math.abs(wheelDelta) >= threshold) {
            if (wheelDelta > 0) nextImage();
            else previousImage();
            wheelDelta = wheelDelta > 0 ? wheelDelta - threshold : wheelDelta + threshold;
          }
          if (wheelProcessing) requestAnimationFrame(processWheel);
        };
        processWheel();
      }
      clearTimeout(wheelTimeout);
      wheelTimeout = setTimeout(() => {
        wheelProcessing = false;
        wheelDelta = 0;
      }, 150);
    }, { passive: false });

    document.addEventListener("keydown", (e) => {
      if (!overlay.classList.contains("active")) return;
      if (e.key === "Escape") {
        close(true);
        return;
      }

      const isTyping = e.target && e.target.matches && e.target.matches("input, textarea, select");
      if (isTyping) return;

      if (e.key === "ArrowDown" || e.key === "ArrowRight" || e.key === "PageDown") {
        e.preventDefault();
        nextImage();
      } else if (e.key === "ArrowUp" || e.key === "ArrowLeft" || e.key === "PageUp") {
        e.preventDefault();
        previousImage();
      } else if (e.key === "+" || e.key === "=") {
        e.preventDefault();
        setZoom((Number(store.settings.zoomPercent) || 0) + 5, true);
      } else if (e.key === "-" || e.key === "_") {
        e.preventDefault();
        setZoom((Number(store.settings.zoomPercent) || 0) - 5, true);
      } else if (e.key === "0") {
        e.preventDefault();
        setZoom(0, true);
      }
    });

    overlay.addEventListener("dblclick", (e) => {
      if (!overlay.classList.contains("active")) return;
      if (isEhpUiTarget(e.target)) return;
      e.preventDefault();
      store.zoomGestureActive = !store.zoomGestureActive;
      overlay.classList.toggle("ehp-zoom-gesture-active", store.zoomGestureActive);
      if (!store.zoomGestureActive) {
        setZoom(0, true);
      }
    });

    overlay.addEventListener("pointerdown", (e) => {
      if (!store.zoomGestureActive || e.button !== 0 || isEhpUiTarget(e.target)) return;
      pointerZoom = {
        id: e.pointerId,
        startX: e.clientX,
        startZoom: store.settings.zoomPercent
      };
      overlay.setPointerCapture(e.pointerId);
      overlay.classList.add("ehp-zoom-dragging");
      e.preventDefault();
    });

    overlay.addEventListener("pointermove", (e) => {
      if (!pointerZoom || pointerZoom.id !== e.pointerId) return;
      const dx = e.clientX - pointerZoom.startX;
      setZoom(pointerZoom.startZoom + dx * 0.35, false);
      e.preventDefault();
    });

    const endPointerZoom = (e) => {
      if (!pointerZoom || pointerZoom.id !== e.pointerId) return;
      _GM_setValue("zoomPercent", store.settings.zoomPercent);
      pointerZoom = null;
      overlay.classList.remove("ehp-zoom-dragging");
    };
    overlay.addEventListener("pointerup", endPointerZoom);
    overlay.addEventListener("pointercancel", endPointerZoom);

    window.addEventListener("resize", () => {
      applyEhpZoom();
      if (overlay.classList.contains("active") && store.settings.readerMode !== "picture") {
        renderReader(store.currentImageIndex, true);
      }
    }, { passive: true });

    store.on("settingsChanged", () => {
      applyEhpThemeColor();
      applyEhpGap();
      applyEhpZoom();
      applyEhpReaderUiSide(ui);
      syncEhpUI(ui);
    });

    return {
      open,
      close,
      isActive: () => overlay.classList.contains("active"),
      getOverlayElement: () => overlay,
      jumpTo: (index) => {
        store.currentImageIndex = Math.max(0, Math.min(index, store.allImages.length - 1));
        if (store.settings.readerMode === "picture") updatePictureImage();
        else scrollIndexIntoView(store.currentImageIndex);
      }
    };
  }

  function initSinglePageMode() {
    const spm = createSinglePageOverlay({
      onLoadNextPage: (links, doc) => {
        store.currPage++;
        processBatch(links, store.currPage);
        store.nextUrl = getNextUrl(doc);
      },
      onLoadPrevPage: (links, doc) => {
        store.currPage = Math.max(1, store.currPage - 1);
        processBatch(links, store.currPage, true);
        store.prevUrl = getPrevUrl(doc);
      }
    });
    return spm;
  }
  const EHP_ICONS = {
    openBook: '<svg viewBox="0 0 24 24" width="22" height="22" aria-hidden="true"><path d="M4 5.5c2.8 0 5 .7 8 2.5v12c-3-1.8-5.2-2.5-8-2.5z"></path><path d="M20 5.5c-2.8 0-5 .7-8 2.5v12c3-1.8 5.2-2.5 8-2.5z"></path><path d="M12 8v12"></path></svg>',
    closedBook: '<svg viewBox="0 0 24 24" width="20" height="20" aria-hidden="true"><path d="M6.5 4.5h10A2.5 2.5 0 0 1 19 7v13H8a3 3 0 0 1-3-3V6a1.5 1.5 0 0 1 1.5-1.5z"></path><path d="M8 4.5V20"></path><path d="M8 17h11"></path></svg>',
    menu: '<svg viewBox="0 0 24 24" width="21" height="21" aria-hidden="true"><path d="M5 7h14"></path><path d="M5 12h14"></path><path d="M5 17h14"></path></svg>',
    up: '<svg viewBox="0 0 24 24" width="20" height="20" aria-hidden="true"><path d="M12 19V5"></path><path d="M5 12l7-7 7 7"></path></svg>',
    mode: '<svg viewBox="0 0 24 24" width="20" height="20" aria-hidden="true"><path d="M4 5h16"></path><path d="M4 12h16"></path><path d="M4 19h16"></path><path d="M8 3v18"></path><path d="M16 3v18"></path></svg>',
    fit: '<svg viewBox="0 0 24 24" width="20" height="20" aria-hidden="true"><path d="M9 4H4v5"></path><path d="M15 4h5v5"></path><path d="M9 20H4v-5"></path><path d="M15 20h5v-5"></path></svg>',
    gap: '<svg viewBox="0 0 24 24" width="20" height="20" aria-hidden="true"><path d="M6 5h12"></path><path d="M6 12h12"></path><path d="M6 19h12"></path><path d="M12 7v3"></path><path d="M12 14v3"></path></svg>',
    reader: '<svg viewBox="0 0 24 24" width="20" height="20" aria-hidden="true"><path d="M7 4.5h6.75A3.25 3.25 0 0 1 17 7.75V19a2.5 2.5 0 0 0-2.5-2.5H7z"></path></svg>',
    theme: '<svg viewBox="0 0 24 24" width="20" height="20" aria-hidden="true"><circle cx="12" cy="12" r="4.5"></circle><path d="M12 2.5v2.5"></path><path d="M12 19v2.5"></path><path d="M4.9 4.9l1.8 1.8"></path><path d="M17.3 17.3l1.8 1.8"></path><path d="M2.5 12H5"></path><path d="M19 12h2.5"></path><path d="M4.9 19.1l1.8-1.8"></path><path d="M17.3 6.7l1.8-1.8"></path></svg>',
    tag: '<svg viewBox="0 0 24 24" width="20" height="20" aria-hidden="true"><path d="M20.5 13.2l-7.3 7.3a2.2 2.2 0 0 1-3.1 0L3.5 13.9a2.2 2.2 0 0 1-.6-1.6V5.2A2.2 2.2 0 0 1 5.2 3h7.1c.6 0 1.2.2 1.6.7l6.6 6.6a2.2 2.2 0 0 1 0 3.1z"></path><circle cx="8.2" cy="8.2" r="1.3"></circle></svg>',
    favorite: '<svg viewBox="0 0 24 24" width="20" height="20" aria-hidden="true"><path d="M12 3.5l2.8 5.7 6.3.9-4.6 4.5 1.1 6.3L12 18l-5.6 2.9 1.1-6.3-4.6-4.5 6.3-.9z"></path></svg>',
    guide: '<svg viewBox="0 0 24 24" width="20" height="20" aria-hidden="true"><circle cx="12" cy="12" r="9"></circle><path d="M12 17v-5"></path><path d="M12 8h.01"></path></svg>',
    add: '<svg viewBox="0 0 24 24" width="22" height="22" aria-hidden="true"><path d="M12 5v14"></path><path d="M5 12h14"></path></svg>',
    remove: '<svg viewBox="0 0 24 24" width="22" height="22" aria-hidden="true"><path d="M5 12h14"></path></svg>',
    search: '<svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="10.5" cy="10.5" r="6.5"></circle><path d="M16 16l4 4"></path></svg>',
    nsArtist: '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 19c2.6.2 4.2-.5 4.8-2.2.4-1.1-.2-2.4-1.3-2.8-1.1-.4-2.4.2-2.8 1.3-.3.8-.4 1.8-.7 3.7z"></path><path d="M8.5 14.2L18.7 4c.8-.8 2.1-.1 1.7 1L16 16"></path><path d="M14.5 7.8l2 2"></path></svg>',
    nsCharacter: '<svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="8" r="3.2"></circle><path d="M5.5 19c.6-3.6 3.1-5.5 6.5-5.5s5.9 1.9 6.5 5.5"></path></svg>',
    nsCosplayer: '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4.5 9c1.6-1.4 3.5-1.7 5.7-.8 1.1.5 2.5.5 3.6 0 2.2-.9 4.1-.6 5.7.8.2 4.2-1.8 6.3-5 5.3-1.7-.5-3.3-.5-5 0-3.2 1-5.2-1.1-5-5.3z"></path><path d="M8 11.5c1.1-.5 2-.5 2.9 0"></path><path d="M13.1 11.5c.9-.5 1.8-.5 2.9 0"></path></svg>',
    nsFemale: '<svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="8" r="4.5"></circle><path d="M12 12.5V21"></path><path d="M8.5 17.5h7"></path></svg>',
    nsGroup: '<svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="8" r="3"></circle><path d="M7 19c.5-3 2.4-4.5 5-4.5s4.5 1.5 5 4.5"></path><circle cx="5.5" cy="10" r="2.2"></circle><path d="M2.5 18c.3-2.1 1.5-3.3 3.3-3.6"></path><circle cx="18.5" cy="10" r="2.2"></circle><path d="M21.5 18c-.3-2.1-1.5-3.3-3.3-3.6"></path></svg>',
    nsLanguage: '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 5h8"></path><path d="M8 3v2"></path><path d="M6 5c.5 3.2 2.4 5.5 6 7"></path><path d="M11 5c-.7 2.9-2.5 5.2-6 7"></path><path d="M14 20l3.2-8 3.3 8"></path><path d="M15.2 17h4"></path></svg>',
    nsLocation: '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 21s6-5.6 6-11a6 6 0 0 0-12 0c0 5.4 6 11 6 11z"></path><circle cx="12" cy="10" r="2"></circle></svg>',
    nsMale: '<svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="9.5" cy="14.5" r="4.5"></circle><path d="M13 11l6-6"></path><path d="M15 5h4v4"></path></svg>',
    nsMixed: '<svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="9" cy="13" r="4"></circle><circle cx="14" cy="10" r="4"></circle><path d="M16.8 7.2L20 4"></path><path d="M17 4h3v3"></path><path d="M9 17v4"></path><path d="M6.5 19h5"></path></svg>',
    nsOther: '<svg viewBox="0 0 24 24" aria-hidden="true"><rect x="5" y="5" width="4.5" height="4.5" rx="0.8"></rect><circle cx="16.5" cy="7.25" r="2.25"></circle><path d="M7.25 14.5l-2.75 5h5.5l-2.75-5z"></path><path d="M16.5 14.5l3 3-3 3-3-3 3-3z"></path></svg>',
    nsParody: '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M6 5.5c3.8 1 8.2 1 12 0v6.2c0 4.1-2.6 7.2-6 8.3-3.4-1.1-6-4.2-6-8.3V5.5z"></path><path d="M8.5 10.5c.7-.8 1.5-.8 2.2 0"></path><path d="M13.3 10.5c.7-.8 1.5-.8 2.2 0"></path><path d="M9 14.5c1.6 1.4 4.4 1.4 6 0"></path></svg>',
    nsReclass: '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 5.5c2.8 0 5 .7 8 2.5v12c-3-1.8-5.2-2.5-8-2.5z"></path><path d="M20 5.5c-2.8 0-5 .7-8 2.5v12c3-1.8 5.2-2.5 8-2.5z"></path><path d="M12 8v12"></path></svg>'
  };

  function normalizeEhpMode(mode) {
    return ["picture", "webtoon", "manga"].includes(mode) ? mode : "picture";
  }

  const EHP_READER_GUIDE_DOCKED_KEY = "ehpUserGuideDocked";
  const EHP_POPUP_CLOSE_EVENT = "ehpPopupClose";

  function isEhpReaderGuideDocked() {
    return !!_GM_getValue(EHP_READER_GUIDE_DOCKED_KEY, false);
  }

  function closeEhpPopups(exceptRoot = null) {
    document.dispatchEvent(new CustomEvent(EHP_POPUP_CLOSE_EVENT, { detail: { exceptRoot } }));
  }

  function shouldIgnoreEhpPopupClose(event, root) {
    return !!(event.detail && event.detail.exceptRoot === root);
  }

  function applyEhpReaderUiSide(ui) {
    const isLeft = store.settings.readerUiSide === "left";
    document.documentElement.classList.toggle("ehp-reader-ui-left", isLeft);
    const root = ui && ui.root ? ui.root : document.getElementById("ehp-reader-ui");
    if (root) root.classList.toggle("ehp-ui-left", isLeft);
    if (ui && ui.guide && ui.guide.sideSwitch) {
      ui.guide.sideSwitch.classList.toggle("is-left", isLeft);
      ui.guide.sideSwitch.setAttribute("aria-pressed", String(isLeft));
    }
  }

  function isEhpUiTarget(target) {
    return !!(target && target.closest && target.closest("#ehp-reader-ui, #ehp-reader-launcher, #ehp-reader-thumbs, #ehp-tag-system, #ehp-page-theme-controls, #ehp-global-top, #ehp-quick-fav-menu, button, input, select, textarea"));
  }

  function setEhpInputModeClass() {
    document.documentElement.classList.add("ehp-desktop-like");
  }


  function createFloatControl(spmHandle) {
    ensureEhpReaderStyle();
    if (document.getElementById("ehp-reader-launcher")) return;

    const button = document.createElement("button");
    button.id = "ehp-reader-launcher";
    button.type = "button";
    button.innerHTML = EHP_ICONS.openBook;
    button.title = "Open reader";
    button.setAttribute("aria-label", "Open reader");
    button.addEventListener("click", (event) => {
      event.preventDefault();
      event.stopPropagation();
      closeEhpPopups();
      spmHandle.open();
    });
    document.body.appendChild(button);
  }

  function mountEhpOverlayUI(overlay, api) {
    const root = document.createElement("div");
    root.id = "ehp-reader-ui";

    const guide = createEhpReaderGuide();

    const topButtonWrap = document.createElement("div");
    topButtonWrap.className = "ehp-top-button";
    const topButton = createEhpButton(EHP_ICONS.up, "Click: top/first page. Hold: bottom/last page.");
    topButtonWrap.appendChild(topButton);

    const actionStack = document.createElement("div");
    actionStack.className = "ehp-action-stack";

    const modeItem = createEhpStackItem("mode", EHP_ICONS.mode, "Reading mode");
    const fitItem = createEhpStackItem("fit", EHP_ICONS.fit, "Fit and zoom");
    const gapItem = createEhpStackItem("gap", EHP_ICONS.gap, "Page gap");
    const pageItem = createEhpStackItem("page", EHP_ICONS.reader, "Jump to page");
    const themeItem = createEhpStackItem("theme", EHP_ICONS.theme, "Theme color");
    const closeItem = createEhpDirectStackItem("close", EHP_ICONS.closedBook, "Close reader");

    actionStack.append(modeItem.item, fitItem.item, gapItem.item, pageItem.item, themeItem.item, closeItem.item);

    const menuButtonWrap = document.createElement("div");
    menuButtonWrap.className = "ehp-menu-button";
    const menuButton = createEhpButton(EHP_ICONS.menu, "Menu");
    menuButtonWrap.appendChild(menuButton);

    root.append(guide.buttonWrap, topButtonWrap, actionStack, menuButtonWrap, guide.panel);
    overlay.appendChild(root);

    const modeToggles = createEhpToggleGroup([
      { label: "Picture", value: "picture", onSelect: () => { api.setMode("picture"); armCollapse(); } },
      { label: "Webtoon", value: "webtoon", onSelect: () => { api.setMode("webtoon"); armCollapse(); } },
      { label: "Manga", value: "manga", onSelect: () => { api.setMode("manga"); armCollapse(); } }
    ]);
    modeItem.panel.appendChild(modeToggles.root);

    fitItem.panel.classList.add("ehp-panel-vertical");
    const fitToggles = createEhpToggleGroup([
      { label: "Vertical", value: 0, onSelect: () => { api.setZoom(0, true); armCollapse(); } },
      { label: "Horizontal", value: 100, onSelect: () => { api.setZoom(100, true); armCollapse(); } }
    ]);
    const zoomWrap = document.createElement("div");
    zoomWrap.className = "ehp-slider-wrap";
    const zoomTop = document.createElement("div");
    zoomTop.className = "ehp-slider-top";
    const zoomLabel = document.createElement("span");
    zoomLabel.textContent = "Zoom";
    const zoomValue = document.createElement("span");
    zoomValue.className = "ehp-slider-value";
    zoomTop.append(zoomLabel, zoomValue);
    const zoomRow = document.createElement("div");
    zoomRow.className = "ehp-slider-row";
    const zoomSlider = document.createElement("input");
    zoomSlider.type = "range";
    zoomSlider.min = "0";
    zoomSlider.max = "100";
    zoomSlider.step = "1";
    const zoomReset = document.createElement("button");
    zoomReset.type = "button";
    zoomReset.textContent = "Reset";
    zoomRow.append(zoomSlider, zoomReset);
    zoomWrap.append(zoomTop, zoomRow);
    fitItem.panel.append(fitToggles.root, zoomWrap);

    const gapToggles = createEhpToggleGroup([0, 5, 10, 15].map((gap) => ({
      label: `${gap}px`,
      value: gap,
      onSelect: () => { api.setGap(gap); armCollapse(); }
    })));
    gapItem.panel.appendChild(gapToggles.root);

    const pagePanel = document.createElement("div");
    pagePanel.className = "ehp-jump";
    const pageInput = document.createElement("input");
    pageInput.type = "number";
    pageInput.min = "1";
    pageInput.placeholder = "Page";
    const pageButton = document.createElement("button");
    pageButton.type = "button";
    pageButton.textContent = "Go";
    pagePanel.append(pageInput, pageButton);
    pageItem.panel.appendChild(pagePanel);

    themeItem.panel.classList.add("ehp-panel-vertical");
    const colorPicker = createEhpColorPicker();
    themeItem.panel.appendChild(colorPicker.root);

    const ui = {
      root,
      menuButton,
      topButton,
      items: { mode: modeItem, fit: fitItem, gap: gapItem, page: pageItem, theme: themeItem, close: closeItem },
      modeButtons: modeToggles.buttons,
      fitButtons: fitToggles.buttons,
      gapButtons: gapToggles.buttons,
      pageInput,
      zoomSlider,
      zoomValue,
      color: colorPicker,
      guide,
      menuOpen: false,
      openPanelName: null,
      pointerInside: false,
      collapseTimer: 0
    };

    const MENU_COLLAPSE_DELAY_MS = 5000;

    function clearCollapse() {
      clearTimeout(ui.collapseTimer);
      ui.collapseTimer = 0;
    }

    function hasFocusedMenuInput() {
      const active = document.activeElement;
      return !!(active && root.contains(active) && /^(INPUT|TEXTAREA|SELECT)$/i.test(active.tagName));
    }

    function markMenuInteraction() {
      if (!ui.menuOpen) return;
      clearCollapse();
    }

    function armCollapse(force = false) {
      clearCollapse();
      if (!ui.menuOpen) return;
      if (!force && ui.pointerInside) return;
      if (hasFocusedMenuInput()) return;
      ui.collapseTimer = window.setTimeout(() => {
        if (ui.pointerInside || hasFocusedMenuInput()) return;
        closeMenu();
      }, MENU_COLLAPSE_DELAY_MS);
    }

    function openMenu() {
      closeEhpPopups(root);
      guide.close();
      ui.menuOpen = true;
      root.classList.add("is-menu-open");
      armCollapse();
    }

    function closeMenu() {
      clearCollapse();
      ui.menuOpen = false;
      ui.openPanelName = null;
      root.classList.remove("is-menu-open");
      closePanels();
    }

    function closePanels() {
      Object.values(ui.items).forEach((item) => item.item.classList.remove("is-open"));
      ui.openPanelName = null;
    }

    function openPanel(name, options = {}) {
      openMenu();
      ui.openPanelName = name;
      Object.entries(ui.items).forEach(([key, item]) => item.item.classList.toggle("is-open", key === name));
      if (name === "theme") updateEhpColorPickerUI(ui);
      if (options.noAutoCollapse) clearCollapse();
      else armCollapse();
    }

    root.addEventListener("pointerenter", () => {
      ui.pointerInside = true;
      clearCollapse();
    });
    root.addEventListener("pointermove", markMenuInteraction);
    root.addEventListener("pointerdown", markMenuInteraction);
    root.addEventListener("click", markMenuInteraction);
    root.addEventListener("focusin", markMenuInteraction);
    root.addEventListener("focusout", () => {
      window.setTimeout(() => armCollapse(), 0);
    });
    root.addEventListener("pointerleave", () => {
      ui.pointerInside = false;
      armCollapse(true);
    });

    document.addEventListener(EHP_POPUP_CLOSE_EVENT, (event) => {
      if (shouldIgnoreEhpPopupClose(event, root)) return;
      closeMenu();
      guide.close();
    });

    menuButton.addEventListener("click", (event) => {
      event.preventDefault();
      event.stopPropagation();
      if (ui.menuOpen) closeMenu();
      else openMenu();
    });

    guide.button.addEventListener("click", (event) => {
      event.preventDefault();
      event.stopPropagation();
      const shouldOpen = !guide.panel.classList.contains("is-open");
      closeMenu();
      if (shouldOpen) closeEhpPopups(root);
      guide.toggle();
    });

    guide.closeButton.addEventListener("click", (event) => {
      event.preventDefault();
      event.stopPropagation();
      _GM_setValue(EHP_READER_GUIDE_DOCKED_KEY, true);
      guide.buttonWrap.classList.add("is-docked");
      guide.close();
    });

    guide.sideSwitch.addEventListener("click", (event) => {
      event.preventDefault();
      event.stopPropagation();
      store.updateSetting("readerUiSide", store.settings.readerUiSide === "left" ? "right" : "left");
      applyEhpReaderUiSide(ui);
    });

    closeItem.button.addEventListener("click", (event) => {
      event.preventDefault();
      event.stopPropagation();
      api.close();
    });

    wireEhpPanelToggle(modeItem, "mode", openPanel, closePanels, armCollapse);
    wireEhpPanelToggle(fitItem, "fit", openPanel, closePanels, armCollapse);
    wireEhpPanelToggle(gapItem, "gap", openPanel, closePanels, armCollapse);
    wireEhpPanelToggle(pageItem, "page", openPanel, closePanels, armCollapse, { noAutoCollapse: true });
    wireEhpPanelToggle(themeItem, "theme", openPanel, closePanels, armCollapse);

    pageButton.addEventListener("click", () => { markMenuInteraction(); api.jumpToPage(pageInput.value, "smooth"); });
    pageInput.addEventListener("keydown", (event) => {
      markMenuInteraction();
      if (event.key === "Enter") api.jumpToPage(pageInput.value, "smooth");
    });

    zoomSlider.addEventListener("input", () => { markMenuInteraction(); api.setZoom(parseInt(zoomSlider.value, 10), false); });
    zoomSlider.addEventListener("change", () => {
      _GM_setValue("zoomPercent", store.settings.zoomPercent);
      armCollapse();
    });
    zoomReset.addEventListener("click", () => {
      api.setZoom(0, true);
      armCollapse();
    });

    setupEhpTopButton(topButton, api.topOrFirst, api.bottomOrLast);
    syncEhpUI(ui);
    applyEhpReaderUiSide(ui);
    return ui;
  }

  function createEhpButton(icon, label) {
    const button = document.createElement("button");
    button.type = "button";
    button.className = "ehp-btn";
    button.innerHTML = icon;
    button.title = label;
    button.setAttribute("aria-label", label);
    return button;
  }

  function createEhpStackItem(name, icon, label) {
    const item = document.createElement("div");
    item.className = "ehp-stack-item";
    item.dataset.item = name;
    const panel = document.createElement("div");
    panel.className = "ehp-panel";
    const button = createEhpButton(icon, label);
    item.append(panel, button);
    return { item, panel, button };
  }

  function createEhpDirectStackItem(name, icon, label) {
    const item = document.createElement("div");
    item.className = "ehp-stack-item";
    item.dataset.item = name;
    const button = createEhpButton(icon, label);
    item.appendChild(button);
    return { item, button };
  }

  function createEhpToggleGroup(items) {
    const root = document.createElement("div");
    root.className = "ehp-segmented";
    const buttons = items.map((item) => {
      const button = document.createElement("button");
      button.type = "button";
      button.className = "ehp-chip";
      button.textContent = item.label;
      button.dataset.value = String(item.value);
      button.addEventListener("click", item.onSelect);
      root.appendChild(button);
      return button;
    });
    return { root, buttons };
  }

  function createEhpReaderGuide() {
    const buttonWrap = document.createElement("div");
    buttonWrap.className = "ehp-guide-button";
    buttonWrap.classList.toggle("is-docked", isEhpReaderGuideDocked());

    const button = createEhpButton(EHP_ICONS.guide, "User guide");
    buttonWrap.appendChild(button);

    const guideControlIcons = {
      esc: '<span class="ehp-guide-manrope-icon is-esc">Esc</span>',
      previous: '<svg viewBox="0 0 24 24" width="22" height="22" aria-hidden="true"><path d="M15 6l-6 6 6 6"></path></svg>',
      next: '<svg viewBox="0 0 24 24" width="22" height="22" aria-hidden="true"><path d="M9 6l6 6-6 6"></path></svg>',
      page: '<svg viewBox="0 0 24 24" width="22" height="22" aria-hidden="true"><path d="M7 4h7l4 4v12H7z"></path><path d="M14 4v4h4"></path><path d="M9 13h6"></path><path d="M9 16h4"></path></svg>',
      zoomIn: EHP_ICONS.add,
      zoomOut: EHP_ICONS.remove,
      resetFit: '<span class="ehp-guide-manrope-icon is-zero">0</span>'
    };
    const keyIcon = (label, icon = "") => `<span class="ehp-guide-key ${icon ? "has-icon" : ""}" aria-label="${label}">${icon || `<span class="ehp-guide-key-text">${label}</span>`}</span>`;
    const panel = document.createElement("div");
    panel.className = "ehp-reader-guide";
    panel.innerHTML = `
      <div class="ehp-guide-title-row">
        <div class="ehp-guide-title-icon">${EHP_ICONS.guide}</div>
        <div>
          <h2>User guide</h2>
          <p>Controls for the web reader.</p>
        </div>
      </div>

      <div class="ehp-guide-section ehp-guide-desktop">
        <h3>Keyboard Control</h3>
        <div class="ehp-guide-list">
          <div class="ehp-guide-item">${keyIcon("Esc", guideControlIcons.esc)}<span>Close the overlay reader.</span></div>
          <div class="ehp-guide-item">${keyIcon("Previous", guideControlIcons.previous)}<span>Previous page or spread.</span></div>
          <div class="ehp-guide-item">${keyIcon("Next", guideControlIcons.next)}<span>Next page or spread.</span></div>
          <div class="ehp-guide-item">${keyIcon("Page", guideControlIcons.page)}<span>PageUp and PageDown step through pages.</span></div>
          <div class="ehp-guide-item">${keyIcon("Increase zoom", guideControlIcons.zoomIn)}<span>Increase zoom.</span></div>
          <div class="ehp-guide-item">${keyIcon("Decrease zoom", guideControlIcons.zoomOut)}<span>Decrease zoom.</span></div>
          <div class="ehp-guide-item">${keyIcon("Reset fit", guideControlIcons.resetFit)}<span>Reset to Vertical fit.</span></div>
        </div>
      </div>

      <div class="ehp-guide-section ehp-guide-ui-controls">
        <h3>Ui Control</h3>
        <div class="ehp-guide-list">
          <div class="ehp-guide-item"><span class="ehp-guide-symbol">${EHP_ICONS.up}</span><span>Click: top or first page. Hold: bottom or last page.</span></div>
          <div class="ehp-guide-item"><span class="ehp-guide-symbol">${EHP_ICONS.menu}</span><span>Open mode, fit, gap, page jump, theme, and close controls.</span></div>
          <div class="ehp-guide-item"><span class="ehp-guide-symbol">${EHP_ICONS.tag}</span><span>Open tag search, saved tags, and gallery tag tools.</span></div>
          <div class="ehp-guide-item"><span class="ehp-guide-symbol">${EHP_ICONS.favorite}</span><span>On gallery pages, hover the native favourite button to choose a category quickly.</span></div>
          <div class="ehp-guide-item"><span class="ehp-guide-symbol">${EHP_ICONS.theme}</span><span>Use the page theme button to recolor native page elements.</span></div>
        </div>
      </div>

      <div class="ehp-guide-section">
        <h3>Modes</h3>
        <div class="ehp-guide-mode-grid">
          <div><strong>Picture</strong><span>One page at a time.</span></div>
          <div><strong>Webtoon</strong><span>Continuous vertical scroll.</span></div>
          <div><strong>Manga</strong><span>Two-page spread view.</span></div>
        </div>
      </div>
    `;

    const sideRow = document.createElement("div");
    sideRow.className = "ehp-reader-guide-row";
    const sideLabel = document.createElement("span");
    sideLabel.textContent = "Flip reader UI to left";
    const sideSwitch = document.createElement("button");
    sideSwitch.type = "button";
    sideSwitch.className = "ehp-guide-switch";
    sideSwitch.setAttribute("aria-label", "Flip reader UI side");
    sideSwitch.setAttribute("aria-pressed", String(store.settings.readerUiSide === "left"));
    sideSwitch.classList.toggle("is-left", store.settings.readerUiSide === "left");
    sideRow.append(sideLabel, sideSwitch);

    const closeButton = document.createElement("button");
    closeButton.type = "button";
    closeButton.className = "ehp-reader-guide-close";
    closeButton.textContent = "Hide user guide";

    panel.append(sideRow, closeButton);

    const open = () => {
      panel.classList.add("is-open");
      buttonWrap.classList.add("is-open");
    };
    const close = () => {
      panel.classList.remove("is-open");
      buttonWrap.classList.remove("is-open");
    };
    const toggle = () => panel.classList.contains("is-open") ? close() : open();


    return { buttonWrap, button, panel, closeButton, sideSwitch, open, close, toggle };
  }

  function wireEhpPanelToggle(entry, name, openPanel, closePanels, armCollapse, options = {}) {
    entry.button.addEventListener("click", (event) => {
      event.preventDefault();
      event.stopPropagation();
      const isOpen = entry.item.classList.contains("is-open");
      if (isOpen) {
        closePanels();
        if (!options.noAutoCollapse) armCollapse();
        return;
      }
      openPanel(name, options);
    });
  }

  function setupEhpTopButton(button, onShort, onLong) {
    let timer = 0;
    let longFired = false;
    const clear = () => {
      if (timer) clearTimeout(timer);
      timer = 0;
    };
    button.addEventListener("pointerdown", (event) => {
      event.preventDefault();
      event.stopPropagation();
      clear();
      longFired = false;
      timer = window.setTimeout(() => {
        longFired = true;
        onLong();
        timer = 0;
      }, 520);
    });
    const release = (event) => {
      event.preventDefault();
      event.stopPropagation();
      if (timer) {
        clear();
        if (!longFired) onShort();
      }
    };
    button.addEventListener("pointerup", release);
    button.addEventListener("pointerleave", clear);
    button.addEventListener("pointercancel", clear);
  }

  const EHP_PAGE_THEME_COLOR_KEY = "ehpPageThemeColor";
  const EHP_GLOBAL_THEME_ENABLED_KEY = "ehpGlobalThemeEnabled";
  const EHP_PAGE_THEME_PRESET = { bgSoft: 14, surface: 20, strong: 32, border: 52, input: 36, accent: 42, shadow: 42 };
  let ehpPageThemePicker = null;
  let ehpThemeMutationObserver = null;
  let ehpThemeMutationFrame = 0;

  function getEhpPageThemeColor() {
    return normalizeHex(_GM_getValue(EHP_PAGE_THEME_COLOR_KEY, ""));
  }

  function isEhpGlobalThemeEnabled() {
    return !!_GM_getValue(EHP_GLOBAL_THEME_ENABLED_KEY, true);
  }


  function getEhpContrastTextColor(hex) {
    const fixed = normalizeHex(hex) || "#f5f1e8";
    const r = parseInt(fixed.slice(1, 3), 16) / 255;
    const g = parseInt(fixed.slice(3, 5), 16) / 255;
    const b = parseInt(fixed.slice(5, 7), 16) / 255;
    const srgb = [r, g, b].map((value) => value <= 0.03928 ? value / 12.92 : Math.pow((value + 0.055) / 1.055, 2.4));
    const luminance = 0.2126 * srgb[0] + 0.7152 * srgb[1] + 0.0722 * srgb[2];
    return luminance > 0.48 ? "#15191f" : "#f7f8fa";
  }

  function ehpMix(base, other, percent) {
    return `color-mix(in srgb, ${base}, ${other} ${Math.max(0, Math.min(100, percent))}%)`;
  }

  function clearEhpGlobalThemeVars(root) {
    [
      "--ehp-page-bg", "--ehp-page-bg-soft", "--ehp-surface", "--ehp-surface-strong", "--ehp-border", "--ehp-text", "--ehp-text-muted", "--ehp-link", "--ehp-link-hover", "--ehp-accent", "--ehp-accent-soft", "--ehp-button-bg", "--ehp-button-hover", "--ehp-input-bg", "--ehp-shadow",
      "--ehp-page-theme-bg", "--ehp-page-theme-text", "--ehp-page-theme-soft", "--ehp-page-theme-control-bg", "--ehp-page-theme-control-text"
    ].forEach((name) => root.style.removeProperty(name));
  }


  function applyEhpGlobalPageTheme(color = getEhpPageThemeColor()) {
    const fixed = normalizeHex(color);
    const root = document.documentElement;

    if (!fixed || !isEhpGlobalThemeEnabled() || !isEhpFeatureEnabled("nativeTheme.pageColor", true)) {
      root.classList.remove("ehp-global-themed");
      clearEhpGlobalThemeVars(root);
      applyEhpSuiteDepth();
      return;
    }

    const preset = EHP_PAGE_THEME_PRESET;
    const textColor = getEhpContrastTextColor(fixed);
    const opposite = textColor === "#15191f" ? "#ffffff" : "#000000";
    const muted = ehpMix(textColor, fixed, 42);
    const border = ehpMix(textColor, fixed, 62);
    const surface = ehpMix(fixed, textColor, preset.surface);
    const strong = ehpMix(fixed, textColor, preset.strong);
    const input = ehpMix(fixed, textColor, preset.input);
    const accentSoft = ehpMix(fixed, textColor, preset.accent);
    const hover = ehpMix(fixed, textColor, preset.accent + 8);

    root.classList.add("ehp-global-themed");
    root.style.setProperty("--ehp-page-bg", fixed);
    root.style.setProperty("--ehp-page-bg-soft", ehpMix(fixed, textColor, preset.bgSoft));
    root.style.setProperty("--ehp-surface", surface);
    root.style.setProperty("--ehp-surface-strong", strong);
    root.style.setProperty("--ehp-border", border);
    root.style.setProperty("--ehp-text", textColor);
    root.style.setProperty("--ehp-text-muted", muted);
    root.style.setProperty("--ehp-link", ehpMix(textColor, fixed, 18));
    root.style.setProperty("--ehp-link-hover", ehpMix(textColor, opposite, 10));
    root.style.setProperty("--ehp-accent", fixed);
    root.style.setProperty("--ehp-accent-soft", accentSoft);
    root.style.setProperty("--ehp-button-bg", strong);
    root.style.setProperty("--ehp-button-hover", hover);
    root.style.setProperty("--ehp-input-bg", input);
    const isBrightTheme = textColor === "#15191f";
    root.dataset.ehpThemeTone = isBrightTheme ? "bright" : "dark";
    root.style.setProperty("--ehp-shadow", isBrightTheme
      ? `0 14px 34px color-mix(in srgb, #000000, transparent ${100 - preset.shadow}%)`
      : `0 0 0 1px transparent, 0 12px 32px color-mix(in srgb, #ffffff, transparent ${Math.max(76, 100 - Math.round(preset.shadow * 0.55))}%)`
    );
    root.style.setProperty("--ehp-theme-depth", "var(--ehp-shadow)");
    applyEhpSuiteDepth();

    // Backward-compatible aliases used by existing UI CSS.
    root.style.setProperty("--ehp-page-theme-bg", "var(--ehp-page-bg)");
    root.style.setProperty("--ehp-page-theme-text", "var(--ehp-text)");
    root.style.setProperty("--ehp-page-theme-soft", "var(--ehp-surface)");
    root.style.setProperty("--ehp-page-theme-control-bg", "var(--ehp-ui-surface)");
    root.style.setProperty("--ehp-page-theme-control-text", "var(--ehp-ui-text)");

    // Page theme, reader theme, and script UI theme intentionally remain separate.
    // Page color recolors only native page surfaces/text. Script controls/windows stay default.
    applyEhpSuiteDepth();
  }

  function observeEhpThemeMutations() {
    if (ehpThemeMutationObserver || !document.body) return;
    ehpThemeMutationObserver = new MutationObserver(() => {
      if (!document.documentElement.classList.contains("ehp-global-themed")) return;
      if (ehpThemeMutationFrame) return;
      ehpThemeMutationFrame = requestAnimationFrame(() => {
        ehpThemeMutationFrame = 0;
        applyEhpGlobalPageTheme();
      });
    });
    ehpThemeMutationObserver.observe(document.body, { childList: true, subtree: true });
  }

  function initEhpGlobalTopButton() {
    ensureEhpReaderStyle();
    if (document.getElementById("ehp-global-top")) return;

    const button = document.createElement("button");
    button.id = "ehp-global-top";
    button.type = "button";
    button.innerHTML = EHP_ICONS.up;
    button.title = "Click: page top. Hold: page bottom.";
    button.setAttribute("aria-label", "Click to scroll page top. Hold to scroll page bottom.");

    setupEhpTopButton(
      button,
      () => window.scrollTo({ top: 0, behavior: "smooth" }),
      () => window.scrollTo({ top: Math.max(document.documentElement.scrollHeight, document.body.scrollHeight), behavior: "smooth" })
    );

    document.body.appendChild(button);
  }

  function initEhpGlobalPageThemeControls() {
    ensureEhpReaderStyle();
    applyEhpGlobalPageTheme();

    if (document.getElementById("ehp-page-theme-controls")) return;

    const root = document.createElement("div");
    root.id = "ehp-page-theme-controls";

    const panel = document.createElement("div");
    panel.className = "ehp-page-theme-panel";

    const picker = createEhpPageThemeColorPicker();
    panel.appendChild(picker.root);

    const button = document.createElement("button");
    button.type = "button";
    button.className = "ehp-page-theme-launcher";
    button.innerHTML = EHP_ICONS.theme;
    button.title = "Page color";
    button.setAttribute("aria-label", "Page color");

    root.append(panel, button);
    document.body.appendChild(root);

    button.addEventListener("click", (event) => {
      event.preventDefault();
      event.stopPropagation();
      const shouldOpen = !root.classList.contains("is-open");
      closeEhpPopups(root);
      root.classList.toggle("is-open", shouldOpen);
      if (shouldOpen) updateEhpPageThemePickerUI(picker);
    });

    panel.addEventListener("click", (event) => event.stopPropagation());
    panel.addEventListener("pointerdown", (event) => event.stopPropagation());


    document.addEventListener(EHP_POPUP_CLOSE_EVENT, (event) => {
      if (shouldIgnoreEhpPopupClose(event, root)) return;
      root.classList.remove("is-open");
    });

    updateEhpPageThemePickerUI(picker);
  }

function createEhpPageThemeColorPicker() {
  const root = document.createElement("div");
  root.className = "ehp-color-picker ehp-page-theme-picker";

  // The page theme picker is intentionally only a color picker now.
  // Global theming is handled by the page theme engine; reader theme remains separate.

  const square = document.createElement("div");
  square.className = "ehp-color-square";
  const knob = document.createElement("div");
  knob.className = "ehp-color-knob";
  square.appendChild(knob);

  const hueRow = document.createElement("div");
  hueRow.className = "ehp-hue-row";
  const hueSlider = document.createElement("input");
  hueSlider.className = "ehp-hue-slider";
  hueSlider.type = "range";
  hueSlider.min = "0";
  hueSlider.max = "360";
  hueSlider.step = "1";
  const resetButton = document.createElement("button");
  resetButton.type = "button";
  resetButton.textContent = "Reset";
  hueRow.append(hueSlider, resetButton);
  root.append(square, hueRow);

  ehpPageThemePicker = hexToHsv(getEhpPageThemeColor() || "#f5f1e8");

  const parts = { root, square, knob, hueSlider };

  const savePickerColor = () => {
    const color = hsvToHex(ehpPageThemePicker.h, ehpPageThemePicker.s, ehpPageThemePicker.v);
    _GM_setValue(EHP_PAGE_THEME_COLOR_KEY, color);
    _GM_setValue(EHP_GLOBAL_THEME_ENABLED_KEY, true);
    applyEhpGlobalPageTheme(color);
    updateEhpPageThemePickerUI(parts);
  };

  const updateSquareFromPointer = (event) => {
    const rect = square.getBoundingClientRect();
    const x = Math.max(0, Math.min(rect.width, event.clientX - rect.left));
    const y = Math.max(0, Math.min(rect.height, event.clientY - rect.top));
    ehpPageThemePicker.s = x / rect.width;
    ehpPageThemePicker.v = 1 - y / rect.height;
    savePickerColor();
  };

  square.addEventListener("pointerdown", (event) => {
    event.preventDefault();
    square.setPointerCapture(event.pointerId);
    updateSquareFromPointer(event);
  });
  square.addEventListener("pointermove", (event) => {
    if (event.buttons !== 1) return;
    updateSquareFromPointer(event);
  });

  hueSlider.addEventListener("input", () => {
    ehpPageThemePicker.h = parseInt(hueSlider.value, 10);
    savePickerColor();
  });

  // Selecting a page color enables full global page theming automatically; reader theme remains separate.

  resetButton.addEventListener("click", () => {
    _GM_setValue(EHP_PAGE_THEME_COLOR_KEY, "");
    _GM_setValue(EHP_GLOBAL_THEME_ENABLED_KEY, false);
    ehpPageThemePicker = hexToHsv("#f5f1e8");
    applyEhpGlobalPageTheme(null);
    updateEhpPageThemePickerUI(parts);
  });

  updateEhpPageThemePickerUI(parts);
  return parts;
}

function updateEhpPageThemePickerUI(parts) {
  if (!parts) return;
  const activeColor = getEhpPageThemeColor();
  const displayColor = activeColor || "#f5f1e8";
  if (!ehpPageThemePicker) ehpPageThemePicker = hexToHsv(displayColor);

  const { square, knob, hueSlider } = parts;
  hueSlider.value = String(Math.round(ehpPageThemePicker.h));
  square.style.setProperty("--ehp-picker-hue", String(Math.round(ehpPageThemePicker.h)));
  knob.style.left = `${ehpPageThemePicker.s * 100}%`;
  knob.style.top = `${(1 - ehpPageThemePicker.v) * 100}%`;
}

function createEhpColorPicker() {
  const root = document.createElement("div");
  root.className = "ehp-color-picker";

  const square = document.createElement("div");
  square.className = "ehp-color-square";
  const knob = document.createElement("div");
  knob.className = "ehp-color-knob";
  square.appendChild(knob);

  const hueRow = document.createElement("div");
  hueRow.className = "ehp-hue-row";
  const hueSlider = document.createElement("input");
  hueSlider.className = "ehp-hue-slider";
  hueSlider.type = "range";
  hueSlider.min = "0";
  hueSlider.max = "360";
  hueSlider.step = "1";
  const resetButton = document.createElement("button");
  resetButton.type = "button";
  resetButton.textContent = "Reset";
  hueRow.append(hueSlider, resetButton);
  root.append(square, hueRow);

  store.picker = hexToHsv(store.settings.themeColor);

  const updateSquareFromPointer = (event) => {
    const rect = square.getBoundingClientRect();
    const x = Math.max(0, Math.min(rect.width, event.clientX - rect.left));
    const y = Math.max(0, Math.min(rect.height, event.clientY - rect.top));
    store.picker.s = x / rect.width;
    store.picker.v = 1 - y / rect.height;
    updateEhpThemeColorFromPicker(false);
    updateEhpColorPickerUI({ color: { square, knob, hueSlider } });
  };

  square.addEventListener("pointerdown", (event) => {
    event.preventDefault();
    square.setPointerCapture(event.pointerId);
    updateSquareFromPointer(event);
  });
  square.addEventListener("pointermove", (event) => {
    if (event.buttons !== 1) return;
    updateSquareFromPointer(event);
  });
  square.addEventListener("pointerup", () => _GM_setValue("themeColor", store.settings.themeColor));

  hueSlider.addEventListener("input", () => {
    store.picker.h = parseInt(hueSlider.value, 10);
    updateEhpThemeColorFromPicker(false);
    updateEhpColorPickerUI({ color: { square, knob, hueSlider } });
  });
  hueSlider.addEventListener("change", () => _GM_setValue("themeColor", store.settings.themeColor));

  resetButton.addEventListener("click", () => {
    store.settings.themeColor = "#f5f1e8";
    store.picker = hexToHsv(store.settings.themeColor);
    _GM_setValue("themeColor", store.settings.themeColor);
    applyEhpThemeColor();
    updateEhpColorPickerUI({ color: { square, knob, hueSlider } });
  });

  return { root, square, knob, hueSlider };
}

  function updateEhpThemeColorFromPicker(shouldSave) {
    store.settings.themeColor = hsvToHex(store.picker.h, store.picker.s, store.picker.v);
    applyEhpThemeColor();
    if (shouldSave) _GM_setValue("themeColor", store.settings.themeColor);
  }

function updateEhpColorPickerUI(ui) {
  const color = ui && ui.color;
  if (!color || !store.picker) return;
  const { square, knob, hueSlider } = color;
  hueSlider.value = String(Math.round(store.picker.h));
  square.style.setProperty("--ehp-picker-hue", String(Math.round(store.picker.h)));
  knob.style.left = `${store.picker.s * 100}%`;
  knob.style.top = `${(1 - store.picker.v) * 100}%`;
}

  function applyEhpSuiteDepth() {
    const root = document.documentElement;
    root.dataset.ehpSuiteTone = "bright";
    root.style.setProperty("--ehp-ui-surface", EHP_STATIC_SCRIPT_UI.surface);
    root.style.setProperty("--ehp-ui-stroke", "transparent");
    root.style.setProperty("--ehp-ui-text", EHP_STATIC_SCRIPT_UI.text);
    root.style.setProperty("--ehp-ui-fill", EHP_STATIC_SCRIPT_UI.fill);

    root.style.setProperty("--ehp-reader-ui-surface", "var(--ehp-ui-surface)");
    root.style.setProperty("--ehp-reader-ui-text", "var(--ehp-ui-text)");
    root.style.setProperty("--ehp-reader-ui-soft", "color-mix(in srgb, #f5f1e8, #2d3137 12%)");
    root.style.setProperty("--ehp-reader-ui-input-bg", EHP_STATIC_SCRIPT_UI.input);
    root.style.setProperty("--ehp-reader-ui-stroke", "transparent");

    root.style.setProperty("--ehp-global-ui-bg", "var(--ehp-ui-surface)");
    root.style.setProperty("--ehp-global-ui-text", "var(--ehp-ui-text)");
    root.style.setProperty("--ehp-global-ui-soft", "var(--ehp-ui-surface)");
    root.style.setProperty("--ehp-global-ui-input-bg", EHP_STATIC_SCRIPT_UI.input);
    root.style.setProperty("--ehp-global-ui-stroke", "transparent");

    root.style.setProperty("--ehp-suite-depth", "0 12px 30px color-mix(in srgb, #000000, transparent 78%)");
    root.style.setProperty("--ehp-suite-depth-soft", "0 7px 18px color-mix(in srgb, #000000, transparent 86%)");
    root.style.setProperty("--ehp-suite-icon-depth", "drop-shadow(0 1px 0 rgba(255,255,255,.34)) drop-shadow(0 2px 3px rgba(0,0,0,.36))");
    root.style.setProperty("--ehp-control-shadow", "var(--ehp-suite-depth)");
    root.style.setProperty("--ehp-icon-shadow", "var(--ehp-suite-icon-depth)");
    root.style.setProperty("--ehp-theme-depth", "var(--ehp-suite-depth)");
  }
  function applyEhpThemeColor() {
    const fixed = normalizeHex(store.settings.themeColor) || EHP_STATIC_SCRIPT_UI.color;
    const root = document.documentElement;
    // Reader color controls the reader canvas/background only.
    // Script UI controls/windows intentionally keep the static default suite color.
    root.style.setProperty("--ehp-theme-bg", fixed);
    applyEhpSuiteDepth();
  }
  function applyEhpGap() {
    document.documentElement.style.setProperty("--ehp-reader-gap", `${Math.max(0, Number(store.settings.pageGap) || 0)}px`);
  }

  function applyEhpZoom() {
    const zoom = Math.max(0, Math.min(100, Number(store.settings.zoomPercent) || 0));
    const overlay = document.getElementById("ehp-reader-overlay");
    const gap = Math.max(0, Number(store.settings.pageGap) || 0);
    const verticalHeight = Math.max(180, window.innerHeight - 20);
    const fullWidth = Math.max(240, window.innerWidth - 20);
    const mangaPageWidth = Math.max(120, Math.floor((fullWidth - gap) / 2));

    document.documentElement.style.setProperty("--ehp-zoom-width", `${fullWidth}px`);
    document.documentElement.style.setProperty("--ehp-manga-page-width", `${mangaPageWidth}px`);

    if (overlay) {
      overlay.classList.toggle("ehp-zoom-over", zoom > 0);
      overlay.classList.toggle("ehp-fit-mode", zoom === 0);

      const images = overlay.querySelectorAll(".ehp-current-image, .ehp-reader-image");
      images.forEach((img) => {
        const naturalWidth = img.naturalWidth || img.width || 0;
        const naturalHeight = img.naturalHeight || img.height || 0;
        if (!naturalWidth || !naturalHeight) {
          img.style.width = "";
          img.style.maxWidth = "none";
          img.style.maxHeight = "none";
          img.style.height = "auto";
          return;
        }

        const ratio = naturalWidth / naturalHeight;
        const verticalFitWidth = verticalHeight * ratio;
        const horizontalFitWidth = img.closest(".ehp-stage-manga") ? mangaPageWidth : fullWidth;
        const targetWidth = verticalFitWidth + (horizontalFitWidth - verticalFitWidth) * (zoom / 100);

        img.style.width = `${Math.max(80, targetWidth).toFixed(2)}px`;
        img.style.height = "auto";
        img.style.maxWidth = "none";
        img.style.maxHeight = "none";
        img.style.objectFit = "contain";
      });
    }
  }

  function syncEhpUI(ui) {
    if (!ui) return;
    const mode = normalizeEhpMode(store.settings.readerMode);
    ui.modeButtons.forEach((btn) => btn.classList.toggle("is-active", btn.dataset.value === mode));
    ui.fitButtons.forEach((btn) => btn.classList.toggle("is-active", Number(btn.dataset.value) === Number(store.settings.zoomPercent)));
    ui.gapButtons.forEach((btn) => btn.classList.toggle("is-active", Number(btn.dataset.value) === Number(store.settings.pageGap)));
    ui.zoomSlider.value = String(Math.max(0, Math.min(100, Number(store.settings.zoomPercent) || 0)));
    ui.zoomValue.textContent = `${ui.zoomSlider.value}%`;
    const currentPage = store.imageOffset + store.currentImageIndex + 1;
    if (document.activeElement !== ui.pageInput) ui.pageInput.value = String(currentPage);
    updateEhpColorPickerUI(ui);
  }

  function normalizeHex(value) {
    let hex = String(value || "").trim();
    if (!hex) return null;
    if (!hex.startsWith("#")) hex = "#" + hex;
    if (/^#[0-9a-f]{3}$/i.test(hex)) {
      hex = "#" + hex.slice(1).split("").map((ch) => ch + ch).join("");
    }
    return /^#[0-9a-f]{6}$/i.test(hex) ? hex.toLowerCase() : null;
  }

  function hexToHsv(hex) {
    const fixed = normalizeHex(hex) || "#f5f1e8";
    const r = parseInt(fixed.slice(1, 3), 16) / 255;
    const g = parseInt(fixed.slice(3, 5), 16) / 255;
    const b = parseInt(fixed.slice(5, 7), 16) / 255;
    const max = Math.max(r, g, b);
    const min = Math.min(r, g, b);
    const delta = max - min;
    let h = 0;
    if (delta !== 0) {
      if (max === r) h = 60 * (((g - b) / delta) % 6);
      else if (max === g) h = 60 * ((b - r) / delta + 2);
      else h = 60 * ((r - g) / delta + 4);
    }
    if (h < 0) h += 360;
    return { h, s: max === 0 ? 0 : delta / max, v: max };
  }

  function hsvToHex(h, s, v) {
    const c = v * s;
    const x = c * (1 - Math.abs((h / 60) % 2 - 1));
    const m = v - c;
    let r1 = 0, g1 = 0, b1 = 0;
    if (h >= 0 && h < 60) { r1 = c; g1 = x; }
    else if (h >= 60 && h < 120) { r1 = x; g1 = c; }
    else if (h >= 120 && h < 180) { g1 = c; b1 = x; }
    else if (h >= 180 && h < 240) { g1 = x; b1 = c; }
    else if (h >= 240 && h < 300) { r1 = x; b1 = c; }
    else { r1 = c; b1 = x; }
    const toHex = (value) => Math.round((value + m) * 255).toString(16).padStart(2, "0");
    return `#${toHex(r1)}${toHex(g1)}${toHex(b1)}`;
  }

  function ensureEhpReaderStyle() {
    if (document.getElementById("ehp-reader-style")) return;
    const style = document.createElement("style");
    style.id = "ehp-reader-style";
    style.textContent = `
      :root {
        --ehp-theme-bg: ${store.settings.themeColor};
        --ehp-ui-surface: rgba(245, 241, 232, 0.96);
        --ehp-ui-stroke: transparent;
        --ehp-ui-text: #2d3137;
        --ehp-ui-fill: #303843;
        --ehp-reader-ui-surface: var(--ehp-ui-surface);
        --ehp-reader-ui-text: var(--ehp-ui-text);
        --ehp-reader-ui-soft: color-mix(in srgb, #f5f1e8, #2d3137 12%);
        --ehp-reader-ui-input-bg: rgba(255, 255, 255, 0.72);
        --ehp-reader-ui-stroke: transparent;
        --ehp-global-ui-bg: var(--ehp-ui-surface);
        --ehp-global-ui-text: var(--ehp-ui-text);
        --ehp-global-ui-soft: var(--ehp-ui-surface);
        --ehp-global-ui-input-bg: rgba(255, 255, 255, 0.72);
        --ehp-global-ui-stroke: transparent;
        --ehp-page-bg: #f5f1e8;
        --ehp-page-bg-soft: #f7f4ee;
        --ehp-surface: rgba(245, 241, 232, 0.96);
        --ehp-surface-strong: rgba(255, 255, 255, 0.72);
        --ehp-border: rgba(0, 0, 0, 0.12);
        --ehp-text: #2d3137;
        --ehp-text-muted: rgba(45, 49, 55, 0.68);
        --ehp-link: #2d3137;
        --ehp-link-hover: #111;
        --ehp-accent: ${store.settings.themeColor};
        --ehp-accent-soft: rgba(255,255,255,.32);
        --ehp-button-bg: rgba(255,255,255,.42);
        --ehp-button-hover: rgba(255,255,255,.58);
        --ehp-input-bg: rgba(255,255,255,.72);
        --ehp-shadow: 0 14px 34px rgba(0,0,0,.26);
        --ehp-suite-depth: 0 12px 30px color-mix(in srgb, #000000, transparent 78%);
        --ehp-suite-depth-soft: 0 7px 18px color-mix(in srgb, #000000, transparent 86%);
        --ehp-suite-icon-depth: drop-shadow(0 1px 0 rgba(255,255,255,.34)) drop-shadow(0 2px 3px rgba(0,0,0,.36));
        --ehp-control-shadow: var(--ehp-suite-depth);
        --ehp-icon-shadow: var(--ehp-suite-icon-depth);
        --ehp-reader-gap: ${store.settings.pageGap}px;
        --ehp-zoom-width: calc(100vw - 32px);
        --ehp-manga-page-width: calc((100vw - 48px) / 2);
      }

      html.ehp-reader-open, html.ehp-reader-open body { overflow: hidden !important; }
      html.ehp-reader-open {
        --ehp-ui-surface: var(--ehp-reader-ui-surface);
        --ehp-ui-text: var(--ehp-reader-ui-text);
        --ehp-ui-fill: var(--ehp-reader-ui-text);
        --ehp-ui-stroke: var(--ehp-reader-ui-stroke);
      }

      #ehp-reader-launcher, #ehp-reader-ui, #ehp-reader-ui *, #ehp-reader-overlay, #ehp-reader-overlay *, #ehp-reader-thumbs, #ehp-reader-thumbs *, #ehp-global-top, #ehp-page-theme-controls, #ehp-page-theme-controls *, #ehp-tag-system, #ehp-tag-system *, #ehp-quick-fav-menu, #ehp-quick-fav-menu * {
        font-family:"Manrope","Inter","Segoe UI",system-ui,sans-serif;
      }

      #ehp-reader-launcher {
        position: fixed; right: 20px; bottom: 20px; z-index: 2147483646;
        width: 50px; height: 50px; border: 1px solid var(--ehp-global-ui-stroke, var(--ehp-ui-stroke)); border-radius: 50%;
        background: var(--ehp-global-ui-bg, var(--ehp-ui-surface)); color: var(--ehp-global-ui-text, var(--ehp-ui-text)); display: inline-flex; align-items: center; justify-content: center;
        cursor: pointer; box-shadow: var(--ehp-control-shadow); transition: transform 150ms ease, background-color 150ms ease, color 150ms ease;
      }
      #ehp-reader-launcher:hover { transform: scale(1.05); }
      #ehp-reader-launcher svg, .ehp-btn svg { display:block; fill:none; stroke:currentColor; stroke-width:2.2; stroke-linecap:round; stroke-linejoin:round; flex:none; filter:var(--ehp-icon-shadow); }

      #ehp-reader-overlay {
        position: fixed; inset: 0; z-index: 2147483647; display: none; overflow-y: auto; overflow-x: auto;
        background: var(--ehp-theme-bg); color: white; overscroll-behavior: contain; scroll-behavior: smooth; transition: background-color 180ms ease;
      }
      #ehp-reader-overlay.active { display: block; }
      #ehp-reader-overlay.ehp-mode-picture { overflow: auto; }
      #ehp-reader-overlay.ehp-zoom-gesture-active { cursor: ew-resize; }
      #ehp-reader-overlay.ehp-zoom-dragging { cursor: ew-resize; user-select: none; }

      .ehp-reader-stage { min-height:100vh; display:flex; flex-direction:column; align-items:center; gap:var(--ehp-reader-gap); padding:14px 0 120px; box-sizing:border-box; }
      .ehp-stage-picture { justify-content:center; padding:0; min-width:100%; }
      .ehp-picture-frame { min-height:100vh; min-width:100%; display:flex; align-items:center; justify-content:center; position:relative; box-sizing:border-box; padding:10px; }
      .ehp-page { width:min(100%, 1600px); min-height:300px; display:flex; justify-content:center; align-items:center; position:relative; scroll-margin-top:10px; scroll-margin-bottom:10px; }
      #ehp-reader-overlay.ehp-fit-mode .ehp-stage-webtoon .ehp-page { min-height: calc(100vh - 20px); }

      .ehp-current-image, .ehp-reader-image {
        display:block; width:auto; height:auto; max-width:none; max-height:none;
        border-radius:12px; background:rgba(0,0,0,.07); box-shadow:0 12px 32px rgba(0,0,0,.16); object-fit:contain; image-rendering:auto;
        opacity:0; will-change:width, max-width, max-height, opacity; transition: opacity 220ms ease, width 90ms cubic-bezier(.22,.61,.36,1), max-width 120ms ease, max-height 120ms ease, border-radius 180ms ease, box-shadow 180ms ease;
      }
      .ehp-current-image.loaded, .ehp-reader-image.loaded { opacity:1; }
      #ehp-reader-overlay.ehp-zoom-over .ehp-current-image, #ehp-reader-overlay.ehp-zoom-over .ehp-stage-webtoon .ehp-reader-image {
        width:min(var(--ehp-zoom-width), 3600px); max-width:none; max-height:none; object-fit:initial;
      }

      .ehp-stage-manga { justify-content:flex-start; }
      .ehp-spread { min-height:calc(100vh - 20px); width:100%; display:flex; flex-direction:row; justify-content:center; align-items:center; gap:var(--ehp-reader-gap); position:relative; scroll-margin-top:12px; scroll-margin-bottom:12px; box-sizing:border-box; }
      .ehp-manga-slot { position:relative; display:flex; justify-content:center; align-items:center; min-width:0; width:auto; }
      .ehp-manga-slot.is-empty { width:min(calc((100vw - 20px) / 2), 820px); min-height:60vh; }
      .ehp-stage-manga .ehp-reader-image { max-width:none; max-height:none; }
      #ehp-reader-overlay.ehp-zoom-over .ehp-stage-manga .ehp-reader-image { width:var(--ehp-manga-page-width); max-width:none; max-height:none; object-fit:initial; }

      .ehp-placeholder { min-width:240px; min-height:220px; padding:22px; border-radius:12px; background:rgba(0,0,0,.18); color:rgba(255,255,255,.75); display:flex; align-items:center; justify-content:center; font:700 14px/1.4 "Manrope","Inter","Segoe UI",system-ui,sans-serif; box-sizing:border-box; }

      #ehp-reader-ui { position:fixed; right:20px; bottom:20px; z-index:2147483647; display:flex; flex-direction:column; align-items:flex-end; gap:12px; pointer-events:none; user-select:none; }
      .ehp-top-button, .ehp-menu-button, .ehp-guide-button { pointer-events:auto; }
      .ehp-action-stack { display:flex; flex-direction:column; align-items:flex-end; gap:12px; max-height:0; opacity:0; overflow:visible; pointer-events:none; transition:max-height 260ms cubic-bezier(.2,.8,.2,1), opacity 180ms ease; }
      #ehp-reader-ui.is-menu-open .ehp-action-stack { max-height:520px; opacity:1; pointer-events:auto; }
      .ehp-stack-item { position:relative; display:flex; align-items:center; justify-content:flex-end; min-height:46px; pointer-events:none; opacity:0; transform:translate3d(0,14px,0) scale(.96); transition:opacity 180ms ease, transform 220ms cubic-bezier(.2,.8,.2,1); }
      #ehp-reader-ui.is-menu-open .ehp-stack-item { opacity:1; transform:translate3d(0,0,0) scale(1); pointer-events:auto; }
      #ehp-reader-ui.is-menu-open .ehp-stack-item:nth-child(1){transition-delay:20ms} #ehp-reader-ui.is-menu-open .ehp-stack-item:nth-child(2){transition-delay:45ms} #ehp-reader-ui.is-menu-open .ehp-stack-item:nth-child(3){transition-delay:70ms} #ehp-reader-ui.is-menu-open .ehp-stack-item:nth-child(4){transition-delay:95ms} #ehp-reader-ui.is-menu-open .ehp-stack-item:nth-child(5){transition-delay:120ms} #ehp-reader-ui.is-menu-open .ehp-stack-item:nth-child(6){transition-delay:145ms}
      .ehp-panel { position:absolute; right:calc(100% + 10px); top:50%; transform:translate3d(8px,-50%,0); display:flex; align-items:center; gap:10px; height:46px; padding:0; max-width:0; overflow:hidden; white-space:nowrap; opacity:0; pointer-events:none; border:1px solid var(--ehp-ui-stroke); border-radius:999px; background:var(--ehp-ui-surface); backdrop-filter:blur(14px); box-shadow:var(--ehp-control-shadow); box-sizing:border-box; transition:max-width 220ms ease, opacity 180ms ease, transform 220ms ease, padding 180ms ease; }
      .ehp-panel.ehp-panel-vertical { height:auto; min-height:46px; flex-direction:column; align-items:stretch; justify-content:center; border-radius:24px; white-space:normal; width:min(286px, calc(100vw - 108px)); max-width:calc(100vw - 108px); }
      .ehp-stack-item.is-open .ehp-panel { max-width:520px; padding:0 10px; opacity:1; transform:translate3d(0,-50%,0); pointer-events:auto; }
      .ehp-stack-item.is-open .ehp-panel.ehp-panel-vertical { padding:12px; }
      .ehp-btn { width:46px; height:46px; border:1px solid var(--ehp-ui-stroke); border-radius:50%; background:var(--ehp-ui-surface); color:var(--ehp-ui-text); display:inline-flex; align-items:center; justify-content:center; cursor:pointer; box-shadow:var(--ehp-control-shadow); transition:transform 150ms ease, background-color 150ms ease, color 150ms ease; }
      .ehp-btn:hover { transform:scale(1.04); }
      #ehp-reader-ui.is-menu-open .ehp-menu-button .ehp-btn { transform:rotate(90deg); }
      #ehp-reader-ui.is-menu-open .ehp-menu-button .ehp-btn:hover { transform:rotate(90deg) scale(1.04); }
      .ehp-segmented { display:flex; align-items:center; justify-content:flex-start; gap:8px; width:auto; padding:4px; border-radius:999px; box-sizing:border-box; flex:none; }
      .ehp-panel-vertical .ehp-segmented { width:100%; }
      .ehp-chip { flex:0 0 auto; min-width:72px; height:32px; padding:0 12px; border:0; border-radius:999px; background:transparent; color:color-mix(in srgb, var(--ehp-ui-text), transparent 24%); cursor:pointer; font-size:13px; font-weight:700; line-height:1; display:inline-flex; align-items:center; justify-content:center; transition:background-color 150ms ease, color 150ms ease; box-sizing:border-box; }
      .ehp-chip.is-active { background:var(--ehp-ui-text); color:var(--ehp-ui-surface); }
      .ehp-jump { display:flex; align-items:center; justify-content:flex-start; gap:8px; width:100%; }
      .ehp-jump input { height:32px; padding:0 12px; border:0; border-radius:999px; background:var(--ehp-reader-ui-input-bg, rgba(255,255,255,.72)); color:var(--ehp-ui-text); font-size:13px; font-weight:700; outline:none; box-sizing:border-box; }
      .ehp-jump input { width:90px; }
      .ehp-slider-wrap { display:flex; flex-direction:column; gap:8px; width:100%; min-width:0; }
      .ehp-slider-top { display:flex; align-items:center; justify-content:space-between; gap:12px; color:var(--ehp-ui-text); font-size:12px; font-weight:700; }
      .ehp-slider-value { min-width:48px; text-align:right; color:color-mix(in srgb, var(--ehp-ui-text), transparent 20%); }
      .ehp-slider-row, .ehp-hue-row { display:grid; grid-template-columns:minmax(0,1fr) auto; align-items:center; gap:8px; width:100%; }
      .ehp-slider-row input[type="range"] { width:100%; min-width:0; accent-color:var(--ehp-ui-text); cursor:pointer; }
      .ehp-slider-row button, .ehp-jump button, .ehp-color-picker button { min-width:58px; height:32px; padding:0 12px; border:0; border-radius:999px; background:var(--ehp-ui-text); color:var(--ehp-ui-surface); cursor:pointer; font-size:13px; font-weight:700; justify-self:end; }
      .ehp-color-picker { width:100%; min-width:0; max-width:100%; display:flex; flex-direction:column; gap:10px; align-items:stretch; box-sizing:border-box; }
      
      
      
      .ehp-color-square { --ehp-picker-hue:0; position:relative; width:100%; height:142px; border-radius:18px; overflow:hidden; background:hsl(var(--ehp-picker-hue), 100%, 50%); cursor:pointer; box-shadow:inset 0 0 0 1px rgba(0,0,0,.12), 0 8px 20px rgba(0,0,0,.12); box-sizing:border-box; flex:none; }
      .ehp-color-square::before { content:""; position:absolute; inset:0; background:linear-gradient(to right,#fff,rgba(255,255,255,0)); }
      .ehp-color-square::after { content:""; position:absolute; inset:0; background:linear-gradient(to bottom,rgba(0,0,0,0),#000); }
      .ehp-color-knob { position:absolute; z-index:2; width:14px; height:14px; border:2px solid white; border-radius:50%; box-shadow:0 0 0 1px rgba(0,0,0,.55), 0 2px 8px rgba(0,0,0,.45); transform:translate(-50%,-50%); pointer-events:none; }
      .ehp-hue-slider { flex:1; height:12px; border-radius:999px; outline:none; cursor:pointer; appearance:none; -webkit-appearance:none; background:linear-gradient(to right,#ff0000 0%,#ffff00 16.6%,#00ff00 33.3%,#00ffff 50%,#0000ff 66.6%,#ff00ff 83.3%,#ff0000 100%); box-shadow:inset 0 0 0 1px rgba(0,0,0,.16); }
      .ehp-hue-slider::-webkit-slider-runnable-track { height:12px; border-radius:999px; background:linear-gradient(to right,#ff0000 0%,#ffff00 16.6%,#00ff00 33.3%,#00ffff 50%,#0000ff 66.6%,#ff00ff 83.3%,#ff0000 100%); }
      .ehp-hue-slider::-webkit-slider-thumb { -webkit-appearance:none; appearance:none; width:18px; height:18px; margin-top:-3px; border-radius:50%; border:2px solid white; background:var(--ehp-ui-text); box-shadow:0 0 0 1px rgba(0,0,0,.35), 0 2px 8px rgba(0,0,0,.35); }
      .ehp-hue-slider::-moz-range-track { height:12px; border-radius:999px; background:linear-gradient(to right,#ff0000 0%,#ffff00 16.6%,#00ff00 33.3%,#00ffff 50%,#0000ff 66.6%,#ff00ff 83.3%,#ff0000 100%); }
      .ehp-hue-slider::-moz-range-thumb { width:18px; height:18px; border-radius:50%; border:2px solid white; background:var(--ehp-ui-text); box-shadow:0 0 0 1px rgba(0,0,0,.35), 0 2px 8px rgba(0,0,0,.35); }
      .ehp-progress-bar { position:fixed; top:0; left:0; height:4px; width:0%; z-index:2147483647; background:var(--ehp-ui-fill); transition:width 80ms linear; }
      .ehp-reader-thumbs { position:fixed; right:78px; bottom:20px; z-index:2147483647; width:154px; height:432px; max-height:calc(100vh - 96px); display:none; flex-direction:column; gap:10px; padding:12px 10px 12px 12px; box-sizing:border-box; border:1px solid var(--ehp-ui-stroke); border-radius:20px; background:var(--ehp-ui-surface); color:var(--ehp-ui-text); backdrop-filter:blur(14px); box-shadow:var(--ehp-control-shadow); overflow:hidden; pointer-events:auto; opacity:0; transition:opacity 180ms ease, transform 180ms ease; }
      .ehp-thumb-viewport { flex:1; min-height:0; overflow-y:auto; overflow-x:hidden; overscroll-behavior:contain; padding:0 8px 0 0; margin-right:-4px; box-sizing:border-box; scrollbar-width:thin; scrollbar-gutter:stable; }
      .ehp-thumb-list { display:flex; flex-direction:column; gap:8px; padding-right:0; box-sizing:border-box; }
      .ehp-thumb-viewport::-webkit-scrollbar { width:6px; }
      .ehp-thumb-viewport::-webkit-scrollbar-track { margin-top:14px; margin-bottom:10px; background:transparent; }
      .ehp-thumb-viewport::-webkit-scrollbar-thumb { border-radius:999px; background-color:color-mix(in srgb, var(--ehp-ui-text), transparent 60%); background-clip:content-box; border:1px solid transparent; }
      .ehp-thumb-item { position:relative; width:100%; aspect-ratio:4 / 3; height:auto; padding:0; border:1px solid color-mix(in srgb, var(--ehp-ui-text), transparent 78%); border-radius:12px; overflow:hidden; background:color-mix(in srgb, var(--ehp-ui-surface), var(--ehp-ui-text) 10%); cursor:pointer; box-sizing:border-box; opacity:.9; transition:border-color 150ms ease, opacity 150ms ease, transform 150ms ease, box-shadow 150ms ease; }
      .ehp-thumb-item:hover { opacity:1; transform:scale(1.02); border-color:rgba(48,56,67,.45); }
      .ehp-thumb-item.is-active { opacity:1; border-color:var(--ehp-ui-fill); box-shadow:0 0 0 2px rgba(255,255,255,.65); }
      .ehp-thumb-img { width:100%; height:100%; object-fit:contain; object-position:center; display:block; pointer-events:none; background:color-mix(in srgb, var(--ehp-ui-surface), var(--ehp-ui-text) 14%); }
      .ehp-thumb-ph { width:100%; height:100%; display:flex; align-items:center; justify-content:center; color:rgba(255,255,255,.72); font:700 13px/1 "Manrope","Inter","Segoe UI",system-ui,sans-serif; pointer-events:none; }
      .ehp-thumb-label { position:absolute; right:0; bottom:0; padding:1px 6px; border-radius:8px 0 0 0; background:rgba(0,0,0,.62); color:white; font:700 11px/1.4 "Manrope","Inter","Segoe UI",system-ui,sans-serif; pointer-events:none; }
      .ehp-page-indicator { position:static; z-index:auto; width:calc(100% - 2px); align-self:center; min-height:34px; box-sizing:border-box; padding:9px 12px; border-radius:14px; border:1px solid var(--ehp-ui-stroke); background:var(--ehp-reader-ui-input-bg, rgba(255,255,255,.72)); color:var(--ehp-ui-text); font-size:clamp(10px, 1.45vw, 13px); font-weight:700; line-height:1.1; text-align:center; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; box-shadow:none; pointer-events:none; user-select:none; }
      .ehp-reader-thumbs:hover { opacity:1; }
      .r-img { border-radius:12px; }
      #ehp-global-top {
        position:fixed; right:20px; bottom:144px; z-index:2147483645;
        width:50px; height:50px; border:1px solid var(--ehp-global-ui-stroke, var(--ehp-ui-stroke)); border-radius:50%;
        background:var(--ehp-global-ui-bg, var(--ehp-ui-surface)); color:var(--ehp-global-ui-text, var(--ehp-ui-text)); display:inline-flex; align-items:center; justify-content:center;
        cursor:pointer; box-shadow:var(--ehp-control-shadow); transition:transform 150ms ease, background-color 150ms ease, color 150ms ease;
      }
      #ehp-global-top:hover { transform:scale(1.05); }
      #ehp-global-top svg, .ehp-page-theme-launcher svg { display:block; fill:none; stroke:currentColor; stroke-width:2.2; stroke-linecap:round; stroke-linejoin:round; flex:none; filter:var(--ehp-icon-shadow); }
      #ehp-page-theme-controls {
        position:fixed; right:20px; bottom:82px; z-index:2147483645; display:flex; flex-direction:column; align-items:flex-end; gap:10px;
      }
      .ehp-reader-open #ehp-global-top, .ehp-reader-open #ehp-page-theme-controls { display:none; }
      .ehp-page-theme-launcher {
        width:50px; height:50px; border:1px solid var(--ehp-global-ui-stroke, var(--ehp-ui-stroke)); border-radius:50%;
        background:var(--ehp-global-ui-bg, var(--ehp-ui-surface)); color:var(--ehp-global-ui-text, var(--ehp-ui-text));
        display:inline-flex; align-items:center; justify-content:center; cursor:pointer; box-shadow:var(--ehp-control-shadow);
        transition:transform 150ms ease, background-color 150ms ease, color 150ms ease;
      }
      .ehp-page-theme-launcher:hover { transform:scale(1.05); }
      .ehp-page-theme-panel {
        position:absolute; right:62px; bottom:0; width:min(286px, calc(100vw - 108px)); padding:12px; border:1px solid var(--ehp-global-ui-stroke, var(--ehp-ui-stroke)); border-radius:24px;
        background:var(--ehp-global-ui-bg, var(--ehp-ui-surface)); color:var(--ehp-global-ui-text, var(--ehp-ui-text)); box-shadow:0 14px 34px rgba(0,0,0,.26), inset 0 1px 0 rgba(255,255,255,.25); backdrop-filter:blur(14px); box-sizing:border-box;
        opacity:0; transform:translate3d(12px,0,0) scale(.98); pointer-events:none; transition:opacity 180ms ease, transform 200ms ease;
      }
      #ehp-page-theme-controls.is-open .ehp-page-theme-panel { opacity:1; transform:translate3d(0,0,0) scale(1); pointer-events:auto; }
      
      
      .ehp-page-theme-panel .ehp-color-picker button { background:var(--ehp-global-ui-text, #303843); color:var(--ehp-global-ui-bg, #f7f8fa); }
      .ehp-page-theme-panel .ehp-hue-slider::-webkit-slider-thumb { background:var(--ehp-global-ui-text, #303843); }
      .ehp-page-theme-panel .ehp-hue-slider::-moz-range-thumb { background:var(--ehp-global-ui-text, #303843); }
            html.ehp-global-themed:not(.ehp-reader-open),
      html.ehp-global-themed:not(.ehp-reader-open) body {
        background-color:var(--ehp-page-theme-bg) !important;
        color:var(--ehp-page-theme-text) !important;
      }
      html.ehp-global-themed:not(.ehp-reader-open) body > div:not(#ehp-reader-overlay):not(#ehp-reader-ui):not(#ehp-reader-thumbs):not(#ehp-reader-launcher):not(#ehp-global-top):not(#ehp-page-theme-controls):not(#ehp-tag-system):not(#ehp-quick-fav-menu):not(#ehp-global-tooltip):not(#ehp-settings-center),
      html.ehp-global-themed:not(.ehp-reader-open) #nb,
      html.ehp-global-themed:not(.ehp-reader-open) #nw,
      html.ehp-global-themed:not(.ehp-reader-open) #gd1,
      html.ehp-global-themed:not(.ehp-reader-open) #gd2,
      html.ehp-global-themed:not(.ehp-reader-open) #gd3,
      html.ehp-global-themed:not(.ehp-reader-open) #gd4,
      html.ehp-global-themed:not(.ehp-reader-open) #gd5,
      html.ehp-global-themed:not(.ehp-reader-open) #gdd,
      html.ehp-global-themed:not(.ehp-reader-open) #gmid,
      html.ehp-global-themed:not(.ehp-reader-open) #gdt,
      html.ehp-global-themed:not(.ehp-reader-open) #gdf,
      html.ehp-global-themed:not(.ehp-reader-open) #taglist,
      html.ehp-global-themed:not(.ehp-reader-open) #tagmenu_act,
      html.ehp-global-themed:not(.ehp-reader-open) #tagmenu_new,
      html.ehp-global-themed:not(.ehp-reader-open) #rating_label,
      html.ehp-global-themed:not(.ehp-reader-open) .ido,
      html.ehp-global-themed:not(.ehp-reader-open) .gm,
      html.ehp-global-themed:not(.ehp-reader-open) .g2,
      html.ehp-global-themed:not(.ehp-reader-open) .g3,
      html.ehp-global-themed:not(.ehp-reader-open) .g4,
      html.ehp-global-themed:not(.ehp-reader-open) .g5,
      html.ehp-global-themed:not(.ehp-reader-open) .g6,
      html.ehp-global-themed:not(.ehp-reader-open) .g7,
      html.ehp-global-themed:not(.ehp-reader-open) .g8,
      html.ehp-global-themed:not(.ehp-reader-open) .g9,
      html.ehp-global-themed:not(.ehp-reader-open) .gl1t,
      html.ehp-global-themed:not(.ehp-reader-open) .gl3t,
      html.ehp-global-themed:not(.ehp-reader-open) .gtb,
      html.ehp-global-themed:not(.ehp-reader-open) .itg,
      html.ehp-global-themed:not(.ehp-reader-open) .ptt,
      html.ehp-global-themed:not(.ehp-reader-open) .ptb,
      html.ehp-global-themed:not(.ehp-reader-open) table:not(#ehp-reader-overlay table):not(#ehp-tag-system table),
      html.ehp-global-themed:not(.ehp-reader-open) td:not(#ehp-reader-overlay td):not(#ehp-tag-system td),
      html.ehp-global-themed:not(.ehp-reader-open) th:not(#ehp-reader-overlay th):not(#ehp-tag-system th) {
        background-color:color-mix(in srgb, var(--ehp-page-theme-bg), var(--ehp-page-theme-text) 4%) !important;
        color:var(--ehp-page-theme-text) !important;
        border-color:var(--ehp-border) !important;
      }
      html.ehp-global-themed:not(.ehp-reader-open) body :not(#ehp-reader-overlay):not(#ehp-reader-overlay *):not(#ehp-reader-ui):not(#ehp-reader-ui *):not(#ehp-reader-thumbs):not(#ehp-reader-thumbs *):not(#ehp-reader-launcher):not(#ehp-reader-launcher *):not(#ehp-global-top):not(#ehp-global-top *):not(#ehp-page-theme-controls):not(#ehp-page-theme-controls *):not(#ehp-tag-system):not(#ehp-tag-system *):not(#ehp-quick-fav-menu):not(#ehp-quick-fav-menu *):not(#ehp-global-tooltip):not(#ehp-settings-center):not(#ehp-settings-center *):not(img):not(svg):not(path) {
        color:var(--ehp-page-theme-text) !important;
        border-color:var(--ehp-border) !important;
      }
      html.ehp-global-themed:not(.ehp-reader-open) input:not(#ehp-tag-system input):not(#ehp-page-theme-controls input):not(#ehp-quick-fav-menu input):not(#ehp-settings-center input),
      html.ehp-global-themed:not(.ehp-reader-open) textarea:not(#ehp-tag-system textarea):not(#ehp-quick-fav-menu textarea):not(#ehp-settings-center textarea),
      html.ehp-global-themed:not(.ehp-reader-open) select:not(#ehp-tag-system select):not(#ehp-quick-fav-menu select):not(#ehp-settings-center select),
      html.ehp-global-themed:not(.ehp-reader-open) button:not(#ehp-tag-system button):not(#ehp-page-theme-controls button):not(#ehp-quick-fav-menu button):not(#ehp-settings-center button):not(#ehp-global-top):not(#ehp-reader-launcher) {
        background-color:var(--ehp-global-ui-input-bg, color-mix(in srgb, var(--ehp-page-theme-bg), var(--ehp-page-theme-text) 18%)) !important;
        color:var(--ehp-page-theme-text) !important;
        border-color:var(--ehp-border) !important;
      }
      html.ehp-global-themed:not(.ehp-reader-open) a:not(#ehp-tag-system a):not(#ehp-page-theme-controls a):not(#ehp-settings-center a) {
        color:var(--ehp-link) !important;
      }
      html.ehp-global-themed:not(.ehp-reader-open) a:not(#ehp-tag-system a):not(#ehp-page-theme-controls a):not(#ehp-settings-center a):hover {
        color:var(--ehp-link-hover) !important;
      }
      html.ehp-global-themed:not(.ehp-reader-open) {
        scrollbar-color:var(--ehp-border) var(--ehp-page-bg);
      }
      html.ehp-global-themed:not(.ehp-reader-open) ::-webkit-scrollbar { width:10px; height:10px; }
      html.ehp-global-themed:not(.ehp-reader-open) ::-webkit-scrollbar-track { background:var(--ehp-page-bg); }
      html.ehp-global-themed:not(.ehp-reader-open) ::-webkit-scrollbar-thumb { background:var(--ehp-border); border-radius:999px; }
      html.ehp-global-themed:not(.ehp-reader-open) .glname,
      html.ehp-global-themed:not(.ehp-reader-open) .glink,
      html.ehp-global-themed:not(.ehp-reader-open) h1,
      html.ehp-global-themed:not(.ehp-reader-open) h2,
      html.ehp-global-themed:not(.ehp-reader-open) h3 {
        border-color:var(--ehp-border) !important;
      }
      html.ehp-global-themed:not(.ehp-reader-open) .gt,
      html.ehp-global-themed:not(.ehp-reader-open) .gtl,
      html.ehp-global-themed:not(.ehp-reader-open) .gtw,
      html.ehp-global-themed:not(.ehp-reader-open) .tc,
      html.ehp-global-themed:not(.ehp-reader-open) .itg > tbody > tr,
      html.ehp-global-themed:not(.ehp-reader-open) .gtr0,
      html.ehp-global-themed:not(.ehp-reader-open) .gtr1 {
        background-color:var(--ehp-surface-strong) !important;
        color:var(--ehp-text) !important;
        border-color:var(--ehp-border) !important;
      }
      html.ehp-global-themed:not(.ehp-reader-open) input:focus,
      html.ehp-global-themed:not(.ehp-reader-open) textarea:focus,
      html.ehp-global-themed:not(.ehp-reader-open) select:focus,
      html.ehp-global-themed:not(.ehp-reader-open) button:focus,
      html.ehp-global-themed:not(.ehp-reader-open) a:focus {
        outline:0 !important;
        box-shadow:none !important;
      }
      html.ehp-global-themed:not(.ehp-reader-open) input::placeholder,
      html.ehp-global-themed:not(.ehp-reader-open) textarea::placeholder { color:var(--ehp-text-muted) !important; }
      html.ehp-global-themed:not(.ehp-reader-open) img,
      html.ehp-global-themed:not(.ehp-reader-open) #img,
      html.ehp-global-themed:not(.ehp-reader-open) .gdtm img,
      html.ehp-global-themed:not(.ehp-reader-open) .gdtl img,
      html.ehp-global-themed:not(.ehp-reader-open) .glthumb img,
      html.ehp-global-themed:not(.ehp-reader-open) .gl1t img,
      html.ehp-global-themed:not(.ehp-reader-open) .gl3t img {
        filter:none !important;
        background:transparent !important;
      }
      /* Always-on native borderless layer: keeps EH/EX layout and spacing while hiding native container strokes even when page color is reset. */
      html.ehp-native-borderless:not(.ehp-reader-open) :is(
        #nb, #nw,
        #gd1, #gd2, #gd3, #gd4, #gd5, #gdd, #gmid, #gdt, #gdf,
        #taglist, #tagmenu_act, #tagmenu_new, #rating_label,
        .ido, .gm, .g2, .g3, .g4, .g5, .g6, .g7, .g8, .g9,
        .itg, .gtr0, .gtr1, .gl1t, .gl1c, .gl2c, .gl3t, .gl3c, .gl4c,
        .glname, .glthumb, .glthumbdiv, .gdtm, .gdtl,
        .gtb, .gpc, .ptt, .ptb, .searchnav, .tc,
        table, tbody, thead, tfoot, tr, td, th
      ) {
        border-color:transparent !important;
        outline-color:transparent !important;
        box-shadow:none !important;
      }
      html.ehp-native-borderless:not(.ehp-reader-open) :is(.gl1t, .gl3t, .gl1c, .gl2c, .gl3c, .gl4c, .gdtm, .gdtl) img {
        border-color:transparent !important;
        outline-color:transparent !important;
        box-shadow:none !important;
      }

      /* Suite-wide shape system: no stroke outlines; surfaces use theme-based shadow/glow instead. */
      :where(#ehp-reader-launcher, #ehp-global-top, .ehp-page-theme-launcher, .ehp-tag-launcher, .ehp-panel, .ehp-btn, #ehp-reader-thumbs, .ehp-page-indicator, .ehp-page-theme-panel, .ehp-reader-guide, .ehp-guide-title-icon, .ehp-guide-section, .ehp-guide-key, .ehp-guide-symbol, #ehp-tag-system .ehp-tag-panel, #ehp-tag-system .ehp-tag-chip, #ehp-tag-system .ehp-tag-action, #ehp-tag-system .ehp-tag-fav-toggle, #ehp-tag-system .ehp-tag-ns-button, #ehp-quick-fav-menu, .ehp-qfav-cat, .ehp-qfav-inline-remove, .ehp-qfav-loading, .ehp-qfav-error, .ehp-global-tooltip) {
        border-color:transparent !important;
        outline-color:transparent !important;
      }
      :where(#ehp-reader-launcher, #ehp-global-top, .ehp-page-theme-launcher, .ehp-tag-launcher, .ehp-panel, .ehp-btn, #ehp-reader-thumbs, .ehp-page-theme-panel, .ehp-reader-guide, #ehp-tag-system .ehp-tag-panel, #ehp-quick-fav-menu, .ehp-global-tooltip) {
        box-shadow:var(--ehp-suite-depth, var(--ehp-control-shadow)) !important;
      }
      :where(.ehp-page-indicator, .ehp-guide-title-icon, .ehp-guide-section, .ehp-guide-key, .ehp-guide-symbol, #ehp-tag-system .ehp-tag-chip, #ehp-tag-system .ehp-tag-action, #ehp-tag-system .ehp-tag-fav-toggle, #ehp-tag-system .ehp-tag-ns-button, .ehp-qfav-cat, .ehp-qfav-inline-remove, .ehp-qfav-loading, .ehp-qfav-error) {
        box-shadow:var(--ehp-suite-depth-soft, var(--ehp-control-shadow)) !important;
      }
      :where(#ehp-reader-launcher, #ehp-global-top, .ehp-page-theme-launcher, .ehp-tag-launcher, .ehp-btn, .ehp-tag-action, .ehp-tag-fav-toggle, .ehp-tag-ns-button) svg {
        filter:var(--ehp-suite-icon-depth, var(--ehp-icon-shadow)) !important;
      }
      #ehp-reader-ui, .ehp-top-button, .ehp-menu-button, .ehp-guide-button, .ehp-action-stack, .ehp-stack-item {
        border-color:transparent !important;
        outline-color:transparent !important;
        box-shadow:none !important;
        filter:none !important;
      }
      :where(.ehp-btn, #ehp-reader-launcher, #ehp-global-top, .ehp-page-theme-launcher, .ehp-tag-launcher, .ehp-panel, #ehp-reader-thumbs, .ehp-page-indicator, .ehp-page-theme-panel, .ehp-reader-guide, #ehp-tag-system .ehp-tag-panel, #ehp-tag-system .ehp-tag-chip, #ehp-tag-system .ehp-tag-action, #ehp-tag-system .ehp-tag-fav-toggle, #ehp-tag-system .ehp-tag-ns-button, #ehp-quick-fav-menu, .ehp-qfav-cat, .ehp-qfav-inline-remove, .ehp-qfav-loading, .ehp-qfav-error, .ehp-global-tooltip) {
        border-color:transparent !important;
        outline-color:transparent !important;
      }

      /* Scrollbars stay inside panels as overlay-like slim scrollbars so panels keep symmetrical edges. */
      :where(#ehp-reader-overlay, #ehp-reader-thumbs, .ehp-thumb-viewport, .ehp-panel, .ehp-page-theme-panel, .ehp-reader-guide, #ehp-tag-system .ehp-tag-panel, #ehp-tag-system .ehp-tag-results, #ehp-tag-system .ehp-tag-saved-list, #ehp-quick-fav-menu, .ehp-qfav-list) {
        scrollbar-width:thin;
        scrollbar-color:color-mix(in srgb, var(--ehp-global-ui-text, var(--ehp-ui-text)), transparent 62%) transparent;
        scrollbar-gutter:auto;
      }
      :where(#ehp-reader-overlay, #ehp-reader-thumbs, .ehp-thumb-viewport, .ehp-panel, .ehp-page-theme-panel, .ehp-reader-guide, #ehp-tag-system .ehp-tag-panel, #ehp-tag-system .ehp-tag-results, #ehp-tag-system .ehp-tag-saved-list, #ehp-quick-fav-menu, .ehp-qfav-list)::-webkit-scrollbar { width:6px; height:6px; }
      :where(#ehp-reader-overlay, #ehp-reader-thumbs, .ehp-thumb-viewport, .ehp-panel, .ehp-page-theme-panel, .ehp-reader-guide, #ehp-tag-system .ehp-tag-panel, #ehp-tag-system .ehp-tag-results, #ehp-tag-system .ehp-tag-saved-list, #ehp-quick-fav-menu, .ehp-qfav-list)::-webkit-scrollbar-track { background:transparent; margin:12px; }
      :where(#ehp-reader-overlay, #ehp-reader-thumbs, .ehp-thumb-viewport, .ehp-panel, .ehp-page-theme-panel, .ehp-reader-guide, #ehp-tag-system .ehp-tag-panel, #ehp-tag-system .ehp-tag-results, #ehp-tag-system .ehp-tag-saved-list, #ehp-quick-fav-menu, .ehp-qfav-list)::-webkit-scrollbar-thumb { border:1px solid transparent; border-radius:999px; background-clip:content-box; background-color:color-mix(in srgb, var(--ehp-global-ui-text, var(--ehp-ui-text)), transparent 58%); }

      /* Web-only always-on native borderless enforcement.
         This stays active before page-color changes, after page-color changes, and after color reset.
         It targets EH/EX native structural borders only, not thumbnails/images/icons or this suite UI. */
      html.ehp-native-borderless:not(.ehp-reader-open) body :not(#ehp-reader-overlay):not(#ehp-reader-overlay *):not(#ehp-reader-ui):not(#ehp-reader-ui *):not(#ehp-reader-thumbs):not(#ehp-reader-thumbs *):not(#ehp-reader-launcher):not(#ehp-reader-launcher *):not(#ehp-global-top):not(#ehp-global-top *):not(#ehp-page-theme-controls):not(#ehp-page-theme-controls *):not(#ehp-tag-system):not(#ehp-tag-system *):not(#ehp-quick-fav-menu):not(#ehp-quick-fav-menu *):not(#ehp-global-tooltip):not(#ehp-settings-center):not(#ehp-settings-center *):not(img):not(svg):not(path):not(canvas):not(video):not([style*="background-image"]):not(.cn):not(.cs):not([class^="ir"]):not([class*=" ir"]):not([id^="rating"]),
      html.ehp-global-themed.ehp-native-borderless:not(.ehp-reader-open) body :not(#ehp-reader-overlay):not(#ehp-reader-overlay *):not(#ehp-reader-ui):not(#ehp-reader-ui *):not(#ehp-reader-thumbs):not(#ehp-reader-thumbs *):not(#ehp-reader-launcher):not(#ehp-reader-launcher *):not(#ehp-global-top):not(#ehp-global-top *):not(#ehp-page-theme-controls):not(#ehp-page-theme-controls *):not(#ehp-tag-system):not(#ehp-tag-system *):not(#ehp-quick-fav-menu):not(#ehp-quick-fav-menu *):not(#ehp-global-tooltip):not(#ehp-settings-center):not(#ehp-settings-center *):not(img):not(svg):not(path):not(canvas):not(video):not([style*="background-image"]):not(.cn):not(.cs):not([class^="ir"]):not([class*=" ir"]):not([id^="rating"]) {
        border-color:transparent !important;
        outline-color:transparent !important;
      }
      html.ehp-native-borderless:not(.ehp-reader-open) :is(table, thead, tbody, tfoot, tr, td, th, .gm, .ido, .itg, .gtr0, .gtr1, .gl1t, .gl1c, .gl2c, .gl3t, .gl3c, .gl4c, .glname, .glthumb, .glthumbdiv, .gdtm, .gdtl, #gdt, #gdf, #gdd, #gd1, #gd2, #gd3, #gd4, #gd5, #taglist, #rating_label, .gtb, .gpc, .ptt, .ptb, .searchnav, .tc) {
        border-color:transparent !important;
        outline-color:transparent !important;
      }

      /* Native top/bottom gallery pager polish. The .gtb wrapper should not draw its own rectangle; only its child text/pager remains functional. */
      html.ehp-native-borderless:not(.ehp-reader-open) .gtb {
        background:transparent !important;
        background-color:transparent !important;
        background-image:none !important;
        border-color:transparent !important;
        outline-color:transparent !important;
        box-shadow:none !important;
      }
      html.ehp-native-borderless:not(.ehp-reader-open) .gtb > .gpc {
        background:transparent !important;
        background-color:transparent !important;
        border-color:transparent !important;
        box-shadow:none !important;
      }

      /* Native top navigation: keep layout/spacing and links, but remove the visible rectangle. */
      html.ehp-native-borderless:not(.ehp-reader-open) #nb {
        background:transparent !important;
        background-color:transparent !important;
        background-image:none !important;
        border-color:transparent !important;
        outline-color:transparent !important;
        box-shadow:none !important;
        overflow:visible !important;
      }
      html.ehp-native-borderless:not(.ehp-reader-open) #nb > div,
      html.ehp-native-borderless:not(.ehp-reader-open) #nb > div > a {
        background:transparent !important;
        background-color:transparent !important;
        background-image:none !important;
        border-color:transparent !important;
        box-shadow:none !important;
      }

      html.ehp-native-borderless:not(.ehp-reader-open) #nb,
      html.ehp-native-borderless:not(.ehp-reader-open) #nb * {
        background:transparent !important;
        background-color:transparent !important;
        background-image:none !important;
        border-color:transparent !important;
        outline-color:transparent !important;
        box-shadow:none !important;
        text-shadow:none !important;
      }

      #ehp-reader-ui.ehp-ui-left { left:20px; right:auto; align-items:flex-start; }
      #ehp-reader-ui.ehp-ui-left .ehp-action-stack { align-items:flex-start; }
      #ehp-reader-ui.ehp-ui-left .ehp-stack-item { justify-content:flex-start; }
      #ehp-reader-ui.ehp-ui-left .ehp-panel { left:calc(100% + 10px); right:auto; transform:translate3d(-8px,-50%,0); }
      #ehp-reader-ui.ehp-ui-left .ehp-stack-item.is-open .ehp-panel { transform:translate3d(0,-50%,0); }
      html.ehp-reader-ui-left .ehp-reader-thumbs { left:78px; right:auto; }
      .ehp-menu-button { display:flex; align-items:center; justify-content:flex-end; gap:10px; }
      #ehp-reader-ui.ehp-ui-left .ehp-menu-button { flex-direction:row-reverse; justify-content:flex-start; }
      .ehp-guide-button { position:fixed; left:20px; bottom:20px; z-index:2147483647; display:flex; align-items:center; justify-content:center; pointer-events:auto; opacity:1; transform:translate3d(0,0,0) scale(1); transition:opacity 180ms ease, transform 180ms ease; }
      #ehp-reader-ui.ehp-ui-left .ehp-guide-button { left:auto; right:20px; }
      .ehp-guide-button.is-docked { opacity:0; }
      .ehp-guide-button:hover, .ehp-guide-button.is-docked:hover, .ehp-guide-button.is-open { opacity:1; transform:translate3d(0,0,0) scale(1); }
      .ehp-reader-guide { position:fixed; left:50%; top:50%; right:auto; bottom:auto; width:min(680px, calc(100vw - 56px)); max-height:calc(100vh - 40px); padding:20px; border:1px solid var(--ehp-ui-stroke); border-radius:24px; background:color-mix(in srgb, var(--ehp-ui-surface), transparent 7%); color:var(--ehp-ui-text); box-shadow:0 18px 44px rgba(0,0,0,.30), inset 0 1px 0 rgba(255,255,255,.24); backdrop-filter:blur(18px); box-sizing:border-box; overflow:auto; opacity:0; transform:translate3d(-50%,-48%,0) scale(.98); pointer-events:none; transition:opacity 180ms ease, transform 200ms ease; font-family:"Manrope","Inter","Segoe UI",system-ui,sans-serif; }
      #ehp-reader-ui.ehp-ui-left .ehp-reader-guide { left:50%; right:auto; }
      .ehp-reader-guide.is-open { opacity:1; transform:translate3d(-50%,-50%,0) scale(1); pointer-events:auto; }
      .ehp-reader-guide h2, .ehp-reader-guide h3 { margin:0 0 10px; color:var(--ehp-ui-text); line-height:1.2; }
      .ehp-reader-guide h2 { font-size:16px; }
      .ehp-reader-guide h3 { margin-top:16px; font-size:13px; }
      .ehp-reader-guide p, .ehp-reader-guide li { color:color-mix(in srgb, var(--ehp-ui-text), transparent 12%); font-size:12px; font-weight:700; line-height:1.45; }
      .ehp-reader-guide ul { margin:0 0 4px; padding-left:18px; }
      .ehp-reader-guide-row { display:flex; align-items:center; justify-content:space-between; gap:14px; margin-top:14px; padding-top:14px; border-top:1px solid var(--ehp-ui-stroke); font-size:12px; font-weight:800; }
      .ehp-reader-guide-close { display:block; width:min(280px, 100%); min-height:38px; margin:18px auto 0; padding:0 18px; border:0; border-radius:999px; background:var(--ehp-ui-text); color:var(--ehp-ui-surface); cursor:pointer; font-size:13px; font-weight:900; }
      .ehp-guide-switch { width:44px; height:24px; border:0; border-radius:999px; background:color-mix(in srgb, var(--ehp-ui-text), transparent 76%); position:relative; flex:none; cursor:pointer; transition:background-color 160ms ease; }
      .ehp-guide-switch::after { content:""; position:absolute; top:3px; left:3px; width:18px; height:18px; border-radius:50%; background:var(--ehp-ui-surface); box-shadow:0 2px 8px rgba(0,0,0,.22); transition:left 160ms ease; }
      .ehp-guide-switch.is-left { background:var(--ehp-ui-text); }
      .ehp-guide-switch.is-left::after { left:23px; }
      #ehp-tag-system { position:fixed; right:20px; bottom:20px; z-index:2147483645; display:flex; flex-direction:column; align-items:flex-end; gap:10px; font-family:"Manrope","Inter","Segoe UI",system-ui,sans-serif; line-height:1; user-select:none; }
      #ehp-tag-system.ehp-gallery-tags { right:82px; }
      .ehp-reader-open #ehp-tag-system { display:none; }
      .ehp-tag-launcher { width:50px; height:50px; border:1px solid var(--ehp-global-ui-stroke, var(--ehp-ui-stroke)); border-radius:50%; background:var(--ehp-global-ui-bg, var(--ehp-ui-surface)); color:var(--ehp-global-ui-text, var(--ehp-ui-text)); display:inline-flex; align-items:center; justify-content:center; cursor:pointer; box-shadow:var(--ehp-control-shadow); transition:transform 150ms ease, background-color 150ms ease, color 150ms ease; }
      .ehp-tag-launcher:hover { transform:scale(1.05); }
      .ehp-tag-launcher svg { display:block; fill:none; stroke:currentColor; stroke-width:2; stroke-linecap:round; stroke-linejoin:round; flex:none; filter:var(--ehp-icon-shadow); }
      .ehp-tag-panel { position:absolute; right:62px; bottom:0; width:min(720px, calc(100vw - 124px), 112vh); aspect-ratio:4 / 3; min-width:min(420px, calc(100vw - 124px)); min-height:min(420px, calc(100vh - 96px)); max-width:calc(100vw - 124px); max-height:88vh; display:grid; grid-template-rows:auto 1fr auto; overflow:hidden; border:1px solid rgba(40,40,40,.12); border-radius:28px; background:#f1eee7; color:#222; box-shadow:0 24px 60px rgba(0,0,0,.18), inset 0 1px 0 rgba(255,255,255,.75); backdrop-filter:blur(16px); box-sizing:border-box; opacity:0; transform:translate3d(12px,0,0) scale(.98); pointer-events:none; transition:opacity 180ms ease, transform 200ms ease; font-family:"Manrope","Inter","Segoe UI",system-ui,sans-serif; }
      .ehp-tag-panel.is-resizing { transition:none; }
      #ehp-tag-system.is-open .ehp-tag-panel { opacity:1; transform:translate3d(0,0,0) scale(1); pointer-events:auto; }
      .ehp-tag-display { position:relative; min-height:0; overflow:auto; padding:0 28px 18px; box-sizing:border-box; scrollbar-width:thin; }
      .ehp-tag-fav-head { z-index:2; min-width:0; min-height:80px; padding:22px 28px 14px; display:flex; align-items:center; gap:18px; box-sizing:border-box; opacity:1; transition:opacity 150ms ease; }
      .ehp-tag-fav-toggle { width:44px; height:44px; padding:0; border:1px solid rgba(0,0,0,.13); border-radius:999px; background:rgba(255,255,255,.34); color:#222; display:inline-grid; place-items:center; cursor:pointer; pointer-events:auto; box-shadow:0 4px 12px rgba(0,0,0,.08), inset 0 1px 0 rgba(255,255,255,.7); flex:none; box-sizing:border-box; line-height:1; }
      .ehp-tag-fav-toggle svg { width:21px; height:21px; display:block; fill:none; stroke:currentColor; stroke-width:1.8; stroke-linecap:round; stroke-linejoin:round; flex:none; }
      .ehp-tag-namespace-rail { min-width:0; height:44px; max-width:0; display:inline-flex; align-items:center; gap:4px; overflow:hidden; padding:4px 0; border:1px solid transparent; border-radius:999px; background:rgba(255,255,255,.28); opacity:0; box-shadow:inset 0 1px 2px rgba(0,0,0,.06), 0 2px 8px rgba(0,0,0,.04); box-sizing:border-box; transition:max-width 220ms ease, opacity 160ms ease, padding 160ms ease, border-color 160ms ease; }
      #ehp-tag-system.is-fav-rail-open .ehp-tag-namespace-rail { max-width:calc(100% - 62px); opacity:1; padding:4px; border-color:rgba(0,0,0,.12); }
      .ehp-tag-ns-button { width:54px; height:34px; padding:0; border:0; border-radius:999px; background:transparent; color:#222; cursor:pointer; display:inline-flex; align-items:center; justify-content:center; flex:none; }
      .ehp-tag-ns-button.is-active { background:rgba(255,255,255,.46); box-shadow:inset 0 1px 2px rgba(255,255,255,.8), inset 0 -1px 3px rgba(0,0,0,.08); }
      .ehp-tag-ns-button svg { width:21px; height:21px; display:block; fill:none; stroke:currentColor; stroke-width:1.8; stroke-linecap:round; stroke-linejoin:round; }
      .ehp-tag-grid { display:flex; flex-wrap:wrap; align-content:flex-start; align-items:flex-start; gap:14px 16px; min-height:100%; padding-top:8px; box-sizing:border-box; }
      .ehp-tag-chip { min-width:150px; max-width:280px; height:46px; display:inline-flex; align-items:center; justify-content:space-between; gap:12px; padding:5px 8px; border:1px solid rgba(0,0,0,.11); border-radius:999px; background:rgba(255,255,255,.28); color:#222; cursor:pointer; font-size:13px; font-weight:650; line-height:1; letter-spacing:0; box-sizing:border-box; box-shadow:0 3px 10px rgba(0,0,0,.045), inset 0 1px 0 rgba(255,255,255,.66); transition:transform 120ms ease, background 120ms ease, box-shadow 120ms ease; }
      .ehp-tag-chip:hover { transform:translateY(-1px); background:rgba(255,255,255,.42); box-shadow:0 5px 14px rgba(0,0,0,.07), inset 0 1px 0 rgba(255,255,255,.72); }
      .ehp-tag-chip.is-active { background:rgba(255,255,255,.36); }
      .ehp-tag-chip.is-live { border-color:rgba(0,0,0,.23); }
      .ehp-tag-chip.is-candidate { border-style:dashed; opacity:.88; }
      .ehp-tag-chip-main { min-width:0; height:34px; display:inline-flex; align-items:center; gap:8px; overflow:hidden; flex:1; }
      .ehp-tag-ns-icon { width:34px; height:34px; border-radius:13px; display:inline-flex; align-items:center; justify-content:center; background:rgba(255,255,255,.36); border:1px solid rgba(0,0,0,.075); box-shadow:inset 0 1px 0 rgba(255,255,255,.7), 0 1px 4px rgba(0,0,0,.045); flex:0 0 auto; color:#222; }
      .ehp-tag-ns-icon svg { width:19px; height:19px; display:block; fill:none; stroke:currentColor; stroke-width:1.75; stroke-linecap:round; stroke-linejoin:round; }
      .ehp-tag-name { flex:1; min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; text-align:left; line-height:1.1; }
      .ehp-tag-action { width:28px; height:28px; padding:0; border:0; border-radius:999px; display:inline-flex; align-items:center; justify-content:center; background:rgba(0,0,0,.055); color:#222; cursor:pointer; line-height:1; flex:0 0 auto; }
      .ehp-tag-action svg { width:15px; height:15px; display:block; fill:none; stroke:currentColor; stroke-width:2; stroke-linecap:round; stroke-linejoin:round; pointer-events:none; }
      .ehp-tag-empty-state { width:100%; min-height:120px; display:flex; align-items:center; justify-content:center; padding:18px; color:rgba(34,34,34,.52); font-size:13px; font-weight:750; text-align:center; box-sizing:border-box; }
      .ehp-tag-search-dock { min-height:76px; padding:16px 20px 18px; border-top:1px solid rgba(0,0,0,.10); background:rgba(255,255,255,.16); box-sizing:border-box; }
      .ehp-tag-search-wrap { width:100%; height:48px; display:flex; align-items:center; gap:14px; padding:0 18px; border:1px solid rgba(0,0,0,.16); border-radius:18px; background:rgba(255,255,255,.26); box-shadow:inset 0 1px 0 rgba(255,255,255,.56), 0 2px 8px rgba(0,0,0,.035); box-sizing:border-box; }
      .ehp-tag-search-wrap:focus-within { border-color:rgba(0,0,0,.28); background:rgba(255,255,255,.36); }
      .ehp-tag-search-wrap svg { width:22px; height:22px; display:block; fill:none; stroke:currentColor; stroke-width:2; stroke-linecap:round; stroke-linejoin:round; color:#222; opacity:.78; flex:none; }
      .ehp-tag-search-input { width:100%; min-width:0; height:100%; border:0; outline:0; background:transparent; color:#222; font:700 15px/48px "Manrope","Inter","Segoe UI",system-ui,sans-serif; }
      .ehp-tag-search-input::placeholder { color:rgba(34,34,34,.42); font-weight:700; }
      .ehp-tag-tooltip { position:absolute; z-index:8; max-width:min(340px, calc(100% - 24px)); padding:8px 11px; border:1px solid rgba(0,0,0,.12); border-radius:18px; background:rgba(245,242,234,.96); color:#222; box-shadow:0 10px 28px rgba(0,0,0,.16), inset 0 1px 0 rgba(255,255,255,.75); font:750 12px/1.35 "Manrope","Inter","Segoe UI",system-ui,sans-serif; white-space:pre-line; overflow-wrap:anywhere; opacity:0; transform:translateY(3px) scale(.985); pointer-events:none; transition:opacity 120ms ease, transform 120ms ease; box-sizing:border-box; }
      .ehp-tag-tooltip.is-visible { opacity:1; transform:translateY(0) scale(1); }
      #ehp-tag-system { --ehp-tag-ui-surface:var(--ehp-global-ui-bg, #f1eee7); --ehp-tag-ui-text:var(--ehp-global-ui-text, #222); --ehp-tag-ui-soft:var(--ehp-global-ui-input-bg, rgba(255,255,255,.28)); --ehp-tag-ui-stroke:var(--ehp-global-ui-stroke, rgba(0,0,0,.13)); }
      #ehp-tag-system .ehp-tag-panel { background:color-mix(in srgb, var(--ehp-tag-ui-surface), transparent 7%); color:var(--ehp-tag-ui-text); border-color:var(--ehp-tag-ui-stroke); }
      #ehp-tag-system .ehp-tag-fav-toggle, #ehp-tag-system .ehp-tag-ns-button, #ehp-tag-system .ehp-tag-chip, #ehp-tag-system .ehp-tag-search-wrap, #ehp-tag-system .ehp-tag-ns-icon, #ehp-tag-system .ehp-tag-action { color:var(--ehp-tag-ui-text); border-color:var(--ehp-tag-ui-stroke); }
      #ehp-tag-system .ehp-tag-search-input { color:var(--ehp-tag-ui-text); }
      #ehp-tag-system .ehp-tag-search-input::placeholder { color:color-mix(in srgb, var(--ehp-tag-ui-text), transparent 55%); }
      #ehp-tag-system .ehp-tag-search-dock, #ehp-tag-system .ehp-tag-search-wrap, #ehp-tag-system .ehp-tag-chip, #ehp-tag-system .ehp-tag-fav-toggle, #ehp-tag-system .ehp-tag-namespace-rail, #ehp-tag-system .ehp-tag-ns-icon, #ehp-tag-system .ehp-tag-action, #ehp-tag-system .ehp-tag-ns-button.is-active { background:color-mix(in srgb, var(--ehp-tag-ui-surface), var(--ehp-tag-ui-text) 10%); }
      #ehp-tag-system .ehp-tag-tooltip { background:color-mix(in srgb, var(--ehp-tag-ui-surface), transparent 4%); color:var(--ehp-tag-ui-text); border-color:var(--ehp-tag-ui-stroke); border-radius:18px; }
      .ehp-global-tooltip.ehp-tag-tooltip { position:fixed; z-index:2147483647; max-width:min(340px, calc(100vw - 24px)); background:color-mix(in srgb, var(--ehp-global-ui-bg, var(--ehp-ui-surface)), transparent 4%); color:var(--ehp-global-ui-text, var(--ehp-ui-text)); border-color:var(--ehp-global-ui-stroke, var(--ehp-ui-stroke)); border-radius:18px; box-shadow:0 10px 28px rgba(0,0,0,.16), inset 0 1px 0 rgba(255,255,255,.35); }
      .ehp-tag-fav-toggle { padding:0; box-sizing:border-box; display:inline-grid; place-items:center; line-height:1; }
      .ehp-tag-fav-toggle svg { margin:auto; transform:translate(0, 0); }
      .ehp-page-theme-panel .ehp-color-picker, .ehp-panel .ehp-color-picker { width:100%; min-width:0; max-width:100%; }
      .ehp-page-theme-panel .ehp-hue-row, .ehp-panel .ehp-hue-row { display:grid; grid-template-columns:minmax(0, 1fr) auto; align-items:center; gap:8px; width:100%; }
      .ehp-page-theme-panel .ehp-hue-slider, .ehp-panel .ehp-hue-slider { width:100%; min-width:0; }
      .ehp-page-theme-panel .ehp-color-picker button, .ehp-panel .ehp-color-picker button, .ehp-chip, .ehp-jump button, .ehp-slider-row button { display:inline-flex; align-items:center; justify-content:center; line-height:1; text-align:center; }


      :where(.ehp-btn, #ehp-reader-launcher, #ehp-global-top, .ehp-page-theme-launcher, .ehp-chip, .ehp-tag-launcher, .ehp-tag-chip, .ehp-tag-action, .ehp-tag-fav-toggle, .ehp-tag-ns-button, .ehp-qfav-cat, .ehp-qfav-remove, .ehp-qfav-original, .ehp-reader-guide-close):active { transform:translateY(1px) scale(.97); filter:brightness(.98); }
      .ehp-tag-action { width:30px; height:30px; border:1px solid color-mix(in srgb, var(--ehp-tag-ui-text, #222), transparent 82%); border-radius:999px; background:color-mix(in srgb, var(--ehp-tag-ui-surface, #f1eee7), var(--ehp-tag-ui-text, #222) 12%); box-shadow:inset 0 1px 0 rgba(255,255,255,.55), 0 2px 7px rgba(0,0,0,.06); transition:transform 120ms ease, background 120ms ease, box-shadow 120ms ease, border-color 120ms ease; }
      .ehp-tag-action:hover { transform:translateY(-1px) scale(1.03); background:color-mix(in srgb, var(--ehp-tag-ui-surface, #f1eee7), var(--ehp-tag-ui-text, #222) 17%); border-color:color-mix(in srgb, var(--ehp-tag-ui-text, #222), transparent 72%); box-shadow:inset 0 1px 0 rgba(255,255,255,.62), 0 4px 10px rgba(0,0,0,.08); }
      .ehp-tag-action svg { width:15px; height:15px; margin:auto; }

      .ehp-guide-title-row { display:grid; grid-template-columns:42px minmax(0, 1fr); align-items:center; gap:12px; margin-bottom:14px; }
      .ehp-guide-title-icon { width:42px; height:42px; border-radius:16px; display:grid; place-items:center; background:color-mix(in srgb, var(--ehp-ui-surface), var(--ehp-ui-text) 12%); border:1px solid var(--ehp-ui-stroke); box-shadow:inset 0 1px 0 rgba(255,255,255,.34); }
      .ehp-guide-title-icon svg, .ehp-guide-symbol svg, .ehp-guide-key svg { width:21px; height:21px; display:block; fill:none; stroke:currentColor; stroke-width:2.05; stroke-linecap:round; stroke-linejoin:round; filter:var(--ehp-icon-shadow); }
      .ehp-guide-manrope-icon { display:inline-flex; align-items:center; justify-content:center; width:100%; height:100%; font-family:"Manrope","Inter","Segoe UI",system-ui,sans-serif; font-weight:950; line-height:1; letter-spacing:-.03em; color:currentColor; filter:var(--ehp-icon-shadow); }
      .ehp-guide-manrope-icon.is-esc { font-size:13px; letter-spacing:-.06em; }
      .ehp-guide-manrope-icon.is-zero { font-size:18px; letter-spacing:-.05em; }
      .ehp-reader-guide .ehp-guide-title-row p { margin:3px 0 0; font-size:12px; }
      .ehp-guide-section { padding:12px; border:1px solid var(--ehp-ui-stroke); border-radius:20px; background:color-mix(in srgb, var(--ehp-ui-surface), var(--ehp-ui-text) 6%); box-shadow:inset 0 1px 0 rgba(255,255,255,.20); }
      .ehp-guide-section + .ehp-guide-section { margin-top:10px; }
      .ehp-guide-list { display:flex; flex-direction:column; gap:8px; }
      @media (min-width:620px) {
        .ehp-reader-guide .ehp-guide-list { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:8px 10px; }
        .ehp-reader-guide .ehp-guide-section:last-of-type .ehp-guide-list { display:flex; }
      }
      .ehp-guide-item { display:grid; grid-template-columns:46px minmax(0, 1fr); align-items:center; gap:10px; min-height:36px; }
      .ehp-guide-key, .ehp-guide-symbol { width:46px; min-height:36px; border-radius:12px; display:inline-grid; place-items:center; background:color-mix(in srgb, var(--ehp-ui-surface), var(--ehp-ui-text) 12%); color:var(--ehp-ui-text); border:1px solid color-mix(in srgb, var(--ehp-ui-text), transparent 80%); font-size:12px; font-weight:950; line-height:1; box-shadow:inset 0 1px 0 rgba(255,255,255,.25), 0 2px 8px rgba(0,0,0,.05); box-sizing:border-box; }
      .ehp-guide-item span:last-child { color:color-mix(in srgb, var(--ehp-ui-text), transparent 10%); font-size:12px; font-weight:720; line-height:1.35; }
      .ehp-guide-mode-grid { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:8px; }
      .ehp-guide-mode-grid div { min-width:0; padding:10px; border-radius:16px; background:color-mix(in srgb, var(--ehp-ui-surface), var(--ehp-ui-text) 8%); border:1px solid color-mix(in srgb, var(--ehp-ui-text), transparent 84%); box-sizing:border-box; }
      .ehp-guide-mode-grid strong, .ehp-guide-mode-grid span { display:block; }
      .ehp-guide-mode-grid strong { margin-bottom:4px; font-size:12px; font-weight:950; }
      .ehp-guide-mode-grid span { font-size:11px; font-weight:700; line-height:1.3; color:color-mix(in srgb, var(--ehp-ui-text), transparent 18%); }

      .ehp-quick-fav-trigger { cursor:pointer !important; }
      .ehp-quick-fav-trigger.ehp-qfav-working { filter:brightness(1.08); }
      .ehp-quick-fav-trigger.ehp-qfav-updated { outline:0 !important; box-shadow:none !important; }
      #ehp-quick-fav-menu {
        position:fixed; z-index:2147483646; width:min(244px, calc(100vw - 20px)); padding:10px 11px;
        border:1px solid transparent; border-radius:18px;
        background:color-mix(in srgb, var(--ehp-global-ui-bg, #f5f1e8), transparent 4%); color:var(--ehp-global-ui-text, #222);
        box-shadow:0 14px 34px rgba(0,0,0,.24), inset 0 1px 0 rgba(255,255,255,.28); backdrop-filter:blur(18px); box-sizing:border-box; user-select:none;
        animation:ehpQfavIn 120ms ease both; font-family:"Manrope","Inter","Segoe UI",system-ui,sans-serif; overflow:visible;
      }
      @keyframes ehpQfavIn { from{opacity:0; transform:translateY(4px) scale(.985)} to{opacity:1; transform:translateY(0) scale(1)} }
      .ehp-qfav-list {
        display:flex; flex-direction:column; gap:5px; max-height:min(360px, calc(100vh - 92px));
        overflow-y:auto; overflow-x:hidden; overscroll-behavior:contain; scrollbar-width:thin;
        padding:3px 10px 5px; margin:0; box-sizing:border-box;
      }
      .ehp-qfav-cat, .ehp-qfav-remove, .ehp-qfav-original {
        min-width:0; height:32px; padding:0 9px; border:1px solid var(--ehp-global-ui-stroke, rgba(0,0,0,.13)); border-radius:12px;
        background:color-mix(in srgb, var(--ehp-global-ui-bg, #f5f1e8), var(--ehp-global-ui-text, #222) 8%); color:inherit;
        display:inline-flex; align-items:center; justify-content:flex-start; gap:8px; cursor:pointer; font-size:12px; font-weight:830; line-height:1; text-align:left;
        box-shadow:inset 0 1px 0 rgba(255,255,255,.30), 0 2px 7px rgba(0,0,0,.04); transition:transform 120ms ease, background 120ms ease, opacity 120ms ease, border-color 120ms ease;
        box-sizing:border-box;
      }
      .ehp-qfav-cat:hover, .ehp-qfav-remove:hover, .ehp-qfav-original:hover { transform:translateY(-1px); background:color-mix(in srgb, var(--ehp-global-ui-bg, #f5f1e8), var(--ehp-global-ui-text, #222) 14%); border-color:color-mix(in srgb, var(--ehp-global-ui-text, #222), transparent 72%); }
      .ehp-qfav-name { min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
      .ehp-qfav-native-icon { --ehp-fav-color:#b28a45; width:21px; height:21px; display:inline-grid; place-items:center; flex:0 0 auto; background:transparent; border:0; box-shadow:none; border-radius:0; overflow:visible; }
      .ehp-qfav-native-icon::before { content:none; }
      .ehp-qfav-native-icon > div.i, .ehp-qfav-native-icon > span.i, .ehp-qfav-native-icon > img { width:21px; height:21px; max-width:21px; max-height:21px; display:block; filter:none !important; }
      .ehp-qfav-fallback-i { border-radius:5px; background:linear-gradient(180deg, color-mix(in srgb, var(--ehp-fav-color), white 14%), color-mix(in srgb, var(--ehp-fav-color), black 5%)); border:1px solid color-mix(in srgb, var(--ehp-fav-color), black 28%); box-shadow:inset 0 1px 0 rgba(255,255,255,.38), 0 1px 2px rgba(0,0,0,.20); position:relative; box-sizing:border-box; }
      .ehp-qfav-fallback-i::before { content:"★"; position:absolute; inset:0; display:grid; place-items:center; color:rgba(255,255,255,.86); font-size:13px; line-height:1; transform:translateY(-.5px); text-shadow:0 1px 0 rgba(0,0,0,.34); }
      .ehp-qfav-native-0,.ehp-qfav-fallback-i-0{--ehp-fav-color:#c8ad5a}.ehp-qfav-native-1,.ehp-qfav-fallback-i-1{--ehp-fav-color:#c96f70}.ehp-qfav-native-2,.ehp-qfav-fallback-i-2{--ehp-fav-color:#83aa67}.ehp-qfav-native-3,.ehp-qfav-fallback-i-3{--ehp-fav-color:#619dc8}.ehp-qfav-native-4,.ehp-qfav-fallback-i-4{--ehp-fav-color:#a783c8}.ehp-qfav-native-5,.ehp-qfav-fallback-i-5{--ehp-fav-color:#c9814e}.ehp-qfav-native-6,.ehp-qfav-fallback-i-6{--ehp-fav-color:#5ea9a4}.ehp-qfav-native-7,.ehp-qfav-fallback-i-7{--ehp-fav-color:#bc6793}.ehp-qfav-native-8,.ehp-qfav-fallback-i-8{--ehp-fav-color:#8994a4}.ehp-qfav-native-9,.ehp-qfav-fallback-i-9{--ehp-fav-color:#a89761}
      .ehp-qfav-original, .ehp-qfav-remove { height:30px; justify-content:center; padding:0 9px; border-radius:999px; font-size:11px; font-weight:880; }
      #ehp-quick-fav-menu[data-status]:not([data-status=""])::after { content:none !important; display:none !important; }
      #ehp-quick-fav-menu.is-working .ehp-qfav-cat, #ehp-quick-fav-menu.is-working .ehp-qfav-remove, #ehp-quick-fav-menu.is-working .ehp-qfav-original { pointer-events:none; opacity:.55; }
      .ehp-qfav-loading, .ehp-qfav-error { min-height:64px; display:flex; align-items:center; justify-content:center; padding:10px; border-radius:14px; background:color-mix(in srgb, var(--ehp-global-ui-bg, #f5f1e8), var(--ehp-global-ui-text, #222) 7%); font-size:12px; font-weight:850; text-align:center; line-height:1.35; box-sizing:border-box; }
      /* Native-aware global theme: recolor surfaces/text, but preserve site imagery, category colors, rating/fav icons, and original geometry. */
      html.ehp-global-themed:not(.ehp-reader-open) select,
      html.ehp-global-themed:not(.ehp-reader-open) option,
      html.ehp-global-themed:not(.ehp-reader-open) optgroup {
        background:var(--ehp-input-bg) !important;
        color:var(--ehp-text) !important;
        border-color:var(--ehp-border) !important;
      }
      html.ehp-global-themed:not(.ehp-reader-open) input:focus,
      html.ehp-global-themed:not(.ehp-reader-open) textarea:focus,
      html.ehp-global-themed:not(.ehp-reader-open) select:focus,
      html.ehp-global-themed:not(.ehp-reader-open) button:focus,
      html.ehp-global-themed:not(.ehp-reader-open) a:focus,
      #ehp-tag-system input:focus,
      #ehp-tag-system button:focus {
        outline:0 !important;
        box-shadow:none !important;
      }
      html.ehp-global-themed:not(.ehp-reader-open) #ehp-global-tooltip,
      html.ehp-global-themed:not(.ehp-reader-open) #ehp-quick-fav-menu,
      html.ehp-global-themed:not(.ehp-reader-open) #ehp-page-theme-controls .ehp-page-theme-panel,
      html.ehp-global-themed:not(.ehp-reader-open) #ehp-tag-system .ehp-tag-panel,
      html.ehp-global-themed:not(.ehp-reader-open) #ehp-global-top,
      html.ehp-global-themed:not(.ehp-reader-open) #ehp-page-theme-controls .ehp-page-theme-launcher,
      html.ehp-global-themed:not(.ehp-reader-open) #ehp-tag-system .ehp-tag-launcher {
        box-shadow:var(--ehp-theme-depth, var(--ehp-shadow)) !important;
      }
      .ehp-global-tooltip.ehp-tag-tooltip { box-shadow:var(--ehp-theme-depth, 0 10px 28px rgba(0,0,0,.16)) !important; }
      .ehp-tag-action svg { width:22px; height:22px; stroke-width:2.2; stroke-linecap:round; stroke-linejoin:round; }
      html.ehp-global-themed:not(.ehp-reader-open) #rating_image,
      html.ehp-global-themed:not(.ehp-reader-open) [id^="rating_image"],
      html.ehp-global-themed:not(.ehp-reader-open) .ir,
      html.ehp-global-themed:not(.ehp-reader-open) [class^="ir"],
      html.ehp-global-themed:not(.ehp-reader-open) [class*=" ir"],
      html.ehp-global-themed:not(.ehp-reader-open) .cn,
      html.ehp-global-themed:not(.ehp-reader-open) .cs,
      html.ehp-global-themed:not(.ehp-reader-open) [class^="ct"],
      html.ehp-global-themed:not(.ehp-reader-open) [class*=" ct"],
      html.ehp-global-themed:not(.ehp-reader-open) [style*="background-image"] {
        filter:none !important;
      }
      .ehp-qfav-cat { position:relative; }
      .ehp-qfav-cat.is-current { padding-right:78px; }
      .ehp-qfav-inline-remove {
        position:absolute; right:5px; top:50%; transform:translateY(-50%); height:24px; min-width:64px; padding:0 10px;
        display:inline-flex; align-items:center; justify-content:center; border-radius:999px;
        background:color-mix(in srgb, var(--ehp-global-ui-bg, #f5f1e8), var(--ehp-global-ui-text, #222) 16%);
        color:var(--ehp-global-ui-text, #222); font:900 10.5px/1 "Manrope","Inter","Segoe UI",system-ui,sans-serif;
        box-shadow:inset 0 1px 0 rgba(255,255,255,.24); border:0; cursor:pointer; box-sizing:border-box;
      }
      .ehp-qfav-inline-remove:hover { background:color-mix(in srgb, var(--ehp-global-ui-bg, #f5f1e8), var(--ehp-global-ui-text, #222) 22%); }

      .ehp-tag-gate { position:absolute; inset:0; z-index:5; padding:16px 18px; display:flex; flex-direction:column; align-items:center; justify-content:flex-start; gap:10px; overflow:auto; background:color-mix(in srgb, var(--ehp-global-ui-bg, #f5f1e8), transparent 8%); color:var(--ehp-global-ui-text, #803c38); backdrop-filter:blur(18px); box-sizing:border-box; text-align:left; }
      #ehp-tag-system.is-gate-accepted .ehp-tag-gate { display:none; }
      .ehp-tag-gate h2 { width:100%; margin:0 0 4px; font-size:13px; line-height:1.2; text-align:center; text-decoration:underline; color:inherit; }
      .ehp-tag-gate p { width:100%; margin:0; font-size:12px; font-weight:500; line-height:1.35; color:inherit; }
      .ehp-tag-gate a { color:inherit; text-decoration:underline; }
      .ehp-tag-gate strong { font-weight:900; }
      .ehp-tag-gate button { min-height:34px; margin-top:2px; padding:0 18px; border:0; border-radius:999px; background:transparent; color:inherit; cursor:pointer; font-size:12px; font-weight:900; }
      @media (max-width:700px) {
        #ehp-reader-launcher, #ehp-reader-ui, #ehp-tag-system { right:12px; bottom:12px; }
        #ehp-reader-ui.ehp-ui-left { left:12px; right:auto; }
        #ehp-tag-system.ehp-gallery-tags { right:74px; }
        #ehp-global-top { right:12px; bottom:136px; }
        #ehp-page-theme-controls { right:12px; bottom:74px; }
        .ehp-guide-button { left:12px; bottom:12px; }
        #ehp-reader-ui.ehp-ui-left .ehp-guide-button { left:auto; right:12px; }
        .ehp-reader-thumbs { right:70px; bottom:12px; width:140px; height:392px; max-height:calc(100vh - 84px); }
        html.ehp-reader-ui-left .ehp-reader-thumbs { left:70px; right:auto; }
        .ehp-reader-guide, #ehp-reader-ui.ehp-ui-left .ehp-reader-guide { left:50%; right:auto; top:50%; bottom:auto; width:calc(100vw - 28px); max-height:calc(100vh - 24px); }
        .ehp-tag-panel { right:62px; bottom:0; width:calc(100vw - 86px); height:min(520px, calc(100vh - 84px)); min-width:0; }
        .ehp-stack-item.is-open .ehp-panel { max-width:calc(100vw - 88px); }
        .ehp-stack-item.is-open .ehp-panel.ehp-panel-vertical { min-width:min(270px, calc(100vw - 102px)); }
        .ehp-chip { min-width:58px; }
        .ehp-stage-manga .ehp-reader-image { max-width:calc((100vw - 36px) / 2); }
      }

      /* Stability patch: page recolor must never act as a script-UI stroke toggle.
         Native page recolor owns native surfaces only; script UI always uses transparent strokes + depth. */
      :root,
      html.ehp-global-themed,
      html.ehp-reader-open {
        --ehp-ui-stroke: transparent !important;
        --ehp-reader-ui-stroke: transparent !important;
        --ehp-global-ui-stroke: transparent !important;
      }

      html :is(
        #ehp-reader-launcher, #ehp-reader-ui, #ehp-reader-ui *, #ehp-reader-thumbs, #ehp-reader-thumbs *,
        #ehp-page-theme-controls, #ehp-page-theme-controls *, #ehp-global-top,
        #ehp-tag-system, #ehp-tag-system *, #ehp-quick-fav-menu, #ehp-quick-fav-menu *,
        #ehp-global-tooltip, .ehp-reader-guide, .ehp-reader-guide *,
        .ehp-btn, .ehp-panel, .ehp-chip, .ehp-guide-key, .ehp-guide-symbol,
        .ehp-guide-section, .ehp-page-indicator, .ehp-thumb-item
      ) {
        border-color: transparent !important;
        outline-color: transparent !important;
        -webkit-text-stroke: 0 transparent !important;
      }

      html :is(#ehp-reader-ui, .ehp-top-button, .ehp-menu-button, .ehp-guide-button, .ehp-action-stack, .ehp-stack-item) {
        box-shadow: none !important;
        filter: none !important;
      }

      html :is(
        #ehp-reader-launcher, #ehp-global-top, .ehp-page-theme-launcher, .ehp-tag-launcher,
        .ehp-btn, .ehp-panel, #ehp-reader-thumbs, .ehp-page-theme-panel,
        .ehp-reader-guide, #ehp-tag-system .ehp-tag-panel, #ehp-quick-fav-menu,
        #ehp-global-tooltip
      ) {
        box-shadow: var(--ehp-suite-depth, var(--ehp-control-shadow, 0 12px 30px rgba(0,0,0,.18))) !important;
      }

      html :is(
        .ehp-page-indicator, .ehp-thumb-item, .ehp-guide-title-icon, .ehp-guide-section,
        .ehp-guide-key, .ehp-guide-symbol, #ehp-tag-system .ehp-tag-chip,
        #ehp-tag-system .ehp-tag-action, #ehp-tag-system .ehp-tag-fav-toggle,
        #ehp-tag-system .ehp-tag-ns-button, .ehp-qfav-cat, .ehp-qfav-inline-remove,
        .ehp-qfav-loading, .ehp-qfav-error
      ) {
        box-shadow: var(--ehp-suite-depth-soft, 0 7px 18px rgba(0,0,0,.12)) !important;
      }

      html.ehp-reader-open #ehp-reader-overlay {
        --ehp-global-ui-bg: var(--ehp-ui-surface);
        --ehp-global-ui-text: var(--ehp-ui-text);
        --ehp-global-ui-input-bg: rgba(255, 255, 255, 0.72);
        --ehp-global-ui-stroke: transparent;
        --ehp-ui-stroke: transparent;
      }

      /* Static script UI color guard: page color and reader color must not recolor script windows/buttons/tooltips. */
      :where(#ehp-reader-launcher, #ehp-reader-ui, #ehp-reader-ui *, #ehp-reader-thumbs, #ehp-reader-thumbs *, #ehp-page-theme-controls, #ehp-page-theme-controls *, #ehp-global-top, #ehp-tag-system, #ehp-tag-system *, #ehp-quick-fav-menu, #ehp-quick-fav-menu *, #ehp-global-tooltip, #ehp-settings-center, #ehp-settings-center *, .ehp-settings-panel, .ehp-settings-panel *) {
        --ehp-ui-surface: rgba(245, 241, 232, 0.96) !important;
        --ehp-ui-text: #2d3137 !important;
        --ehp-ui-fill: #303843 !important;
        --ehp-ui-stroke: transparent !important;
        --ehp-reader-ui-surface: rgba(245, 241, 232, 0.96) !important;
        --ehp-reader-ui-text: #2d3137 !important;
        --ehp-reader-ui-soft: color-mix(in srgb, #f5f1e8, #2d3137 12%) !important;
        --ehp-reader-ui-input-bg: rgba(255, 255, 255, 0.72) !important;
        --ehp-reader-ui-stroke: transparent !important;
        --ehp-global-ui-bg: rgba(245, 241, 232, 0.96) !important;
        --ehp-global-ui-text: #2d3137 !important;
        --ehp-global-ui-soft: rgba(245, 241, 232, 0.96) !important;
        --ehp-global-ui-input-bg: rgba(255, 255, 255, 0.72) !important;
        --ehp-global-ui-stroke: transparent !important;
        --ehp-suite-depth: 0 12px 30px color-mix(in srgb, #000000, transparent 78%) !important;
        --ehp-suite-depth-soft: 0 7px 18px color-mix(in srgb, #000000, transparent 86%) !important;
        --ehp-suite-icon-depth: drop-shadow(0 1px 0 rgba(255,255,255,.34)) drop-shadow(0 2px 3px rgba(0,0,0,.36)) !important;
        --ehp-control-shadow: var(--ehp-suite-depth) !important;
        --ehp-icon-shadow: var(--ehp-suite-icon-depth) !important;
        --ehp-theme-depth: var(--ehp-suite-depth) !important;
      }

      #ehp-global-tooltip.ehp-global-tooltip {
        z-index: 2147483647 !important;
        pointer-events: none !important;
      }
    `;
    document.head.appendChild(style);
    applyEhpThemeColor();
    applyEhpGap();
    applyEhpZoom();
  }

  /************************************************************
   * LIST / THUMBNAIL INFINITE LOADER
   * Runs on list/search pages and on /g/ gallery thumbnail pages.
   ************************************************************/
  function initSimpleInfiniteContentLoader(options) {
    options = options || {};

    const CONFIG = {
        enableListInfiniteScroll: true,      // For homepage/search/favorites/list pages
        enableGalleryThumbnails: true,       // For /g/ gallery pages
        maxListPages: 0,                     // 0 = unlimited
        maxGalleryPages: 0,                  // 0 = unlimited
        requestIntervalMs: 600,              // Be gentle. Do not hammer the site.
        requestTimeoutMs: 12000,
        observerRootMargin: '300px 0px'
    };


    Object.assign(CONFIG, options);
    const $ = (selector, root = document) => root.querySelector(selector);
    const $$ = (selector, root = document) => Array.from(root.querySelectorAll(selector));
    const $id = id => document.getElementById(id);
    const $el = tag => document.createElement(tag);

    function throttle(fn, wait) {
        let lastTime = 0;
        let timeout = null;

        return function (...args) {
            const now = Date.now();
            const remaining = wait - (now - lastTime);

            if (remaining <= 0) {
                clearTimeout(timeout);
                timeout = null;
                lastTime = now;
                fn.apply(this, args);
            } else if (!timeout) {
                timeout = setTimeout(() => {
                    lastTime = Date.now();
                    timeout = null;
                    fn.apply(this, args);
                }, remaining);
            }
        };
    }

    const queuedFetch = (() => {
        let lastRequestTime = 0;
        let chain = Promise.resolve();

        return function (url) {
            const task = chain.catch(() => {}).then(async () => {
                const wait = CONFIG.requestIntervalMs - (performance.now() - lastRequestTime);

                if (wait > 0) {
                    await new Promise(resolve => setTimeout(resolve, wait));
                }

                lastRequestTime = performance.now();

                const controller = new AbortController();
                const timeout = setTimeout(() => controller.abort(), CONFIG.requestTimeoutMs);

                try {
                    return await fetch(url, {
                        credentials: 'include',
                        signal: controller.signal
                    });
                } finally {
                    clearTimeout(timeout);
                }
            });

            chain = task.then(() => {}, () => {});
            return task;
        };
    })();

    /************************************************************
     * PAGE DETECTION
     ************************************************************/

    const pageInfo = {
        isGalleryPage: location.pathname.startsWith('/g/'),

        // E-Hentai list/search pages usually expose display mode through this select.
        // Values may include: m, p, l, e, t.
        listDisplayMode: $('.searchnav select[onchange*="dm_"]')?.value || null
    };

    const isSupportedPage = pageInfo.isGalleryPage || !!pageInfo.listDisplayMode;

    if (!isSupportedPage) {
        return;
    }

    const enabledForThisPage = pageInfo.isGalleryPage
        ? CONFIG.enableGalleryThumbnails
        : CONFIG.enableListInfiniteScroll;

    if (!enabledForThisPage) {
        return;
    }

    /************************************************************
     * STATE
     ************************************************************/

    const nextPage = {
        isLoading: false,
        isError: false,
        pageLink: null,
        loadedCount: 1
    };

    let scrollObserver = null;

    const throttledLoadNextPage = throttle(loadNextPage, 600);

    /************************************************************
     * CSS
     ************************************************************/

    function injectInfiniteScrollCSS() {
        if ($id('ehinf-style')) return;

        const style = $el('style');
        style.id = 'ehinf-style';

        style.textContent = `
            .ehinf-loading-container {
                box-sizing: border-box;
                color: inherit;
                min-height: 36px;
            }

            div.ehinf-loading-container {
                display: flex;
                align-items: center;
                justify-content: center;
                grid-column: 1 / -1;
                width: 100%;
                border-radius: 4px;
                border: 1px solid color-mix(in srgb, currentColor, transparent 80%);
                margin: 8px 0;
            }

            tr.ehinf-loading-container td {
                text-align: center;
                color: inherit;
                vertical-align: middle;
                border: 1px solid color-mix(in srgb, currentColor, transparent 80%);
                padding: 8px;
            }

            div.ehinf-loading-container:has(.ehinf-loading-link),
            tr.ehinf-loading-container:has(.ehinf-loading-link) td {
                cursor: pointer;
                border-color: color-mix(in srgb, currentColor, transparent 60%);
            }

            div.ehinf-loading-container:has(.ehinf-loading-link):hover,
            tr.ehinf-loading-container:has(.ehinf-loading-link):hover td,
            div.ehinf-loading-container:has(.ehinf-loading-spinner),
            tr.ehinf-loading-container:has(.ehinf-loading-spinner) td {
                border-color: color-mix(in srgb, currentColor, transparent 40%);
                background: rgba(128, 128, 128, 0.08);
            }

            .ehinf-loading-spinner {
                display: inline-block;
                width: 16px;
                height: 16px;
                border: 4px solid rgba(120, 120, 120, 0.36);
                border-radius: 50%;
                border-top-color: currentColor;
                animation: ehinf-loading-spin 0.6s linear infinite;
                vertical-align: middle;
            }

            @keyframes ehinf-loading-spin {
                to { transform: rotate(360deg); }
            }

            .ehinf-loading-status-text {
                font-size: 18px;
                display: inline-block;
                color: inherit;
                user-select: none;
                margin-left: 10px;
                vertical-align: middle;
                line-height: 24px;
            }

            .ehinf-loading-status-text.ehinf-loading-end {
                opacity: 0.6;
            }
        `;

        document.head.appendChild(style);
    }

    /************************************************************
     * FIND TARGET CONTAINER
     ************************************************************/

    function getAppendParent() {
        if (pageInfo.listDisplayMode === 't') {
            return document.getElementsByClassName('itg gld')[0] || $('.itg.gld');
        }

        if (pageInfo.listDisplayMode) {
            return $('.itg > tbody');
        }

        if (pageInfo.isGalleryPage) {
            return $id('gdt');
        }

        return null;
    }

    function isTableParent(parent) {
        return parent?.tagName === 'TBODY';
    }

    /************************************************************
     * NEXT-PAGE LINK DETECTION
     ************************************************************/

    function updateNextPageLink(doc = document) {
        if (pageInfo.listDisplayMode) {
            nextPage.pageLink = $('#dnext', doc)?.href || null;

            if (nextPage.pageLink) {
                const topNext = $id('unext');
                const bottomNext = $id('dnext');

                if (topNext) topNext.href = nextPage.pageLink;
                if (bottomNext) bottomNext.href = nextPage.pageLink;
            }

            return;
        }

        if (pageInfo.isGalleryPage) {
            nextPage.pageLink =
                $('.ptb tr:first-child td:last-child a', doc)?.href ||
                $('.ptt tr:first-child td:last-child a', doc)?.href ||
                null;

            if (nextPage.pageLink) {
                const topNext = $('.ptt tr:first-child td:last-child a');
                const bottomNext = $('.ptb tr:first-child td:last-child a');

                if (topNext) topNext.href = nextPage.pageLink;
                if (bottomNext) bottomNext.href = nextPage.pageLink;
            }
        }
    }

    /************************************************************
     * LOADING INDICATOR
     ************************************************************/

    function updateLoadingStatus(status) {
        const parent = getAppendParent();
        if (!parent) return;

        const isTable = isTableParent(parent);
        const indicatorId = 'ehinf-next-indicator';

        let container = $id(indicatorId);

        if (!container) {
            container = $el(isTable ? 'tr' : 'div');
            container.id = indicatorId;
            container.className = 'ehinf-loading-container';

            if (isTable) {
                container.innerHTML = '<td colspan="100%"></td>';
            }

            parent.appendChild(container);
        }

        const shouldShow =
            (pageInfo.listDisplayMode && CONFIG.enableListInfiniteScroll) ||
            (pageInfo.isGalleryPage && CONFIG.enableGalleryThumbnails);

        if (!shouldShow) {
            container.style.display = 'none';
            return;
        }

        container.style.display = '';

        const htmlByStatus = {
            idle: '<span class="ehinf-loading-status-text ehinf-loading-link">--- Load more ---</span>',
            loading: '<div class="ehinf-loading-spinner"></div><span class="ehinf-loading-status-text">Loading...</span>',
            end: '<span class="ehinf-loading-status-text ehinf-loading-end">--- No more content ---</span>',
            error: '<span class="ehinf-loading-status-text ehinf-loading-link">--- Load failed · Retry ---</span>'
        };

        const target = isTable ? container.firstElementChild : container;
        target.innerHTML = htmlByStatus[status] || htmlByStatus.idle;

        nextPage.isError = status === 'error';

        container.onclick = (status === 'idle' || status === 'error')
            ? () => {
                nextPage.isError = false;
                throttledLoadNextPage();
            }
            : null;

        if (parent.lastElementChild !== container) {
            parent.appendChild(container);
        }
    }

    /************************************************************
     * CONTENT EXTRACTION
     ************************************************************/

    function getContentNodesFromFetchedPage(fetchedDoc) {
        if (pageInfo.listDisplayMode === 't') {
            // Thumbnail mode on list/search pages.
            return $$('.gl1t', fetchedDoc);
        }

        if (pageInfo.listDisplayMode) {
            // Normal list/table modes. These rows include gallery titles.
            return $$('.itg > tbody > tr', fetchedDoc);
        }

        if (pageInfo.isGalleryPage) {
            // Gallery page thumbnails.
            return $$('#gdt > a', fetchedDoc);
        }

        return [];
    }

    function buildFragmentFromFetchedNodes(contentNodes) {
        const fragment = document.createDocumentFragment();

        contentNodes.forEach((item, index) => {
            const shouldKeep =
                pageInfo.listDisplayMode === 't' ||
                pageInfo.listDisplayMode === 'e' ||
                pageInfo.isGalleryPage ||
                index > 0; // Skip table header row in normal list mode.

            if (shouldKeep) {
                fragment.appendChild(item);
            }
        });

        return fragment;
    }

    /************************************************************
     * LOAD NEXT PAGE
     ************************************************************/

    async function loadNextPage() {
        if (nextPage.isLoading || !nextPage.pageLink) return;

        nextPage.isLoading = true;
        updateLoadingStatus('loading');

        try {
            console.log('[EHINF] Loading next page:', nextPage.pageLink);

            const response = await queuedFetch(nextPage.pageLink);

            if (!response.ok) {
                throw new Error(`HTTP ${response.status}`);
            }

            const html = await response.text();
            const fetchedDoc = new DOMParser().parseFromString(html, 'text/html');

            const contentNodes = getContentNodesFromFetchedPage(fetchedDoc);

            if (contentNodes.length > 0) {
                const fragment = buildFragmentFromFetchedNodes(contentNodes);
                const indicator = $id('ehinf-next-indicator');

                if (indicator) {
                    indicator.before(fragment);
                }

                nextPage.loadedCount += 1;

                document.dispatchEvent(new CustomEvent('ehinf:page-loaded', {
                    detail: {
                        loadedCount: nextPage.loadedCount,
                        sourceUrl: nextPage.pageLink,
                        pageType: pageInfo.isGalleryPage ? 'gallery' : 'list'
                    }
                }));

                console.log('[EHINF] New content appended.');
            } else {
                console.log('[EHINF] No content nodes found on fetched page.');
            }

            updateNextPageLink(fetchedDoc);

            if (nextPage.pageLink) {
                updateLoadingStatus('idle');
            } else {
                updateLoadingStatus('end');
            }
        } catch (error) {
            console.error('[EHINF] Load failed:', error);
            updateLoadingStatus('error');
        } finally {
            nextPage.isLoading = false;

            const indicator = $id('ehinf-next-indicator');

            if (indicator && scrollObserver && !nextPage.isError && nextPage.pageLink) {
                scrollObserver.unobserve(indicator);
                scrollObserver.observe(indicator);
            }
        }
    }

    /************************************************************
     * INTERSECTION OBSERVER
     ************************************************************/

    function setupScrollObserver() {
        const indicator = $id('ehinf-next-indicator');

        if (!indicator) return;

        if (scrollObserver) {
            scrollObserver.disconnect();
        }

        scrollObserver = new IntersectionObserver(([entry]) => {
            const enabled = pageInfo.isGalleryPage
                ? CONFIG.enableGalleryThumbnails
                : CONFIG.enableListInfiniteScroll;

            const maxPages = pageInfo.isGalleryPage
                ? CONFIG.maxGalleryPages
                : CONFIG.maxListPages;

            if (!entry.isIntersecting) return;
            if (!enabled) return;
            if (nextPage.isLoading) return;
            if (nextPage.isError) return;

            if (!nextPage.pageLink) {
                updateLoadingStatus('end');
                scrollObserver.unobserve(indicator);
                return;
            }

            if (maxPages !== 0 && nextPage.loadedCount >= maxPages) {
                console.log('[EHINF] Max page limit reached:', nextPage.loadedCount, '>=', maxPages);
                updateLoadingStatus('idle');
                return;
            }

            throttledLoadNextPage();
        }, {
            root: null,
            rootMargin: CONFIG.observerRootMargin
        });

        scrollObserver.observe(indicator);
    }

    /************************************************************
     * INIT
     ************************************************************/

    function initInfiniteLoader() {
        injectInfiniteScrollCSS();
        updateNextPageLink(document);

        if (!nextPage.pageLink) {
            updateLoadingStatus('end');
            return;
        }

        updateLoadingStatus('idle');
        setupScrollObserver();

        console.log('[EHINF] Infinite loader ready:', {
            pageType: pageInfo.isGalleryPage ? 'gallery thumbnails' : 'list titles',
            firstNextPage: nextPage.pageLink
        });
    }

    initInfiniteLoader();


  }

  /************************************************************
   * EXTRA FEATURE: WIKI-BACKED TAG SYSTEM
   * Shared search/favorite/gallery tagging panel.
   ************************************************************/
  const EHP_TAG_FAVORITES_KEY = "ehpTagFavorites";
  const EHP_OLD_QUICK_TAGS_KEY = "ehpQuickSearchTags";
  const EHP_TAG_CACHE_KEY = "ehpWikiTagCache";
  const EHP_TAG_CACHE_VERSION = 4;
  const EHP_TAG_CACHE_TTL = 7 * 24 * 60 * 60 * 1000;
  const EHP_FETISH_LISTING_URL = "https://ehwiki.org/wiki/Fetish_Listing";
  const EHP_GALLERY_TAG_NOTICE_KEY = "ehpGalleryTagNoticeAccepted";
  const EHP_TAG_PANEL_SIZE_KEY = "ehpTagPanelSize";
  const EHP_LIVE_TAG_LOOKUP_MIN_LENGTH = 3;
  const EHP_LIVE_TAG_LOOKUP_MAX_GALLERIES = 5;
  const EHP_LIVE_TAG_LOOKUP_MAX_RESULTS = 80;
  const EHP_LIVE_LOOKUP_NAMESPACES = ["artist", "group", "parody", "character", "cosplayer", "female", "male", "mixed", "other", "language", "location"];
  const ehpLiveTagLookupCache = new Map();

  const EHP_NAMESPACE_DEFS = [
    { key: "artist", icon: "nsArtist", aliases: ["a"] },
    { key: "character", icon: "nsCharacter", aliases: ["c", "char"] },
    { key: "cosplayer", icon: "nsCosplayer", aliases: ["cos"] },
    { key: "female", icon: "nsFemale", aliases: ["f"] },
    { key: "group", icon: "nsGroup", aliases: ["g", "circle"] },
    { key: "language", icon: "nsLanguage", aliases: ["l", "lang"] },
    { key: "location", icon: "nsLocation", aliases: ["loc"] },
    { key: "male", icon: "nsMale", aliases: ["m"] },
    { key: "mixed", icon: "nsMixed", aliases: ["x"] },
    { key: "other", icon: "nsOther", aliases: ["o", "misc"] },
    { key: "parody", icon: "nsParody", aliases: ["p", "series"] },
    { key: "reclass", icon: "nsReclass", aliases: ["r"] },
    { key: "temp", icon: "nsOther", aliases: ["tmp"] }
  ];

  const EHP_NAMESPACE_ALIAS = new Map();
  EHP_NAMESPACE_DEFS.forEach((item) => {
    EHP_NAMESPACE_ALIAS.set(item.key, item.key);
    item.aliases.forEach((alias) => EHP_NAMESPACE_ALIAS.set(alias, item.key));
  });

  let ehpTagCatalog = null;
  let ehpTagCatalogPromise = null;

  function normalizeEhpNamespace(namespace) {
    const key = String(namespace || "").trim().toLowerCase();
    return EHP_NAMESPACE_ALIAS.get(key) || "other";
  }

  function getEhpNamespaceMeta(namespace) {
    const key = normalizeEhpNamespace(namespace);
    return EHP_NAMESPACE_DEFS.find((item) => item.key === key) || EHP_NAMESPACE_DEFS.find((item) => item.key === "other");
  }

  function getEhpNamespaceIcon(namespace) {
    const meta = getEhpNamespaceMeta(namespace);
    return EHP_ICONS[meta.icon] || EHP_ICONS.nsOther;
  }

  function normalizeEhpTagName(name) {
    return String(name || "")
      .replace(/[\u200e\u200f\u202a-\u202e]/g, "")
      .replace(/\s+/g, " ")
      .trim();
  }

  function getEhpDisplayTagName(entry) {
    const parsed = parseEhpTagEntry(entry);
    if (!parsed) return "";
    let clean = String(parsed.name || "").trim();
    clean = clean.replace(/\$$/, "").trim();
    if ((clean.startsWith('"') && clean.endsWith('"')) || (clean.startsWith("'") && clean.endsWith("'"))) {
      clean = clean.slice(1, -1).trim();
    }
    clean = clean.replace(/\$$/, "").trim();
    return clean || parsed.name;
  }

  function makeEhpTagSearchKey(value) {
    return normalizeEhpTagName(value)
      .toLowerCase()
      .replace(/[_:]+/g, " ")
      .replace(/[“”]/g, '"')
      .replace(/[‘’]/g, "'")
      .replace(/["'`$]+/g, " ")
      .replace(/\s+/g, " ")
      .trim();
  }

  function getEhpTagSearchText(namespace, name) {
    const value = `${namespace}:${name}`;
    return [
      `${namespace} ${name}`.toLowerCase(),
      value.toLowerCase(),
      makeEhpTagSearchKey(value),
      makeEhpTagSearchKey(name)
    ].join(" ");
  }

  function getEhpCanonicalTagName(name) {
    let clean = normalizeEhpTagName(name);
    clean = clean.replace(/\$$/, "").trim();
    if ((clean.startsWith('"') && clean.endsWith('"')) || (clean.startsWith("'") && clean.endsWith("'"))) {
      clean = clean.slice(1, -1).trim();
    }
    clean = clean.replace(/\$$/, "").trim();
    return clean || normalizeEhpTagName(name);
  }

  function ensureEhpExactSearchName(name) {
    let clean = normalizeEhpTagName(name);
    if (!clean) return "";

    const quote = clean[0];
    if (quote === '"' || quote === "'") {
      let inner = clean.slice(1);
      if (inner.endsWith(quote)) inner = inner.slice(0, -1);
      inner = normalizeEhpTagName(inner).replace(/\$$/, "").trim();
      return inner ? `${quote}${inner}$${quote}` : "";
    }

    clean = clean.replace(/\$$/, "").trim();
    return clean ? `${clean}$` : "";
  }

  function formatEhpTagQuery(namespace, name) {
    const exact = ensureEhpExactSearchName(name);
    if (!exact) return "";
    if (/^["']/.test(exact)) return `${namespace}:${exact}`;
    if (/\s/.test(exact)) return `${namespace}:"${exact.replace(/\$$/, "").replace(/"/g, '\"')}$"`;
    return `${namespace}:${exact}`;
  }

  function parseEhpTagEntry(value, fallbackNamespace = "other") {
    if (value && typeof value === "object") {
      const namespace = normalizeEhpNamespace(value.namespace || fallbackNamespace);
      const name = normalizeEhpTagName(value.name || value.tag || value.label || "");
      if (!name) return null;
      const query = formatEhpTagQuery(namespace, name);
      const canonicalName = getEhpCanonicalTagName(name);
      return {
        namespace,
        name,
        value: query,
        query,
        galleryValue: `${namespace}:${canonicalName}`,
        key: `${namespace}:${canonicalName}`.toLowerCase(),
        search: getEhpTagSearchText(namespace, name),
        source: value.source || "catalog"
      };
    }

    const raw = String(value || "").trim();
    if (!raw) return null;
    const colonIndex = raw.indexOf(":");
    const namespace = colonIndex > 0 ? normalizeEhpNamespace(raw.slice(0, colonIndex)) : normalizeEhpNamespace(fallbackNamespace);
    const name = normalizeEhpTagName(colonIndex > 0 ? raw.slice(colonIndex + 1) : raw);
    if (!name) return null;
    const query = formatEhpTagQuery(namespace, name);
    const canonicalName = getEhpCanonicalTagName(name);
    return {
      namespace,
      name,
      value: query,
      query,
      galleryValue: `${namespace}:${canonicalName}`,
      key: `${namespace}:${canonicalName}`.toLowerCase(),
      search: getEhpTagSearchText(namespace, name),
      source: "manual"
    };
  }

  function uniqEhpTagEntries(entries) {
    const seen = new Set();
    const clean = [];
    entries.forEach((entry) => {
      const parsed = parseEhpTagEntry(entry);
      if (!parsed) return;
      const key = parsed.key || parsed.value.toLowerCase();
      if (seen.has(key)) return;
      seen.add(key);
      clean.push(parsed);
    });
    return clean;
  }

  function getEhpFavoriteTags() {
    const raw = _GM_getValue(EHP_TAG_FAVORITES_KEY, null);
    if (raw) {
      if (Array.isArray(raw)) return uniqEhpTagEntries(raw);
      if (typeof raw === "string") {
        try {
          const parsed = JSON.parse(raw);
          if (Array.isArray(parsed)) return uniqEhpTagEntries(parsed);
        } catch (_) {
          return uniqEhpTagEntries(raw.split("\n"));
        }
      }
    }

    const legacy = _GM_getValue(EHP_OLD_QUICK_TAGS_KEY, []);
    const migrated = Array.isArray(legacy) ? uniqEhpTagEntries(legacy) : [];
    if (migrated.length) setEhpFavoriteTags(migrated);
    return migrated;
  }

  function setEhpFavoriteTags(tags) {
    const clean = uniqEhpTagEntries(tags);
    _GM_setValue(EHP_TAG_FAVORITES_KEY, clean.map((tag) => ({ namespace: tag.namespace, name: tag.name, query: tag.query })));
    return clean;
  }

  function isEhpFavoriteTag(entry) {
    const parsed = parseEhpTagEntry(entry);
    if (!parsed) return false;
    return getEhpFavoriteTags().some((tag) => (tag.key || tag.value.toLowerCase()) === (parsed.key || parsed.value.toLowerCase()));
  }

  function addEhpFavoriteTag(entry) {
    const parsed = parseEhpTagEntry(entry);
    if (!parsed) return getEhpFavoriteTags();
    return setEhpFavoriteTags([...getEhpFavoriteTags(), parsed]);
  }

  function removeEhpFavoriteTag(entry) {
    const parsed = parseEhpTagEntry(entry);
    if (!parsed) return getEhpFavoriteTags();
    return setEhpFavoriteTags(getEhpFavoriteTags().filter((tag) => (tag.key || tag.value.toLowerCase()) !== (parsed.key || parsed.value.toLowerCase())));
  }

  function findEhpSearchInput() {
    const selectors = [
      'input[name="f_search"]',
      'input#f_search',
      'form input[type="text"][name*="search"]',
      '.searchtext input[type="text"]'
    ];
    for (const selector of selectors) {
      const input = document.querySelector(selector);
      if (input) return input;
    }
    return null;
  }

  function escapeEhpRegExp(value) {
    return String(value).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  }

  function normalizeEhpSearchText(value) {
    return String(value || "").trim().replace(/\s+/g, " ");
  }

  function getEhpSearchTokenVariants(entry) {
    const parsed = parseEhpTagEntry(entry);
    if (!parsed) return [];
    const query = parsed.query || parsed.value;
    const variants = [query, parsed.value];
    if (parsed.galleryValue) variants.push(parsed.galleryValue);
    const seen = new Set();
    return variants
      .map(normalizeEhpSearchText)
      .filter(Boolean)
      .filter((item) => {
        const key = item.toLowerCase();
        if (seen.has(key)) return false;
        seen.add(key);
        return true;
      });
  }

  function isEhpTagInSearch(tag, value) {
    return getEhpSearchTokenVariants(tag).some((token) => {
      const re = new RegExp(`(?:^|\\s)${escapeEhpRegExp(token)}(?=\\s|$)`, "i");
      return re.test(normalizeEhpSearchText(value));
    });
  }

  function removeEhpTagFromSearch(tag, value) {
    let next = String(value || "");
    getEhpSearchTokenVariants(tag).forEach((token) => {
      const re = new RegExp(`(?:^|\\s)${escapeEhpRegExp(token)}(?=\\s|$)`, "gi");
      next = next.replace(re, " ");
    });
    return normalizeEhpSearchText(next);
  }

  function toggleEhpTagInSearch(entry) {
    const input = findEhpSearchInput();
    const parsed = parseEhpTagEntry(entry);
    if (!input || !parsed) return false;

    const current = normalizeEhpSearchText(input.value);
    const query = parsed.query || parsed.value;
    const next = isEhpTagInSearch(parsed, current)
      ? removeEhpTagFromSearch(parsed, current)
      : (current ? `${current} ${query}` : query);

    input.value = next;
    input.dispatchEvent(new Event("input", { bubbles: true }));
    input.dispatchEvent(new Event("change", { bubbles: true }));
    return true;
  }

  function addEhpTagToGallery(entry) {
    const parsed = parseEhpTagEntry(entry);
    if (!parsed) return false;
    const field = document.querySelector("#newtagfield, input[name='tagname_new'], input[name='newtag']");
    if (!field) return false;

    field.value = parsed.galleryValue || parsed.value;
    field.dispatchEvent(new Event("input", { bubbles: true }));
    field.dispatchEvent(new Event("change", { bubbles: true }));

    const button = document.querySelector("#newtagbutton") || field.form?.querySelector("input[type='submit'], button[type='submit'], button");
    if (button) {
      button.click();
    } else if (field.form && typeof field.form.requestSubmit === "function") {
      field.form.requestSubmit();
    } else if (field.form) {
      field.form.submit();
    }
    return true;
  }

  function ehpFetchText(url) {
    if (typeof _GM_xmlhttpRequest === "function") {
      return new Promise((resolve, reject) => {
        _GM_xmlhttpRequest({
          method: "GET",
          url,
          timeout: 15000,
          onload: (response) => {
            if (response.status >= 200 && response.status < 300) resolve(response.responseText || "");
            else reject(new Error(`HTTP ${response.status}`));
          },
          onerror: () => reject(new Error("Network error")),
          ontimeout: () => reject(new Error("Request timeout"))
        });
      });
    }
    return fetch(url, { credentials: "omit" }).then((response) => {
      if (!response.ok) throw new Error(`HTTP ${response.status}`);
      return response.text();
    });
  }

  function parseEhpFetishListing(html) {
    const doc = new DOMParser().parseFromString(html, "text/html");
    const content = doc.querySelector(".mw-parser-output") || doc.querySelector("#mw-content-text") || doc.body;
    if (!content) return [];

    const entries = [];

    function getTagAliases(link) {
      const aliases = [];
      const source = link.closest("[title]")?.getAttribute("title") || "";
      if (!/\b(also|alias|formerly|aka)\b/i.test(source)) return aliases;
      const quoteRe = /["']([^"']+)["']/g;
      let match;
      while ((match = quoteRe.exec(source))) {
        const alias = normalizeEhpTagName(match[1]);
        if (alias) aliases.push(alias);
      }
      return aliases;
    }

    function inferNamespacesFromLink(link) {
      const namespaces = new Set();
      let tail = "";
      let node = link.nextSibling;
      while (node && tail.length < 120) {
        if (node.nodeType === 1 && node.matches && node.matches("a[href*='/wiki/'], a[href^='/wiki/']")) break;
        tail += node.textContent || "";
        if (/[,;\n]/.test(tail)) break;
        node = node.nextSibling;
      }

      const idText = [link.id, link.getAttribute("href"), link.getAttribute("title")].filter(Boolean).join(" ");
      const haystack = `${tail} ${idText}`;

      if (/♀|\bfemale\b|(?:^|\s)f\s*:/i.test(haystack)) namespaces.add("female");
      if (/♂|\bmale\b|(?:^|\s)m\s*:/i.test(haystack)) namespaces.add("male");
      if (/⚥|\bmixed\b|\bboth\b|(?:^|\s)x\s*:/i.test(haystack)) namespaces.add("mixed");
      if (/\bother\b|\bmisc\b|(?:^|\s)o\s*:/i.test(haystack)) namespaces.add("other");

      return namespaces.size ? Array.from(namespaces) : ["other"];
    }

    let active = false;
    Array.from(content.children).forEach((child) => {
      const heading = child.matches("h2") ? child.textContent.replace(/\[.*?\]/g, "").trim().toLowerCase() : "";
      if (heading === "age") active = true;
      if (heading === "see also") active = false;
      if (!active) return;

      Array.from(child.querySelectorAll("a[href*='/wiki/'], a[href^='/wiki/']")).forEach((link) => {
        if (link.closest(".mw-editsection, .toc, #toc")) return;
        const label = normalizeEhpTagName(link.textContent || link.getAttribute("title") || "");
        if (!label || label.length < 2 || label.length > 64) return;
        if (/^(edit|jump to navigation|jump to search|tag types|galleries)$/i.test(label)) return;

        const namespaces = inferNamespacesFromLink(link);
        namespaces.forEach((namespace) => {
          [label, ...getTagAliases(link)].forEach((name) => {
            const entry = parseEhpTagEntry({ namespace, name, source: "catalog" });
            if (entry) entries.push(entry);
          });
        });
      });
    });

    return uniqEhpTagEntries(entries).sort((a, b) => a.name.localeCompare(b.name) || a.namespace.localeCompare(b.namespace));
  }

  function readEhpTagCatalogCache() {
    const raw = _GM_getValue(EHP_TAG_CACHE_KEY, null);
    if (!raw) return null;
    try {
      const parsed = typeof raw === "string" ? JSON.parse(raw) : raw;
      if (!parsed || !Array.isArray(parsed.tags)) return null;
      if (parsed.version !== EHP_TAG_CACHE_VERSION) return null;
      if (!parsed.savedAt || Date.now() - parsed.savedAt > EHP_TAG_CACHE_TTL) return null;
      const tags = uniqEhpTagEntries(parsed.tags);
      return tags.length ? tags : null;
    } catch (_) {
      return null;
    }
  }

  function writeEhpTagCatalogCache(tags) {
    _GM_setValue(EHP_TAG_CACHE_KEY, {
      version: EHP_TAG_CACHE_VERSION,
      savedAt: Date.now(),
      tags: tags.map((tag) => ({ namespace: tag.namespace, name: tag.name }))
    });
  }

  function loadEhpTagCatalog() {
    if (ehpTagCatalog) return Promise.resolve(ehpTagCatalog);
    const cached = readEhpTagCatalogCache();
    if (cached) {
      ehpTagCatalog = cached;
      return Promise.resolve(ehpTagCatalog);
    }
    if (ehpTagCatalogPromise) return ehpTagCatalogPromise;

    ehpTagCatalogPromise = ehpFetchText(EHP_FETISH_LISTING_URL)
      .then((html) => {
        const tags = parseEhpFetishListing(html);
        if (!tags.length) throw new Error("No tags parsed");
        ehpTagCatalog = tags;
        writeEhpTagCatalogCache(tags);
        return tags;
      })
      .catch((err) => {
        console.error("[EHP Tags] Failed to load Fetish Listing", err);
        ehpTagCatalog = readEhpTagCatalogCache() || [];
        return ehpTagCatalog;
      })
      .finally(() => {
        ehpTagCatalogPromise = null;
      });
    return ehpTagCatalogPromise;
  }

  function searchEhpTagCatalog(tags, query) {
    const q = makeEhpTagSearchKey(query);
    if (!q) return [];

    function getSearchFields(tag) {
      const namespace = makeEhpTagSearchKey(tag.namespace || "");
      const name = makeEhpTagSearchKey(tag.name || "");
      const full = makeEhpTagSearchKey(`${tag.namespace || ""}:${tag.name || ""}`);
      const search = makeEhpTagSearchKey(tag.search || getEhpTagSearchText(tag.namespace, tag.name));
      return { namespace, name, full, search };
    }

    function firstMatchIndex(fields) {
      const indexes = [fields.name.indexOf(q), fields.full.indexOf(q), fields.search.indexOf(q), fields.namespace.indexOf(q)]
        .filter((index) => index >= 0);
      return indexes.length ? Math.min(...indexes) : Number.MAX_SAFE_INTEGER;
    }

    return tags
      .filter((tag) => {
        const fields = getSearchFields(tag);
        return fields.name.includes(q) || fields.namespace.includes(q) || fields.full.includes(q) || fields.search.includes(q);
      })
      .sort((a, b) => {
        const aFields = getSearchFields(a);
        const bFields = getSearchFields(b);
        const aStarts = aFields.name.startsWith(q) || aFields.full.startsWith(q) ? 0 : 1;
        const bStarts = bFields.name.startsWith(q) || bFields.full.startsWith(q) ? 0 : 1;
        return aStarts - bStarts
          || firstMatchIndex(aFields) - firstMatchIndex(bFields)
          || aFields.name.length - bFields.name.length
          || aFields.name.localeCompare(bFields.name);
      })
      .slice(0, 120);
  }

  function getEhpExplicitQueryNamespace(query) {
    const raw = String(query || "").trim();
    const colonIndex = raw.indexOf(":");
    if (colonIndex <= 0) return null;
    const namespace = normalizeEhpNamespace(raw.slice(0, colonIndex));
    const name = normalizeEhpTagName(raw.slice(colonIndex + 1));
    return name ? { namespace, name } : null;
  }

  function getEhpPlainTagLookupName(query) {
    const explicit = getEhpExplicitQueryNamespace(query);
    let clean = normalizeEhpTagName(explicit ? explicit.name : query);
    clean = clean.replace(/^['"]|['"]$/g, "").replace(/\$$/, "").trim();
    return clean;
  }

  function getEhpLookupNamespaces(query) {
    const explicit = getEhpExplicitQueryNamespace(query);
    return explicit ? [explicit.namespace] : EHP_LIVE_LOOKUP_NAMESPACES;
  }

  function makeEhpGallerySearchURL(searchText) {
    const url = new URL("/", location.origin);
    url.searchParams.set("f_search", searchText);
    return url.toString();
  }

  function makeEhpLiveSearchText(query) {
    const explicit = getEhpExplicitQueryNamespace(query);
    if (!explicit) return getEhpPlainTagLookupName(query);
    const name = explicit.name.includes(" ") ? `"${explicit.name.replace(/"/g, '\\"')}"` : explicit.name;
    return `${explicit.namespace}:${name}`;
  }

  function ehpFetchSameOriginText(url) {
    return fetch(url, { credentials: "same-origin" }).then((response) => {
      if (!response.ok) throw new Error(`HTTP ${response.status}`);
      return response.text();
    });
  }

  function parseEhpGalleryLinksFromSearchHtml(html) {
    const doc = new DOMParser().parseFromString(html, "text/html");
    const seen = new Set();
    return Array.from(doc.querySelectorAll("a[href*='/g/']"))
      .map((a) => a.href)
      .filter((href) => /\/g\/\d+\/[0-9a-f]+\/?/i.test(href))
      .filter((href) => {
        const clean = href.replace(/[?#].*$/, "");
        if (seen.has(clean)) return false;
        seen.add(clean);
        return true;
      })
      .slice(0, EHP_LIVE_TAG_LOOKUP_MAX_GALLERIES);
  }

  function parseEhpTagFromHref(href) {
    try {
      const url = new URL(href, location.origin);
      const search = url.searchParams.get("f_search") || "";
      const parsed = parseEhpTagEntry(search);
      return parsed;
    } catch (_) {
      return null;
    }
  }

  function parseEhpTagsFromGalleryHtml(html) {
    const doc = new DOMParser().parseFromString(html, "text/html");
    const entries = [];

    doc.querySelectorAll("#taglist tr").forEach((row) => {
      const namespaceText = normalizeEhpNamespace((row.querySelector(".tc, td:first-child")?.textContent || "").replace(":", ""));
      row.querySelectorAll("[id^='td_'], a[href*='f_search'], .gt, .gtl, .gtw").forEach((node) => {
        let namespace = namespaceText;
        let name = "";
        const id = node.id || "";

        if (id.startsWith("td_") && id.includes(":")) {
          const raw = id.slice(3);
          const colonIndex = raw.indexOf(":");
          namespace = normalizeEhpNamespace(raw.slice(0, colonIndex));
          name = decodeURIComponent(raw.slice(colonIndex + 1)).replace(/_/g, " ");
        }

        if (!name && node.matches && node.matches("a[href*='f_search']")) {
          const parsed = parseEhpTagFromHref(node.getAttribute("href") || "");
          if (parsed) {
            entries.push({ ...parsed, source: "live" });
            return;
          }
        }

        if (!name) name = normalizeEhpTagName(node.textContent || node.getAttribute("title") || "");
        if (!name || /^[-+\d]+$/.test(name)) return;
        const parsed = parseEhpTagEntry({ namespace, name, source: "live" });
        if (parsed) entries.push(parsed);
      });
    });

    return uniqEhpTagEntries(entries);
  }

  function createEhpNamespaceCandidates(query) {
    const plainName = getEhpPlainTagLookupName(query);
    if (!plainName) return [];
    return getEhpLookupNamespaces(query)
      .map((namespace) => parseEhpTagEntry({ namespace, name: plainName, source: "candidate" }))
      .filter(Boolean);
  }

  function tagMatchesEhpQuery(tag, query) {
    const q = makeEhpTagSearchKey(query);
    const plain = makeEhpTagSearchKey(getEhpPlainTagLookupName(query));
    const namespace = makeEhpTagSearchKey(tag.namespace || "");
    const name = makeEhpTagSearchKey(tag.name || "");
    const full = makeEhpTagSearchKey(`${tag.namespace || ""}:${tag.name || ""}`);
    const search = makeEhpTagSearchKey(tag.search || getEhpTagSearchText(tag.namespace, tag.name));
    return name.includes(q) || full.includes(q) || search.includes(q) || namespace.includes(q) || (!!plain && name.includes(plain));
  }

  function loadEhpLiveTagMatches(query) {
    const plainName = getEhpPlainTagLookupName(query);
    const explicit = getEhpExplicitQueryNamespace(query);
    if (!plainName || (!explicit && plainName.length < EHP_LIVE_TAG_LOOKUP_MIN_LENGTH)) {
      return Promise.resolve([]);
    }

    const cacheKey = `${location.origin}|${makeEhpTagSearchKey(query)}`;
    if (ehpLiveTagLookupCache.has(cacheKey)) return ehpLiveTagLookupCache.get(cacheKey);

    const promise = ehpFetchSameOriginText(makeEhpGallerySearchURL(makeEhpLiveSearchText(query)))
      .then((html) => parseEhpGalleryLinksFromSearchHtml(html))
      .then((links) => Promise.all(links.map((href) => ehpFetchSameOriginText(href).then(parseEhpTagsFromGalleryHtml).catch(() => []))))
      .then((chunks) => uniqEhpTagEntries(chunks.flat())
        .filter((tag) => tagMatchesEhpQuery(tag, query))
        .slice(0, EHP_LIVE_TAG_LOOKUP_MAX_RESULTS))
      .catch((err) => {
        console.warn("[EHP Tags] Live lookup failed", err);
        return [];
      });

    ehpLiveTagLookupCache.set(cacheKey, promise);
    return promise;
  }

  function clampEhpTagPanelSize(width, height) {
    const maxWidth = Math.max(260, window.innerWidth - 124);
    const maxHeight = Math.max(260, window.innerHeight - 96);
    const minWidth = Math.min(420, maxWidth);
    const minHeight = Math.min(420, maxHeight);
    return {
      width: Math.max(minWidth, Math.min(maxWidth, Math.round(width))),
      height: Math.max(minHeight, Math.min(maxHeight, Math.round(height)))
    };
  }

  function applyEhpSavedTagPanelSize(panel) {
    const saved = _GM_getValue(EHP_TAG_PANEL_SIZE_KEY, null);
    if (!saved || typeof saved !== "object" || !saved.width || !saved.height) return;
    const size = clampEhpTagPanelSize(saved.width, saved.height);
    panel.style.width = `${size.width}px`;
    panel.style.height = `${size.height}px`;
    panel.style.aspectRatio = "auto";
  }

  function attachEhpTagPanelResize(panel) {
    let resizeState = null;
    const edgeSize = 10;
    const getEdges = (event) => {
      const rect = panel.getBoundingClientRect();
      const left = event.clientX - rect.left <= edgeSize;
      const top = event.clientY - rect.top <= edgeSize;
      return { left, top, active: left || top };
    };
    const cursorFor = (edges) => edges.left && edges.top ? "nwse-resize" : edges.left ? "ew-resize" : edges.top ? "ns-resize" : "";

    panel.addEventListener("pointermove", (event) => {
      if (resizeState) return;
      panel.style.cursor = cursorFor(getEdges(event));
    });

    panel.addEventListener("pointerleave", () => {
      if (!resizeState) panel.style.cursor = "";
    });

    panel.addEventListener("pointerdown", (event) => {
      const edges = getEdges(event);
      if (!edges.active || event.button !== 0) return;
      const rect = panel.getBoundingClientRect();
      resizeState = {
        pointerId: event.pointerId,
        edges,
        startX: event.clientX,
        startY: event.clientY,
        width: rect.width,
        height: rect.height
      };
      panel.classList.add("is-resizing");
      panel.setPointerCapture(event.pointerId);
      event.preventDefault();
      event.stopPropagation();
    });

    panel.addEventListener("pointermove", (event) => {
      if (!resizeState || resizeState.pointerId !== event.pointerId) return;
      const nextWidth = resizeState.edges.left ? resizeState.width + (resizeState.startX - event.clientX) : resizeState.width;
      const nextHeight = resizeState.edges.top ? resizeState.height + (resizeState.startY - event.clientY) : resizeState.height;
      const size = clampEhpTagPanelSize(nextWidth, nextHeight);
      panel.style.width = `${size.width}px`;
      panel.style.height = `${size.height}px`;
      panel.style.aspectRatio = "auto";
      event.preventDefault();
      event.stopPropagation();
    });

    const finishResize = (event) => {
      if (!resizeState || resizeState.pointerId !== event.pointerId) return;
      resizeState = null;
      panel.classList.remove("is-resizing");
      panel.style.cursor = "";
      const rect = panel.getBoundingClientRect();
      const size = clampEhpTagPanelSize(rect.width, rect.height);
      _GM_setValue(EHP_TAG_PANEL_SIZE_KEY, size);
    };
    panel.addEventListener("pointerup", finishResize);
    panel.addEventListener("pointercancel", finishResize);
  }

  function createEhpTagGate(root) {
    const gate = document.createElement("div");
    gate.className = "ehp-tag-gate";
    gate.innerHTML = `
      <h2><a href="https://ehwiki.org/wiki/Gallery_Tagging" target="_blank" rel="noopener noreferrer">A Quick Note About Tagging</a></h2>
      <p>While tagging is relatively straight-forward, there are a number of established guidelines that determine when adding a particular tag is proper and when it is not. Before you put any significant amount of effort into it, we therefore ask that you skim through the <a href="https://ehwiki.org/wiki/Gallery_Tagging#General_Usage_Guidelines" target="_blank" rel="noopener noreferrer">Basic Tagging Guidelines</a> and <a href="https://ehwiki.org/wiki/Fetish_Listing" target="_blank" rel="noopener noreferrer">Fetish Listing</a>. This will likely save both you and the tagging moderators from doing unnecessary work. In particular, you should note the following:</p>
      <p>- These are galleries, not individual images. <strong>Do not tag stuff that is only featured in a few images.</strong></p>
      <p>- If a tag is ambiguous or frequently misused, you may have to specify a namespace; <a href="https://ehwiki.org/wiki/Namespace" target="_blank" rel="noopener noreferrer">see the Wiki</a>.</p>
      <p>- The <a href="https://ehwiki.org/wiki/Tagging_Mechanics#Tag_Mod_Power" target="_blank" rel="noopener noreferrer">power</a> with which you can affect tagging is determined by a number of factors, such as your account age and whether or not you are active on the <a href="https://forums.e-hentai.org/" target="_blank" rel="noopener noreferrer">forums</a>.</p>
      <p>- The forums is also where <a href="https://forums.e-hentai.org/" target="_blank" rel="noopener noreferrer">everything about tagging is discussed</a>. If you have any comments, suggestions or questions about tagging, this is where you should take it.</p>
    `;
    const accept = document.createElement("button");
    accept.type = "button";
    accept.textContent = "Alright Already";
    accept.addEventListener("click", (event) => {
      event.preventDefault();
      event.stopPropagation();
      _GM_setValue(EHP_GALLERY_TAG_NOTICE_KEY, true);
      root.classList.add("is-gate-accepted");
    });
    gate.appendChild(accept);
    return gate;
  }

  function initEhpTagSystem() {
    if (document.getElementById("ehp-tag-system")) return;

    const isGalleryPage = location.pathname.startsWith("/g/");
    const searchInput = findEhpSearchInput();
    if (!isGalleryPage && !searchInput) return;

    ensureEhpReaderStyle();

    const root = document.createElement("div");
    root.id = "ehp-tag-system";
    root.className = isGalleryPage ? "ehp-gallery-tags" : "ehp-search-tags";
    if (!isGalleryPage || _GM_getValue(EHP_GALLERY_TAG_NOTICE_KEY, false)) {
      root.classList.add("is-gate-accepted");
    }

    const panel = document.createElement("div");
    panel.className = "ehp-tag-panel";

    const display = document.createElement("div");
    display.className = "ehp-tag-display";

    const favHead = document.createElement("div");
    favHead.className = "ehp-tag-fav-head";

    const favToggle = document.createElement("button");
    favToggle.type = "button";
    favToggle.className = "ehp-tag-fav-toggle";
    favToggle.innerHTML = EHP_ICONS.favorite;
    favToggle.setAttribute("aria-label", "Favorite namespaces");

    const namespaceRail = document.createElement("div");
    namespaceRail.className = "ehp-tag-namespace-rail";
    favHead.append(favToggle, namespaceRail);

    const grid = document.createElement("div");
    grid.className = "ehp-tag-grid";

    const searchDock = document.createElement("div");
    searchDock.className = "ehp-tag-search-dock";

    const searchWrap = document.createElement("div");
    searchWrap.className = "ehp-tag-search-wrap";

    const searchIcon = document.createElement("span");
    searchIcon.className = "ehp-tag-search-icon";
    searchIcon.innerHTML = EHP_ICONS.search;

    const tagSearchInput = document.createElement("input");
    tagSearchInput.type = "search";
    tagSearchInput.className = "ehp-tag-search-input";
    tagSearchInput.placeholder = "search tags";
    tagSearchInput.autocomplete = "off";
    tagSearchInput.spellcheck = false;
    tagSearchInput.setAttribute("aria-label", "Search E-Hentai tags");

    searchWrap.append(searchIcon, tagSearchInput);
    searchDock.appendChild(searchWrap);

    display.appendChild(grid);

    panel.append(favHead, display, searchDock);
    if (isGalleryPage && !_GM_getValue(EHP_GALLERY_TAG_NOTICE_KEY, false)) {
      panel.appendChild(createEhpTagGate(root));
    }

    const launcher = document.createElement("button");
    launcher.type = "button";
    launcher.className = "ehp-tag-launcher";
    launcher.innerHTML = EHP_ICONS.tag;
    launcher.title = isGalleryPage ? "Gallery tags" : "Search tags";
    launcher.setAttribute("aria-label", launcher.title);

    root.append(panel, launcher);
    document.body.appendChild(root);
    applyEhpSavedTagPanelSize(panel);
    attachEhpTagPanelResize(panel);

    let activeNamespace = "";
    let tagSearchQuery = "";
    let tagSearchRun = 0;
    const recentlyAddedGalleryTags = new Set();

    const tagTooltip = document.createElement("div");
    tagTooltip.className = "ehp-tag-tooltip";
    tagTooltip.setAttribute("role", "tooltip");
    panel.appendChild(tagTooltip);

    function setTagUiOpen(open) {
      root.classList.toggle("is-open", open);
      if (!open) hideTagTooltip();
    }

    function hideTagTooltip() {
      tagTooltip.classList.remove("is-visible");
    }

    function showTagTooltip(anchor, text) {
      if (!anchor || !text || !root.classList.contains("is-open")) return;
      tagTooltip.textContent = text;
      tagTooltip.classList.add("is-visible");

      const panelRect = panel.getBoundingClientRect();
      const anchorRect = anchor.getBoundingClientRect();
      const tipRect = tagTooltip.getBoundingClientRect();
      const pad = 10;

      let left = anchorRect.left - panelRect.left + anchorRect.width / 2 - tipRect.width / 2;
      let top = anchorRect.top - panelRect.top - tipRect.height - 8;

      if (top < pad) top = anchorRect.bottom - panelRect.top + 8;
      left = Math.max(pad, Math.min(left, panelRect.width - tipRect.width - pad));
      top = Math.max(pad, Math.min(top, panelRect.height - tipRect.height - pad));

      tagTooltip.style.left = `${left}px`;
      tagTooltip.style.top = `${top}px`;
    }

    function wireTagTooltip(anchor, text) {
      if (!anchor || !text) return;
      anchor.dataset.ehpTooltip = text;
      anchor.removeAttribute("title");
      anchor.addEventListener("pointerenter", () => showTagTooltip(anchor, text));
      anchor.addEventListener("pointerleave", hideTagTooltip);
      anchor.addEventListener("focus", () => showTagTooltip(anchor, text));
      anchor.addEventListener("blur", hideTagTooltip);
    }

    wireTagTooltip(favToggle, "Favorite namespaces");
    display.addEventListener("scroll", hideTagTooltip, { passive: true });

    function activeFavoriteNamespaces() {
      const seen = new Set();
      getEhpFavoriteTags().forEach((tag) => seen.add(tag.namespace));
      return EHP_NAMESPACE_DEFS.filter((meta) => seen.has(meta.key));
    }

    function renderNamespaceRail() {
      namespaceRail.innerHTML = "";
      const metas = activeFavoriteNamespaces();
      if (!metas.some((meta) => meta.key === activeNamespace)) activeNamespace = "";
      metas.forEach((meta) => {
        const btn = document.createElement("button");
        btn.type = "button";
        btn.className = "ehp-tag-ns-button";
        btn.classList.toggle("is-active", activeNamespace === meta.key);
        btn.innerHTML = getEhpNamespaceIcon(meta.key);
        btn.setAttribute("aria-label", `${meta.key} favorites`);
        wireTagTooltip(btn, `${meta.key} favorites`);
        btn.addEventListener("click", (event) => {
          event.preventDefault();
          event.stopPropagation();
          activeNamespace = activeNamespace === meta.key ? "" : meta.key;
          renderIdle();
        });
        namespaceRail.appendChild(btn);
      });
    }

    function makeTagChip(entry, mode) {
      const parsed = parseEhpTagEntry(entry);
      if (!parsed) return null;
      const isFavorite = isEhpFavoriteTag(parsed);
      const siteSearchValue = findEhpSearchInput()?.value || "";

      const chip = document.createElement("button");
      chip.type = "button";
      chip.className = "ehp-tag-chip";
      chip.classList.toggle("is-active", isGalleryPage ? recentlyAddedGalleryTags.has(parsed.value.toLowerCase()) : isEhpTagInSearch(parsed, siteSearchValue));
      chip.classList.toggle("is-live", parsed.source === "live");
      chip.classList.toggle("is-candidate", parsed.source === "candidate");
      const tooltipText = `${parsed.value}${parsed.source === "candidate" ? "\nCandidate: click only if you know this exact namespace is correct." : parsed.source === "live" ? "\nFound from matching gallery tags." : ""}`;
      chip.dataset.ehpTooltip = tooltipText;
      chip.removeAttribute("title");
      chip.addEventListener("pointerenter", () => showTagTooltip(chip, tooltipText));
      chip.addEventListener("pointerleave", hideTagTooltip);
      chip.addEventListener("focus", () => showTagTooltip(chip, tooltipText));
      chip.addEventListener("blur", hideTagTooltip);

      const main = document.createElement("span");
      main.className = "ehp-tag-chip-main";
      const icon = document.createElement("span");
      icon.className = "ehp-tag-ns-icon";
      icon.innerHTML = getEhpNamespaceIcon(parsed.namespace);
      const name = document.createElement("span");
      name.className = "ehp-tag-name";
      name.textContent = getEhpDisplayTagName(parsed);
      main.append(icon, name);

      const action = document.createElement("span");
      action.className = "ehp-tag-action";
      action.innerHTML = mode === "favorite" || isFavorite ? EHP_ICONS.remove : EHP_ICONS.add;
      const actionTooltip = mode === "favorite" || isFavorite ? "Remove favorite" : "Add favorite";
      action.dataset.ehpTooltip = actionTooltip;
      action.setAttribute("aria-label", actionTooltip);
      action.removeAttribute("title");

      chip.append(main, action);
      chip.addEventListener("click", (event) => {
        event.preventDefault();
        event.stopPropagation();
        if (action.contains(event.target)) {
          if (mode === "favorite" || isEhpFavoriteTag(parsed)) removeEhpFavoriteTag(parsed);
          else addEhpFavoriteTag(parsed);
          refresh();
          return;
        }
        if (isGalleryPage) {
          if (!isEhpFeatureEnabled("tagging.activeGalleryTagging", true)) return;
          if (addEhpTagToGallery(parsed)) {
            recentlyAddedGalleryTags.add(parsed.value.toLowerCase());
            setTagUiOpen(true);
            refresh();
          }
        } else {
          toggleEhpTagInSearch(parsed);
          refresh();
        }
      });
      return chip;
    }

    function renderEntries(entries, mode) {
      grid.innerHTML = "";
      entries.forEach((entry) => {
        const chip = makeTagChip(entry, mode);
        if (chip) grid.appendChild(chip);
      });
    }

    function renderTagMessage(message) {
      grid.innerHTML = "";
      const empty = document.createElement("div");
      empty.className = "ehp-tag-empty-state";
      empty.textContent = message;
      grid.appendChild(empty);
    }

    function renderIdle() {
      renderNamespaceRail();
      const favorites = getEhpFavoriteTags().filter((tag) => !activeNamespace || tag.namespace === activeNamespace);
      if (favorites.length) renderEntries(favorites, "favorite");
      else renderTagMessage("No favorite tags yet. Search below, then press the + on a tag capsule to save it here.");
    }

    function renderSearch() {
      renderNamespaceRail();
      const query = tagSearchQuery.trim();
      if (!query) {
        renderIdle();
        return;
      }

      const runId = ++tagSearchRun;
      renderTagMessage("Searching tag catalog...");

      loadEhpTagCatalog().then((tags) => {
        if (runId !== tagSearchRun) return;
        const catalogResults = searchEhpTagCatalog(tags, query);
        if (!isEhpFeatureEnabled("tagging.liveLookup", true)) {
          let results = catalogResults;
          if (!results.length || getEhpExplicitQueryNamespace(query)) {
            results = uniqEhpTagEntries([...results, ...createEhpNamespaceCandidates(query)]);
          }
          if (results.length) renderEntries(results, "search");
          else renderTagMessage(`No tags found for “${query}”. Try namespace:name manually if you know the exact tag.`);
          return null;
        }

        if (catalogResults.length) renderEntries(catalogResults, "search");
        else renderTagMessage("Checking live gallery tags...");

        return loadEhpLiveTagMatches(query).then((liveResults) => {
          if (runId !== tagSearchRun) return;
          let results = uniqEhpTagEntries([...catalogResults, ...liveResults]);

          if (!results.length || getEhpExplicitQueryNamespace(query)) {
            results = uniqEhpTagEntries([...results, ...createEhpNamespaceCandidates(query)]);
          }

          if (results.length) renderEntries(results, "search");
          else renderTagMessage(`No tags found for “${query}”. Try namespace:name manually if you know the exact tag.`);
        });
      }).catch((err) => {
        console.error("[EHP Tags] Search failed", err);
        if (runId === tagSearchRun) renderTagMessage("Could not load tag catalog. Try the search again later.");
      });
    }

    function refresh() {
      if (tagSearchQuery.trim()) renderSearch();
      else renderIdle();
    }

    tagSearchInput.addEventListener("input", () => {
      tagSearchQuery = tagSearchInput.value || "";
      refresh();
    });

    tagSearchInput.addEventListener("keydown", (event) => {
      if (event.key === "Escape") {
        event.preventDefault();
        tagSearchInput.value = "";
        tagSearchQuery = "";
        refresh();
      }
    });

    favToggle.addEventListener("click", (event) => {
      event.preventDefault();
      event.stopPropagation();
      activeNamespace = "";
      root.classList.toggle("is-fav-rail-open");
      renderIdle();
    });

    launcher.addEventListener("click", (event) => {
      event.preventDefault();
      event.stopPropagation();
      const shouldOpen = !root.classList.contains("is-open");
      closeEhpPopups(root);
      setTagUiOpen(shouldOpen);
      refresh();
      if (shouldOpen) setTimeout(() => tagSearchInput.focus({ preventScroll: true }), 80);
    });

    if (searchInput) {
      searchInput.addEventListener("input", refresh);
      searchInput.addEventListener("change", refresh);
    }


    document.addEventListener(EHP_POPUP_CLOSE_EVENT, (event) => {
      if (shouldIgnoreEhpPopupClose(event, root)) return;
      setTagUiOpen(false);
    });

    refresh();
  }

  /************************************************************
   * EXTRA FEATURE: QUICK FAVOURITE
   * Native-looking favourite category picker for existing EH/EX favourite triggers.
   ************************************************************/
  const EHP_QUICK_FAV_CACHE_KEY = "ehpQuickFavouriteCategories";
  const EHP_QUICK_FAV_CACHE_TTL = 24 * 60 * 60 * 1000;
  const EHP_QUICK_FAV_TIP_DISMISSED_KEY = "ehpQuickFavouriteTipDismissed";
  let ehpQuickFavMenu = null;
  let ehpQuickFavObserver = null;
  let ehpQuickFavHoverTimer = 0;
  let ehpQuickFavCloseTimer = 0;
  let ehpQuickFavActiveContext = null;
  const ehpQuickFavStateCache = new Map();
  const ehpQuickFavPopupDocCache = new Map();


  function normalizeEhpQuickFavUrl(url) {
    if (!url) return "";
    const cleaned = String(url).replace(/&amp;/g, "&").trim();
    try {
      return new URL(cleaned, location.origin).toString();
    } catch (_err) {
      return "";
    }
  }

  function getEhpQuickFavGalleryUrlFromPage() {
    const match = location.pathname.match(/^\/g\/(\d+)\/([^/]+)/);
    if (!match) return "";
    return `${location.origin}/gallerypopups.php?gid=${encodeURIComponent(match[1])}&t=${encodeURIComponent(match[2])}&act=addfav`;
  }

  function extractEhpQuickFavUrl(trigger) {
    if (!trigger) return "";
    if (trigger.dataset && trigger.dataset.ehpQuickFavUrl) return trigger.dataset.ehpQuickFavUrl;

    const href = trigger.getAttribute && (trigger.getAttribute("href") || trigger.href);
    if (href && /gallerypopups\.php/i.test(href) && /act=addfav/i.test(href)) {
      return normalizeEhpQuickFavUrl(href);
    }

    const onclick = trigger.getAttribute && trigger.getAttribute("onclick");
    if (onclick) {
      const quoted = onclick.match(/["']([^"']*gallerypopups\.php\?[^"']*act=addfav[^"']*)["']/i);
      if (quoted && quoted[1]) return normalizeEhpQuickFavUrl(quoted[1]);
    }

    if (trigger.id === "gdf" || trigger.closest && trigger.closest("#gdf")) {
      return getEhpQuickFavGalleryUrlFromPage();
    }

    return "";
  }

  function getEhpQuickFavGalleryKeyFromUrl(favUrl) {
    try {
      const url = new URL(favUrl, location.origin);
      const gid = url.searchParams.get("gid") || "";
      const token = url.searchParams.get("t") || "";
      return gid ? `${gid}:${token}` : url.toString();
    } catch (_err) {
      return favUrl || "";
    }
  }

  function readEhpQuickFavCategoryCache() {
    const cached = _GM_getValue(EHP_QUICK_FAV_CACHE_KEY, null);
    if (!cached || typeof cached !== "object") return null;
    if (!Array.isArray(cached.categories)) return null;
    if (Date.now() - Number(cached.savedAt || 0) > EHP_QUICK_FAV_CACHE_TTL) return null;
    return cached.categories;
  }

  function writeEhpQuickFavCategoryCache(categories) {
    _GM_setValue(EHP_QUICK_FAV_CACHE_KEY, { savedAt: Date.now(), categories });
  }

  function fallbackEhpQuickFavCategories() {
    return Array.from({ length: 10 }, (_, index) => ({ index, name: `Favorite ${index}` }));
  }

  function parseEhpQuickFavCategories(doc) {
    const found = [];
    const inputs = Array.from(qa('input[name^="favorite_"]', doc));
    inputs.forEach((input) => {
      const match = String(input.name || "").match(/favorite_(\d+)/i);
      if (!match) return;
      const index = parseInt(match[1], 10);
      if (Number.isNaN(index)) return;
      const rawName = String(input.value || "").trim();
      found.push({ index, name: rawName || `Favorite ${index}` });
    });

    if (!found.length) {
      const options = Array.from(qa('select[name="favcat"] option, input[name="favcat"]', doc));
      options.forEach((option) => {
        const index = parseInt(option.value, 10);
        if (Number.isNaN(index) || index < 0) return;
        const rawName = String(option.textContent || option.getAttribute("label") || "").trim();
        found.push({ index, name: rawName || `Favorite ${index}` });
      });
    }

    return found
      .filter((cat, pos, all) => all.findIndex((item) => item.index === cat.index) === pos)
      .sort((a, b) => a.index - b.index);
  }

  async function loadEhpQuickFavCategories(forceRefresh = false) {
    if (!forceRefresh) {
      const cached = readEhpQuickFavCategoryCache();
      if (cached && cached.length) return cached;
    }

    try {
      const response = await fetch(`${location.origin}/uconfig.php`, { credentials: "include" });
      if (!response.ok) throw new Error(`HTTP ${response.status}`);
      const html = await response.text();
      const doc = sharedParser.parseFromString(html, "text/html");
      const categories = parseEhpQuickFavCategories(doc);
      const finalCategories = categories.length ? categories : fallbackEhpQuickFavCategories();
      writeEhpQuickFavCategoryCache(finalCategories);
      return finalCategories;
    } catch (err) {
      console.warn("[EHP Quick Favourite] Could not load favourite category names", err);
      const cached = readEhpQuickFavCategoryCache();
      return cached && cached.length ? cached : fallbackEhpQuickFavCategories();
    }
  }

  function cleanEhpNativeIconClone(icon) {
    if (!icon) return "";
    const clone = icon.cloneNode(true);
    if (clone.removeAttribute) {
      clone.removeAttribute("id");
      clone.removeAttribute("onclick");
      clone.removeAttribute("onmouseover");
      clone.removeAttribute("onmouseout");
      clone.setAttribute("aria-hidden", "true");
    }
    clone.querySelectorAll?.("script, style, input, button, select, textarea").forEach((node) => node.remove());
    return clone.outerHTML || "";
  }

  function parseEhpQuickFavNativeIconMap(doc) {
    const icons = new Map();
    const inputs = Array.from(qa('input[name="favcat"], select[name="favcat"] option', doc));
    inputs.forEach((input) => {
      const index = parseInt(input.value, 10);
      if (Number.isNaN(index) || index < 0) return;
      const root = input.closest?.("tr, li, label, div, p") || input.parentElement;
      if (!root) return;
      const icon = root.querySelector('div.i, span.i, img, [style*="background-image"], [class*="fav"], [class*="star"], [class^="fp"], [class*=" fp"], [class^="fs"], [class*=" fs"]');
      const html = cleanEhpNativeIconClone(icon);
      if (html) icons.set(index, html);
    });
    return icons;
  }

  async function fetchEhpQuickFavPopupDoc(context) {
    if (!context || !context.favUrl) return null;
    const key = context.galleryKey || context.favUrl;
    if (ehpQuickFavPopupDocCache.has(key)) return ehpQuickFavPopupDocCache.get(key);

    const promise = fetch(context.favUrl, { credentials: "include" }).then(async (response) => {
      if (!response.ok) throw new Error(`HTTP ${response.status}`);
      const html = await response.text();
      return sharedParser.parseFromString(html, "text/html");
    }).catch((err) => {
      ehpQuickFavPopupDocCache.delete(key);
      throw err;
    });

    ehpQuickFavPopupDocCache.set(key, promise);
    return promise;
  }

  async function loadEhpQuickFavCategoriesForMenu(context) {
    const categories = await loadEhpQuickFavCategories(true);
    if (!context || !context.favUrl) return categories;

    try {
      const doc = await fetchEhpQuickFavPopupDoc(context);
      const iconMap = parseEhpQuickFavNativeIconMap(doc);
      if (!iconMap.size) return categories;
      return categories.map((cat) => ({ ...cat, iconHtml: iconMap.get(Number(cat.index)) || cat.iconHtml || "" }));
    } catch (err) {
      console.warn("[EHP Quick Favourite] Could not load native favourite icons", err);
      return categories;
    }
  }

  function closeEhpQuickFavMenu() {
    clearTimeout(ehpQuickFavHoverTimer);
    cancelEhpQuickFavCloseTimer();
    if (!ehpQuickFavMenu) {
      ehpQuickFavActiveContext = null;
      return;
    }
    ehpQuickFavMenu.remove();
    ehpQuickFavMenu = null;
    ehpQuickFavActiveContext = null;
  }

  function cancelEhpQuickFavCloseTimer() {
    clearTimeout(ehpQuickFavCloseTimer);
    ehpQuickFavCloseTimer = 0;
  }

  function scheduleEhpQuickFavClose(delay = 220) {
    cancelEhpQuickFavCloseTimer();
    ehpQuickFavCloseTimer = window.setTimeout(() => closeEhpQuickFavMenu(), delay);
  }

  function shouldShowEhpQuickFavTip() {
    return !_GM_getValue(EHP_QUICK_FAV_TIP_DISMISSED_KEY, false);
  }

  function markEhpQuickFavTipDone() {
    _GM_setValue(EHP_QUICK_FAV_TIP_DISMISSED_KEY, true);
  }

  function makeEhpQuickFavNativeIcon(index, nativeHtml = "") {
    const icon = document.createElement("span");
    const safeIndex = Number.isFinite(Number(index)) ? Math.max(0, Math.min(9, Number(index))) : 0;
    icon.className = `ehp-qfav-native-icon ehp-qfav-native-${safeIndex}`;
    icon.setAttribute("aria-hidden", "true");
    icon.dataset.favcat = String(safeIndex);

    if (nativeHtml) {
      const doc = sharedParser.parseFromString(`<body>${nativeHtml}</body>`, "text/html");
      const nativeNode = doc.body.firstElementChild;
      if (nativeNode) {
        nativeNode.removeAttribute?.("id");
        icon.classList.add("has-native-node");
        icon.innerHTML = "";
        icon.appendChild(document.importNode(nativeNode, true));
      }
    }

    if (!icon.classList.contains("has-native-node")) {
      const fallback = document.createElement("div");
      fallback.className = `i ehp-qfav-fallback-i ehp-qfav-fallback-i-${safeIndex}`;
      fallback.setAttribute("aria-hidden", "true");
      icon.classList.add("has-native-node", "has-fallback-i");
      icon.innerHTML = "";
      icon.appendChild(fallback);
    }

    return icon;
  }

  function positionEhpQuickFavMenu(menu, trigger) {
    if (!menu || !trigger) return;
    const rect = trigger.getBoundingClientRect();
    const gap = 10;

    menu.style.left = "0px";
    menu.style.top = "0px";
    const menuRect = menu.getBoundingClientRect();
    const left = Math.max(12, Math.min(window.innerWidth - menuRect.width - 12, rect.left + rect.width / 2 - menuRect.width / 2));
    const topAbove = rect.top - menuRect.height - gap;
    const top = topAbove >= 10 ? topAbove : Math.min(window.innerHeight - menuRect.height - 12, rect.bottom + gap);

    menu.style.left = `${Math.round(left)}px`;
    menu.style.top = `${Math.round(Math.max(10, top))}px`;
    requestAnimationFrame(() => menu.classList.add("is-open"));
  }

  function clearEhpQuickFavContent(menu) {
    if (!menu) return;
    Array.from(menu.querySelectorAll(":scope > .ehp-qfav-list, :scope > .ehp-qfav-loading, :scope > .ehp-qfav-error"))
      .forEach((node) => node.remove());
  }

  function insertEhpQuickFavContent(menu, node) {
    if (!menu || !node) return;
    menu.appendChild(node);
  }

  function renderEhpQuickFavLoading(menu, message = "Loading favourite categories...") {
    if (!menu) return;
    clearEhpQuickFavContent(menu);
    const loading = document.createElement("div");
    loading.className = "ehp-qfav-loading";
    loading.textContent = message;
    insertEhpQuickFavContent(menu, loading);
  }

  function setEhpQuickFavStatus(menu, text) {
    if (!menu) return;
    const value = String(text || "").trim();
    if (value) menu.dataset.status = value;
    else delete menu.dataset.status;
  }

  function applyEhpQuickFavReturnedUpdate(html) {
    try {
      const doc = sharedParser.parseFromString(String(html || ""), "text/html");
      const scripts = Array.from(doc.querySelectorAll("script"))
        .map((script) => script.textContent || "")
        .filter(Boolean);
      const updateCode = scripts.find((code) => /window\.opener|opener\.|fav/i.test(code));
      if (!updateCode) return false;
      const safeCode = updateCode
        .replace(/window\.opener\./g, "")
        .replace(/opener\./g, "")
        .replace(/window\.close\(\);?/g, "")
        .replace(/self\.close\(\);?/g, "");
      if (!safeCode.trim()) return false;
      new Function(safeCode)();
      return true;
    } catch (err) {
      console.warn("[EHP Quick Favourite] Returned page update script failed", err);
      return false;
    }
  }

  function getEhpQuickFavCurrentCategory(trigger) {
    if (!trigger) return null;
    const status = String(trigger.dataset?.ehpQuickFavStatus || "");
    const fromDataset = status.match(/cat-(\d+)/i);
    if (fromDataset) return Number(fromDataset[1]);
    const text = String(trigger.textContent || "").replace(/\s+/g, " ").trim();
    const fromText = text.match(/Favorites?\s*(\d+)/i) || text.match(/Favourite\s*(\d+)/i);
    if (fromText) return Number(fromText[1]);
    return null;
  }

  function parseEhpQuickFavStateFromPopup(doc, context) {
    const text = doc && doc.body ? doc.body.textContent || "" : "";
    const triggerCategory = getEhpQuickFavCurrentCategory(context && context.trigger);

    const explicitRemoveControl = !!(doc && doc.querySelector(
      'input[type="submit"][value*="Remove"], input[type="button"][value*="Remove"], button[value*="Remove"], button[name="apply"][value*="Remove"]'
    ));
    const explicitRemoveText = /remove\s+from\s+favou?rites/i.test(text);
    const popupConfirmsFavorited = explicitRemoveControl || explicitRemoveText;

    let checkedCategory = null;
    if (popupConfirmsFavorited && doc) {
      const checked = doc.querySelector('input[name="favcat"]:checked, option[selected][value]');
      if (checked) {
        const value = parseInt(checked.value, 10);
        if (!Number.isNaN(value) && value >= 0) checkedCategory = value;
      }
    }

    const currentCategory = triggerCategory !== null ? triggerCategory : checkedCategory;
    return {
      isFavorited: currentCategory !== null && (triggerCategory !== null || popupConfirmsFavorited),
      currentCategory
    };
  }

  async function resolveEhpQuickFavState(context) {
    const key = context && (context.galleryKey || context.favUrl);
    if (!key) return { isFavorited: false, currentCategory: null };
    if (ehpQuickFavStateCache.has(key)) return ehpQuickFavStateCache.get(key);

    try {
      const doc = await fetchEhpQuickFavPopupDoc(context);
      const state = parseEhpQuickFavStateFromPopup(doc, context);
      ehpQuickFavStateCache.set(key, state);
      return state;
    } catch (err) {
      console.warn("[EHP Quick Favourite] Could not resolve favourite state", err);
      const fallbackCategory = getEhpQuickFavCurrentCategory(context.trigger);
      const state = { isFavorited: fallbackCategory !== null, currentCategory: fallbackCategory };
      ehpQuickFavStateCache.set(key, state);
      return state;
    }
  }

  function shouldShowRemoveForQuickFav(context, category, state) {
    return !!(state && state.isFavorited && Number(state.currentCategory) === Number(category.index));
  }

  function updateEhpQuickFavStateCache(context, state) {
    if (!context) return;
    const key = context.galleryKey || context.favUrl;
    if (!key) return;
    ehpQuickFavStateCache.set(key, state);
    ehpQuickFavPopupDocCache.delete(key);
  }

  async function submitEhpQuickFavourite(context, favcat, categoryName, menu) {
    if (!context || !context.favUrl || !menu) return;
    const trigger = context.trigger;
    menu.classList.add("is-working");
    trigger.classList.add("ehp-qfav-working");
    setEhpQuickFavStatus(menu, favcat === "favdel" ? "Removing from favourites..." : `Saving to ${categoryName}...`);

    const body = new URLSearchParams();
    body.set("favcat", String(favcat));
    body.set("favnote", "");
    if (favcat !== "favdel") body.set("apply", "Add to Favorites");
    body.set("update", "1");

    try {
      const response = await fetch(context.favUrl, {
        method: "POST",
        credentials: "include",
        headers: { "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8" },
        body: body.toString()
      });
      if (!response.ok) throw new Error(`HTTP ${response.status}`);
      const html = await response.text();
      applyEhpQuickFavReturnedUpdate(html);
      trigger.classList.remove("ehp-qfav-working");
      trigger.classList.add("ehp-qfav-updated");
      markEhpQuickFavTipDone();

      if (favcat === "favdel") {
        trigger.dataset.ehpQuickFavStatus = "removed";
        updateEhpQuickFavStateCache(context, { isFavorited: false, currentCategory: null });
        setEhpQuickFavStatus(menu, "Removed from favourites.");
      } else {
        const nextCategory = Number(favcat);
        trigger.dataset.ehpQuickFavStatus = `cat-${nextCategory}`;
        trigger.dataset.ehpQuickFavCategoryName = categoryName;
        updateEhpQuickFavStateCache(context, { isFavorited: true, currentCategory: nextCategory });
        setEhpQuickFavStatus(menu, `Saved to ${categoryName}.`);
      }
      window.setTimeout(closeEhpQuickFavMenu, 520);
    } catch (err) {
      console.error("[EHP Quick Favourite] Update failed", err);
      trigger.classList.remove("ehp-qfav-working");
      setEhpQuickFavStatus(menu, "Could not update. EH/EX may have rejected the request.");
    } finally {
      menu.classList.remove("is-working");
    }
  }

  function renderCategoryRows(menu, context, categories, state = { isFavorited: false, currentCategory: null }) {
    if (!menu) return;
    clearEhpQuickFavContent(menu);

    const list = document.createElement("div");
    list.className = "ehp-qfav-list";

    categories.forEach((category) => {
      const button = document.createElement("button");
      button.type = "button";
      button.className = "ehp-qfav-cat";
      button.classList.toggle("is-current", shouldShowRemoveForQuickFav(context, category, state));
      button.title = `Save to ${category.name}`;
      button.setAttribute("aria-label", `Save to ${category.name}`);

      const icon = makeEhpQuickFavNativeIcon(category.index, category.iconHtml);
      const name = document.createElement("span");
      name.className = "ehp-qfav-name";
      name.textContent = category.name;
      button.append(icon, name);

      if (shouldShowRemoveForQuickFav(context, category, state)) {
        const remove = document.createElement("span");
        remove.className = "ehp-qfav-inline-remove";
        remove.setAttribute("role", "button");
        remove.setAttribute("tabindex", "0");
        remove.setAttribute("aria-label", `Remove from ${category.name}`);
        remove.textContent = "Remove";
        const removeHandler = (event) => {
          event.preventDefault();
          event.stopPropagation();
          submitEhpQuickFavourite(context, "favdel", "favourites", menu);
        };
        remove.addEventListener("click", removeHandler);
        remove.addEventListener("keydown", (event) => {
          if (event.key === "Enter" || event.key === " ") removeHandler(event);
        });
        button.appendChild(remove);
      }

      button.addEventListener("click", (event) => {
        event.preventDefault();
        event.stopPropagation();
        submitEhpQuickFavourite(context, category.index, category.name, menu);
      });
      list.appendChild(button);
    });

    insertEhpQuickFavContent(menu, list);
    setEhpQuickFavStatus(menu, shouldShowEhpQuickFavTip() ? "Choose a favourite category." : "");
  }

  function createQuickFavMenuShell(context) {
    const menu = document.createElement("div");
    menu.id = "ehp-quick-fav-menu";
    menu.innerHTML = "";
    document.body.appendChild(menu);
    ehpQuickFavMenu = menu;
    ehpQuickFavActiveContext = context;

    menu.addEventListener("click", (event) => event.stopPropagation());
    menu.addEventListener("pointerdown", (event) => event.stopPropagation());
    menu.addEventListener("pointerenter", cancelEhpQuickFavCloseTimer);
    menu.addEventListener("pointerleave", () => scheduleEhpQuickFavClose(260));
    return menu;
  }

  async function renderSharedMenu(context, options = {}) {
    if (!context || !context.trigger || !context.favUrl) return;
    cancelEhpQuickFavCloseTimer();
    clearTimeout(ehpQuickFavHoverTimer);

    if (ehpQuickFavMenu && ehpQuickFavActiveContext && ehpQuickFavActiveContext.galleryKey === context.galleryKey && !options.forceReopen) {
      positionEhpQuickFavMenu(ehpQuickFavMenu, context.trigger);
      return;
    }

    closeEhpPopups();
    closeEhpQuickFavMenu();
    const menu = createQuickFavMenuShell(context);

    const cached = readEhpQuickFavCategoryCache();
    const cachedState = ehpQuickFavStateCache.get(context.galleryKey || context.favUrl) || { isFavorited: false, currentCategory: null };
    if (cached && cached.length) renderCategoryRows(menu, context, cached, cachedState);
    else renderEhpQuickFavLoading(menu);
    positionEhpQuickFavMenu(menu, context.trigger);

    try {
      const [categories, state] = await Promise.all([
        loadEhpQuickFavCategoriesForMenu(context),
        resolveEhpQuickFavState(context)
      ]);
      if (menu !== ehpQuickFavMenu) return;
      renderCategoryRows(menu, context, categories, state);
      positionEhpQuickFavMenu(menu, context.trigger);
    } catch (err) {
      console.error("[EHP Quick Favourite] Menu render failed", err);
      if (menu !== ehpQuickFavMenu) return;
      if (!menu.querySelector(":scope > .ehp-qfav-list, :scope > .ehp-qfav-loading, :scope > .ehp-qfav-error")) {
        clearEhpQuickFavContent(menu);
        const error = document.createElement("div");
        error.className = "ehp-qfav-error";
        error.textContent = "Could not load favourite categories.";
        insertEhpQuickFavContent(menu, error);
      }
      positionEhpQuickFavMenu(menu, context.trigger);
    }
  }

  function detectGalleryTrigger(root = document) {
    if (!/^\/g\//.test(location.pathname)) return [];
    const found = [];
    if (root.nodeType === 1 && root.matches && root.matches("#gdf")) found.push(root);
    if (root.querySelectorAll) found.push(...Array.from(root.querySelectorAll("#gdf")));
    return found.filter((node, pos, all) => node && all.indexOf(node) === pos);
  }


  function buildEhpQuickFavContext(trigger) {
    const favUrl = extractEhpQuickFavUrl(trigger);
    if (!favUrl) return null;
    return {
      type: "gallery",
      trigger,
      favUrl,
      galleryKey: getEhpQuickFavGalleryKeyFromUrl(favUrl)
    };
  }

  function wireEhpQuickFavTrigger(trigger) {
    if (!trigger || trigger.dataset.ehpQuickFavWired === "1") return;
    const context = buildEhpQuickFavContext(trigger);
    if (!context) return;

    trigger.dataset.ehpQuickFavWired = "1";
    trigger.dataset.ehpQuickFavUrl = context.favUrl;
    trigger.classList.add("ehp-quick-fav-trigger");
    if (!trigger.getAttribute("title")) trigger.setAttribute("title", "Quick favourite");

    trigger.addEventListener("pointerenter", () => {
      clearTimeout(ehpQuickFavHoverTimer);
      cancelEhpQuickFavCloseTimer();
      ehpQuickFavHoverTimer = window.setTimeout(() => renderSharedMenu(context), 180);
    });

    trigger.addEventListener("pointerleave", () => {
      clearTimeout(ehpQuickFavHoverTimer);
      if (ehpQuickFavMenu && ehpQuickFavActiveContext && ehpQuickFavActiveContext.galleryKey === context.galleryKey) scheduleEhpQuickFavClose(260);
    });
  }

  function scanTriggers(root = document) {
    detectGalleryTrigger(root).forEach(wireEhpQuickFavTrigger);
  }

  function initEhpQuickFavorite() {
    if (!/^\/g\//.test(location.pathname)) return;
    ensureEhpReaderStyle();
    scanTriggers(document);

    if (!ehpQuickFavObserver && document.body) {
      ehpQuickFavObserver = new MutationObserver((mutations) => {
        for (const mutation of mutations) {
          mutation.addedNodes.forEach((node) => scanTriggers(node));
        }
      });
      ehpQuickFavObserver.observe(document.body, { childList: true, subtree: true });
    }

    document.addEventListener(EHP_POPUP_CLOSE_EVENT, () => closeEhpQuickFavMenu());
    document.addEventListener("pointerdown", (event) => {
      if (ehpQuickFavMenu && !ehpQuickFavMenu.contains(event.target)) closeEhpQuickFavMenu();
    }, true);
    window.addEventListener("resize", () => closeEhpQuickFavMenu(), { passive: true });
    window.setTimeout(() => loadEhpQuickFavCategories(false).catch(() => null), 400);
  }

  let ehpGlobalTooltip = null;
  let ehpGlobalTooltipTarget = null;
  let ehpGlobalTooltipTimer = 0;
  const EHP_GLOBAL_TOOLTIP_DELAY_MS = 2000;

  function initEhpGlobalTooltipSystem() {
    ensureEhpReaderStyle();
    if (ehpGlobalTooltip || !document.body) return;

    ehpGlobalTooltip = document.createElement("div");
    ehpGlobalTooltip.id = "ehp-global-tooltip";
    ehpGlobalTooltip.className = "ehp-global-tooltip ehp-tag-tooltip";
    ehpGlobalTooltip.setAttribute("role", "tooltip");
    document.body.appendChild(ehpGlobalTooltip);

    const readTooltipText = (node) => {
      if (!node) return "";
      if (node.dataset && node.dataset.ehpTooltip) return node.dataset.ehpTooltip.trim();
      const title = node.getAttribute && node.getAttribute("title");
      if (title) {
        node.dataset.ehpTooltip = title;
        node.removeAttribute("title");
        return title.trim();
      }
      const label = node.getAttribute && node.getAttribute("aria-label");
      return label ? label.trim() : "";
    };

    const findTooltipTarget = (target) => {
      if (!target || !target.closest) return null;
      if (target.closest("#ehp-global-tooltip")) return null;

      // Tag search result capsules keep their fast local tooltip.
      // Only the add/remove favorite action inside a capsule uses the global UI tooltip style.
      const tagPanel = target.closest("#ehp-tag-system .ehp-tag-panel");
      if (tagPanel && !target.closest(".ehp-tag-action")) return null;

      const node = target.closest('[data-ehp-tooltip], [title], button[aria-label], a[aria-label], input[aria-label], select[aria-label], textarea[aria-label], .ehp-tag-action[aria-label]');
      if (!node) return null;
      if (node.closest("#ehp-tag-system .ehp-tag-panel") && !node.classList.contains("ehp-tag-action")) return null;

      const text = readTooltipText(node);
      return text ? node : null;
    };

    const clearTooltipTimer = () => {
      if (ehpGlobalTooltipTimer) {
        clearTimeout(ehpGlobalTooltipTimer);
        ehpGlobalTooltipTimer = 0;
      }
    };

    const hide = () => {
      clearTooltipTimer();
      ehpGlobalTooltipTarget = null;
      ehpGlobalTooltip.classList.remove("is-visible");
    };

    const position = (node) => {
      if (!node || !ehpGlobalTooltip) return;
      const rect = node.getBoundingClientRect();
      const tipRect = ehpGlobalTooltip.getBoundingClientRect();
      const pad = 10;
      let left = rect.left + rect.width / 2 - tipRect.width / 2;
      let top = rect.top - tipRect.height - 8;
      if (top < pad) top = rect.bottom + 8;
      left = Math.max(pad, Math.min(left, window.innerWidth - tipRect.width - pad));
      top = Math.max(pad, Math.min(top, window.innerHeight - tipRect.height - pad));
      ehpGlobalTooltip.style.left = `${left}px`;
      ehpGlobalTooltip.style.top = `${top}px`;
    };

    const showFor = (node) => {
      const text = readTooltipText(node);
      if (!text || !ehpGlobalTooltip) return;
      // Keep tooltip above reader overlay: it may be created before the overlay, so re-append before showing.
      if (ehpGlobalTooltip.parentElement) document.body.appendChild(ehpGlobalTooltip);
      ehpGlobalTooltipTarget = node;
      ehpGlobalTooltip.textContent = text;
      ehpGlobalTooltip.classList.add("is-visible");
      requestAnimationFrame(() => position(node));
    };

    const scheduleShowFor = (node) => {
      clearTooltipTimer();
      // Global hover tooltips wait 2 seconds. Tag-search capsules keep their own immediate tooltip handler.
      ehpGlobalTooltipTimer = window.setTimeout(() => {
        ehpGlobalTooltipTimer = 0;
        if (node && node.matches && document.documentElement.contains(node)) showFor(node);
      }, EHP_GLOBAL_TOOLTIP_DELAY_MS);
    };

    document.addEventListener("pointerover", (event) => {
      const node = findTooltipTarget(event.target);
      if (!node || node === ehpGlobalTooltipTarget) return;
      scheduleShowFor(node);
    }, true);

    document.addEventListener("pointerout", (event) => {
      clearTooltipTimer();
      if (!ehpGlobalTooltipTarget) return;
      const leaving = ehpGlobalTooltipTarget;
      const related = event.relatedTarget;
      if (related && leaving.contains && leaving.contains(related)) return;
      hide();
    }, true);

    document.addEventListener("focusin", (event) => {
      const node = findTooltipTarget(event.target);
      if (node) showFor(node);
    }, true);
    document.addEventListener("focusout", hide, true);
    window.addEventListener("scroll", hide, true);
    window.addEventListener("resize", hide, { passive: true });
  }


  function installEhpPermanentNativeTransparency() {
    importCSS(`
      /* Unified native border mode. When enabled, native container strokes plus #nb/.gtb plates are transparent.
         When disabled, this class disappears and EH/EX native borders/plates return, even under page color mode. */
      html.ehp-native-borderless:not(.ehp-reader-open) body #nb,
      html.ehp-native-borderless:not(.ehp-reader-open) body #nb.nosel,
      html.ehp-native-borderless:not(.ehp-reader-open) body #nb::before,
      html.ehp-native-borderless:not(.ehp-reader-open) body #nb::after,
      html.ehp-native-borderless:not(.ehp-reader-open) body #nb > div,
      html.ehp-native-borderless:not(.ehp-reader-open) body #nb > div::before,
      html.ehp-native-borderless:not(.ehp-reader-open) body #nb > div::after,
      html.ehp-native-borderless:not(.ehp-reader-open) body #nb > div > a,
      html.ehp-native-borderless:not(.ehp-reader-open) body #nb > div > a::before,
      html.ehp-native-borderless:not(.ehp-reader-open) body #nb > div > a::after,
      html.ehp-native-borderless:not(.ehp-reader-open) body .gtb,
      html.ehp-native-borderless:not(.ehp-reader-open) body .gtb::before,
      html.ehp-native-borderless:not(.ehp-reader-open) body .gtb::after,
      html.ehp-native-borderless:not(.ehp-reader-open) body .gtb > .gpc,
      html.ehp-native-borderless:not(.ehp-reader-open) body .gtb .ptt,
      html.ehp-native-borderless:not(.ehp-reader-open) body .gtb .ptt tbody,
      html.ehp-native-borderless:not(.ehp-reader-open) body .gtb .ptt tr,
      html.ehp-native-borderless:not(.ehp-reader-open) body .gtb .ptt td,
      html.ehp-native-borderless:not(.ehp-reader-open) body .gtb .ptt th,
      html.ehp-native-borderless:not(.ehp-reader-open) body .gtb .ptt a {
        background:transparent !important;
        background-color:transparent !important;
        background-image:none !important;
        border-color:transparent !important;
        outline-color:transparent !important;
        box-shadow:none !important;
      }
      html.ehp-native-borderless:not(.ehp-reader-open) body .gtb .gpc,
      html.ehp-native-borderless:not(.ehp-reader-open) body .gtb .ptt,
      html.ehp-native-borderless:not(.ehp-reader-open) body .gtb .ptt * {
        text-shadow:none !important;
      }

      html.ehp-global-themed:not(.ehp-native-borderless):not(.ehp-reader-open) :is(
        #nb, #nw, #gd1, #gd2, #gd3, #gd4, #gd5, #gdd, #gmid, #gdt, #gdf,
        #taglist, #tagmenu_act, #tagmenu_new, #rating_label,
        .ido, .gm, .g2, .g3, .g4, .g5, .g6, .g7, .g8, .g9,
        .itg, .gtr0, .gtr1, .gl1t, .gl1c, .gl2c, .gl3t, .gl3c, .gl4c,
        .glname, .glthumb, .glthumbdiv, .gdtm, .gdtl,
        .gtb, .gpc, .ptt, .ptb, .searchnav, .tc,
        table, tbody, thead, tfoot, tr, td, th, input, textarea, select, button
      ) {
        border-color:var(--ehp-border) !important;
      }
    `);
  }

  function setEhpNativeTransparencyInline(node, enabled) {
    if (!node || !node.style) return;
    const props = ["background", "background-color", "background-image", "border-color", "outline-color", "box-shadow", "text-shadow"];
    if (enabled) {
      node.dataset.ehpPermanentTransparent = "1";
      props.forEach((prop) => {
        if (prop === "text-shadow" && !(node.matches && node.matches(".gtb, .gtb *"))) return;
        node.style.setProperty(prop, prop === "background-image" ? "none" : prop === "text-shadow" ? "none" : "transparent", "important");
      });
      return;
    }
    if (node.dataset.ehpPermanentTransparent !== "1") return;
    props.forEach((prop) => node.style.removeProperty(prop));
    delete node.dataset.ehpPermanentTransparent;
  }

  function applyEhpNativeBorderMode() {
    const enabled = isEhpFeatureEnabled("nativeTheme.borderlessContainers", true);
    document.documentElement.classList.toggle("ehp-native-borderless", enabled);
    installEhpPermanentNativeTransparency();

    const nodes = document.querySelectorAll("#nb, #nb > div, #nb > div > a, .gtb, .gtb > .gpc, .gtb .ptt, .gtb .ptt tbody, .gtb .ptt tr, .gtb .ptt td, .gtb .ptt th, .gtb .ptt a");
    nodes.forEach((node) => setEhpNativeTransparencyInline(node, enabled));

    if (!applyEhpNativeBorderMode.observer) {
      const observer = new MutationObserver(() => {
        if (!isEhpFeatureEnabled("nativeTheme.borderlessContainers", true)) return;
        window.requestAnimationFrame(() => {
          document.querySelectorAll("#nb, #nb > div, #nb > div > a, .gtb, .gtb > .gpc, .gtb .ptt, .gtb .ptt tbody, .gtb .ptt tr, .gtb .ptt td, .gtb .ptt th, .gtb .ptt a").forEach((node) => setEhpNativeTransparencyInline(node, true));
        });
      });
      observer.observe(document.documentElement, { childList:true, subtree:true });
      applyEhpNativeBorderMode.observer = observer;
    }
  }

  function ensureEhpSettingsCenterStyle() {
    importCSS(`
      #ehp-settings-center { position:fixed; inset:0; z-index:2147483646; display:flex; align-items:center; justify-content:center; padding:24px; background:rgba(0,0,0,.22); font-family:"Manrope","Inter","Segoe UI",system-ui,sans-serif; color:#2d3137; box-sizing:border-box; }
      #ehp-settings-center * { box-sizing:border-box; }
      .ehp-settings-panel { width:min(700px, calc(100vw - 48px)); max-height:min(720px, calc(100vh - 48px)); overflow:auto; padding:20px; border:0; border-radius:28px; background:rgba(245,241,232,.96); color:#2d3137; box-shadow:0 18px 44px rgba(0,0,0,.22); scrollbar-width:thin; }
      .ehp-settings-panel::-webkit-scrollbar { width:8px; height:8px; }
      .ehp-settings-panel::-webkit-scrollbar-track { background:transparent; }
      .ehp-settings-panel::-webkit-scrollbar-thumb { border-radius:999px; background:rgba(45,49,55,.32); }
      .ehp-settings-head { display:flex; align-items:flex-start; justify-content:space-between; gap:14px; margin-bottom:14px; }
      .ehp-settings-title { margin:0; font:900 18px/1.2 "Manrope","Inter","Segoe UI",system-ui,sans-serif; letter-spacing:.01em; }
      .ehp-settings-subtitle { margin:6px 0 0; font:700 12px/1.45 "Manrope","Inter","Segoe UI",system-ui,sans-serif; opacity:.72; }
      .ehp-settings-close { width:38px; height:38px; border:0; border-radius:999px; display:inline-flex; align-items:center; justify-content:center; cursor:pointer; background:color-mix(in srgb, #f5f1e8, #2d3137 10%); color:#2d3137; box-shadow:0 8px 20px rgba(0,0,0,.12); }
      .ehp-settings-close svg { width:22px; height:22px; display:block; fill:none; stroke:currentColor; stroke-width:2.4; stroke-linecap:round; stroke-linejoin:round; }
      .ehp-settings-grid { display:grid; grid-template-columns:1fr 1fr; gap:12px; }
      .ehp-settings-section { border:0; border-radius:22px; padding:14px; background:color-mix(in srgb, #f5f1e8, #2d3137 6%); box-shadow:inset 0 1px 0 rgba(255,255,255,.20); }
      .ehp-settings-section h3 { margin:0 0 10px; font:900 13px/1.2 "Manrope","Inter","Segoe UI",system-ui,sans-serif; }
      .ehp-setting-row { display:flex; align-items:center; justify-content:space-between; gap:12px; padding:9px 0; border-top:1px solid rgba(45,49,55,.12); transition:opacity 140ms ease; }
      .ehp-setting-row:first-of-type { border-top:0; }
      .ehp-setting-row.is-child { padding-left:16px; }
      .ehp-setting-row.is-child .ehp-setting-name::before { content:"↳ "; opacity:.62; }
      .ehp-setting-row.is-disabled { opacity:.42; }
      .ehp-setting-copy { min-width:0; }
      .ehp-setting-name { display:block; font:850 12px/1.25 "Manrope","Inter","Segoe UI",system-ui,sans-serif; }
      .ehp-setting-desc { display:block; margin-top:3px; font:650 10.5px/1.35 "Manrope","Inter","Segoe UI",system-ui,sans-serif; opacity:.64; }
      .ehp-setting-toggle { width:46px; height:26px; border:0; border-radius:999px; padding:3px; flex:0 0 auto; cursor:pointer; background:rgba(45,49,55,.22); box-shadow:inset 0 1px 2px rgba(0,0,0,.18); }
      .ehp-setting-toggle span { width:20px; height:20px; display:block; border-radius:999px; background:#f5f1e8; box-shadow:0 4px 10px rgba(0,0,0,.18); transition:transform 140ms ease; }
      .ehp-setting-toggle.is-on { background:color-mix(in srgb, #f596aa, #2d3137 18%); }
      .ehp-setting-toggle.is-on span { transform:translateX(20px); }
      .ehp-setting-toggle:disabled { cursor:not-allowed; }
      .ehp-settings-actions { display:flex; flex-wrap:wrap; justify-content:flex-end; gap:10px; margin-top:16px; }
      .ehp-settings-actions button { border:0; border-radius:999px; padding:10px 14px; cursor:pointer; background:color-mix(in srgb, #f5f1e8, #2d3137 10%); color:#2d3137; box-shadow:0 8px 20px rgba(0,0,0,.12); font:900 12px/1 "Manrope","Inter","Segoe UI",system-ui,sans-serif; }
      .ehp-settings-actions button:hover, .ehp-settings-close:hover { transform:translateY(-1px); }
      .ehp-settings-note { margin:12px 0 0; font:700 11px/1.45 "Manrope","Inter","Segoe UI",system-ui,sans-serif; opacity:.7; }
      #ehp-settings-center,
      #ehp-settings-center * {
        --ehp-ui-surface: rgba(245,241,232,.96) !important;
        --ehp-ui-text: #2d3137 !important;
        --ehp-ui-fill: #303843 !important;
        --ehp-ui-stroke: transparent !important;
        --ehp-global-ui-bg: rgba(245,241,232,.96) !important;
        --ehp-global-ui-text: #2d3137 !important;
        --ehp-global-ui-input-bg: rgba(255,255,255,.72) !important;
        --ehp-global-ui-stroke: transparent !important;
        --ehp-suite-depth: 0 12px 30px rgba(0,0,0,.18) !important;
        --ehp-suite-depth-soft: 0 7px 18px rgba(0,0,0,.12) !important;
        color: #2d3137 !important;
        border-color: transparent !important;
        outline-color: transparent !important;
        text-shadow: none !important;
        -webkit-text-stroke: 0 transparent !important;
      }
      #ehp-settings-center { background: rgba(0,0,0,.22) !important; }
      #ehp-settings-center .ehp-settings-panel { background: rgba(245,241,232,.96) !important; color:#2d3137 !important; border:0 !important; box-shadow:0 18px 44px rgba(0,0,0,.22) !important; }
      #ehp-settings-center .ehp-settings-section { background: color-mix(in srgb, #f5f1e8, #2d3137 6%) !important; box-shadow:inset 0 1px 0 rgba(255,255,255,.20) !important; }
      #ehp-settings-center .ehp-settings-close,
      #ehp-settings-center .ehp-settings-actions button { background: color-mix(in srgb, #f5f1e8, #2d3137 10%) !important; color:#2d3137 !important; box-shadow:0 8px 20px rgba(0,0,0,.12) !important; }
      #ehp-settings-center .ehp-setting-toggle { background: rgba(45,49,55,.22) !important; box-shadow: inset 0 1px 2px rgba(0,0,0,.18) !important; }
      #ehp-settings-center .ehp-setting-toggle.is-on { background: color-mix(in srgb, #f596aa, #2d3137 18%) !important; }
      #ehp-settings-center .ehp-setting-toggle span { background:#f5f1e8 !important; box-shadow:0 4px 10px rgba(0,0,0,.18) !important; }
      @media (max-width:760px) { .ehp-settings-grid { grid-template-columns:1fr; } #ehp-settings-center { padding:14px; } .ehp-settings-panel { width:calc(100vw - 28px); max-height:calc(100vh - 28px); } }
    `);
  }

  const EHP_SETTINGS_SCHEMA = [
    { title:"Core module", items:[
      ["modules.reader", "Reader Overlay", "Open-book overlay, reading modes, zoom, thumbnails, and reader controls."],
      ["modules.infiniteLoader", "Infinite Loading", "List/gallery scrolling and gallery thumbnail loading."],
      ["modules.tagging", "Tag System", "Tag search and capsule UI."],
      ["tagging.activeGalleryTagging", "Active Gallery Tagging", "Allow tag capsules to submit tags to the gallery tag field.", "modules.tagging"],
      ["tagging.liveLookup", "Live Lookup", "Search matching gallery pages when local/catalog search is not enough.", "modules.tagging"],
      ["modules.quickFavourite", "Quick Favourite", "Gallery-page favourite category menu."]
    ]},
    { title:"Native UI", items:[
      ["nativeTheme.pageColor", "Page color control", "Floating page color picker and native page recoloring."],
      ["nativeTheme.borderlessContainers", "Transparent native borders", "Transparent native borders also make #nb and .gtb transparent. Off means visible native borders/nav/pager, regardless of page color."]
    ]}
  ];

  function applyEhpSettingsLiveUpdate(path) {
    if (path === "nativeTheme.borderlessContainers") {
      applyEhpNativeBorderMode();
      if (isEhpFeatureEnabled("nativeTheme.pageColor", true) && isEhpGlobalThemeEnabled()) applyEhpGlobalPageTheme();
      return;
    }
    if (path === "nativeTheme.pageColor") {
      if (isEhpFeatureEnabled("nativeTheme.pageColor", true)) {
        applyEhpGlobalPageTheme();
        initEhpGlobalPageThemeControls();
        observeEhpThemeMutations();
      } else {
        applyEhpGlobalPageTheme("");
        const controls = document.getElementById("ehp-page-theme-controls");
        if (controls) controls.remove();
      }
      applyEhpSuiteDepth();
      return;
    }
    if (path === "modules.tagging") {
      const root = document.getElementById("ehp-tag-system");
      if (!isEhpFeatureEnabled("modules.tagging", true)) {
        if (root) root.style.display = "none";
      } else {
        if (root) root.style.display = "";
        initEhpTagSystem();
      }
      return;
    }
    if (path === "modules.quickFavourite") {
      const menu = document.getElementById("ehp-quick-fav-menu");
      if (menu) menu.remove();
      if (isEhpFeatureEnabled("modules.quickFavourite", true)) initEhpQuickFavorite();
      return;
    }
  }

  function openEhpSettingsCenter() {
    ensureEhpSettingsCenterStyle();
    closeEhpPopups();
    const existing = document.getElementById("ehp-settings-center");
    if (existing) existing.remove();

    const root = document.createElement("div");
    root.id = "ehp-settings-center";
    const panel = document.createElement("div");
    panel.className = "ehp-settings-panel";

    const head = document.createElement("div");
    head.className = "ehp-settings-head";
    const titleWrap = document.createElement("div");
    const title = document.createElement("h2");
    title.className = "ehp-settings-title";
    title.textContent = "Comfort Suite Settings";
    const subtitle = document.createElement("p");
    subtitle.className = "ehp-settings-subtitle";
    subtitle.textContent = "Toggle modules without editing code. Reload after changing startup modules for the cleanest result.";
    titleWrap.append(title, subtitle);
    const close = document.createElement("button");
    close.type = "button";
    close.className = "ehp-settings-close";
    close.innerHTML = EHP_ICONS.remove;
    close.setAttribute("aria-label", "Close settings");
    head.append(titleWrap, close);

    const grid = document.createElement("div");
    grid.className = "ehp-settings-grid";

    const toggleSyncers = [];
    const makeToggle = (path, parentPath = null) => {
      const button = document.createElement("button");
      button.type = "button";
      button.className = "ehp-setting-toggle";
      button.setAttribute("aria-label", path);
      button.appendChild(document.createElement("span"));
      const sync = () => {
        const parentEnabled = parentPath ? isEhpFeatureEnabled(parentPath, true) : true;
        button.disabled = !parentEnabled;
        button.setAttribute("aria-disabled", String(!parentEnabled));
        button.classList.toggle("is-on", isEhpFeatureEnabled(path, true));
        const row = button.closest(".ehp-setting-row");
        if (row) row.classList.toggle("is-disabled", !parentEnabled);
      };
      toggleSyncers.push(sync);
      button.addEventListener("click", () => {
        if (button.disabled) return;
        setEhpSetting(path, !isEhpFeatureEnabled(path, true));
        applyEhpSettingsLiveUpdate(path);
        toggleSyncers.forEach((fn) => fn());
      });
      return button;
    };

    EHP_SETTINGS_SCHEMA.forEach((section) => {
      const box = document.createElement("section");
      box.className = "ehp-settings-section";
      const h = document.createElement("h3");
      h.textContent = section.title;
      box.appendChild(h);
      section.items.forEach(([path, label, desc, parentPath]) => {
        const row = document.createElement("div");
        row.className = parentPath ? "ehp-setting-row is-child" : "ehp-setting-row";
        const copy = document.createElement("div");
        copy.className = "ehp-setting-copy";
        const name = document.createElement("span");
        name.className = "ehp-setting-name";
        name.textContent = label;
        const small = document.createElement("span");
        small.className = "ehp-setting-desc";
        small.textContent = desc;
        copy.append(name, small);
        row.append(copy, makeToggle(path, parentPath));
        box.appendChild(row);
      });
      grid.appendChild(box);
    });

    toggleSyncers.forEach((fn) => fn());

    const note = document.createElement("p");
    note.className = "ehp-settings-note";
    note.textContent = "Use Reload page after changing startup modules such as Reader Overlay, Infinite Loading, Tag System, or Quick Favourite.";

    const actions = document.createElement("div");
    actions.className = "ehp-settings-actions";
    const reset = document.createElement("button");
    reset.type = "button";
    reset.textContent = "Reset settings";
    reset.addEventListener("click", () => {
      if (!confirm("Reset Comfort Suite feature settings to defaults?")) return;
      resetEhpSuiteSettings();
      root.remove();
      openEhpSettingsCenter();
    });
    const reload = document.createElement("button");
    reload.type = "button";
    reload.textContent = "Reload page";
    reload.addEventListener("click", () => location.reload());
    actions.append(reset, reload);

    panel.append(head, grid, note, actions);
    root.appendChild(panel);
    document.body.appendChild(root);

    close.addEventListener("click", () => root.remove());
    root.addEventListener("click", (event) => { if (event.target === root) root.remove(); });
    panel.addEventListener("click", (event) => event.stopPropagation());
  }

  function registerMenuCommands(spmHandle = null) {
    if (typeof _GM_registerMenuCommand !== "function") return;
    _GM_registerMenuCommand("Comfort Suite: Settings", () => openEhpSettingsCenter());
    _GM_registerMenuCommand("Comfort Suite: Open Reader", () => {
      if (spmHandle && typeof spmHandle.open === "function") spmHandle.open();
      else alert("Reader module is disabled or unavailable on this page.");
    });
  }

  function initEhpModuleRegistry(modules, context) {
    modules.forEach((module) => {
      try {
        if (module.enabled && !module.enabled(context)) return;
        if (module.matches && !module.matches(context)) return;
        module.init(context);
      } catch (err) {
        console.error(`[Comfort Suite] ${module.key || "module"} failed`, err);
      }
    });
  }


  (function main() {
    const mainBox = document.querySelector("#gdt");
    const isGalleryPage = location.pathname.startsWith("/g/");
    const context = { mainBox, isGalleryPage, spmHandle: null };

    const modules = [
      {
        key: "nativeTheme",
        init: () => {
          applyEhpNativeBorderMode();
          applyEhpSuiteDepth();
          setEhpInputModeClass();
          if (isEhpFeatureEnabled("nativeTheme.pageColor", true)) {
            applyEhpGlobalPageTheme();
            observeEhpThemeMutations();
          }
        }
      },
      {
        key: "globalTopButton",
        init: () => initEhpGlobalTopButton()
      },
      {
        key: "pageThemeControls",
        enabled: () => isEhpFeatureEnabled("nativeTheme.pageColor", true),
        init: () => initEhpGlobalPageThemeControls()
      },
      {
        key: "tooltips",
        init: () => initEhpGlobalTooltipSystem()
      },
      {
        key: "infiniteLoader",
        enabled: () => isEhpFeatureEnabled("modules.infiniteLoader", true),
        init: (ctx) => initSimpleInfiniteContentLoader({
          enableListInfiniteScroll: true,
          enableGalleryThumbnails: ctx.isGalleryPage
        })
      },
      {
        key: "tagging",
        enabled: () => isEhpFeatureEnabled("modules.tagging", true),
        init: () => initEhpTagSystem()
      },
      {
        key: "quickFavourite",
        enabled: () => isEhpFeatureEnabled("modules.quickFavourite", true),
        matches: (ctx) => ctx.isGalleryPage,
        init: () => initEhpQuickFavorite()
      },
      {
        key: "reader",
        enabled: () => isEhpFeatureEnabled("modules.reader", true),
        matches: (ctx) => !!ctx.mainBox,
        init: (ctx) => {
          const urlP = new URLSearchParams(window.location.search).get("p");
          store.currPage = urlP ? parseInt(urlP, 10) + 1 : 1;
          const initLinks = Array.from(qa("#gdt a", document)).map((a) => a.href);
          store.perPage = initLinks.length || 20;

          const galleryId = window.location.pathname;
          const savedTotal = localStorage.getItem(`eh_total_${galleryId}`);
          if (savedTotal && parseInt(savedTotal, 10) > 0) {
            store.totalPage = parseInt(savedTotal, 10);
          } else {
            store.totalPage = calcTotal(document, initLinks.length);
            localStorage.setItem(`eh_total_${galleryId}`, String(store.totalPage));
          }

          const range = parseImageRange(document);
          if (range) {
            store.imageOffset = range.start - 1;
            store.totalImages = range.total;
          } else {
            store.imageOffset = (store.currPage - 1) * store.perPage;
            store.totalImages = store.totalPage * store.perPage;
          }

          store.nextUrl = getNextUrl(document);
          store.prevUrl = getPrevUrl(document);

          let hiddenBox = document.querySelector("#gdt-hidden");
          if (!hiddenBox) {
            hiddenBox = document.createElement("div");
            hiddenBox.id = "gdt-hidden";
            hiddenBox.style.display = "none";
            document.body.appendChild(hiddenBox);
          }
          processBatch(initLinks, store.currPage);
          setupPrefetchListener();

          ctx.spmHandle = initSinglePageMode();
          createFloatControl(ctx.spmHandle);

          const targetHash = (location.hash || "").match(/page-(\d+)/);
          if (targetHash) {
            const globalPage = parseInt(targetHash[1], 10);
            const localIndex = globalPage - 1 - store.imageOffset;
            if (localIndex >= 0) store.currentImageIndex = localIndex;
          }
        }
      }
    ];

    initEhpModuleRegistry(modules, context);
    registerMenuCommands(context.spmHandle);
  })();


})();