☰

ExHentai Reader Pro

E站 阅读加强 自适应点对点缩放+预载图片 v4 — 嵌入原网页,保留原有样式,向下滚动自动加载,失败自动重试,阅读记忆

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴、Greasemonkey 油猴子 或 Violentmonkey 暴力猴,才能安装此脚本。

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

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴 或 Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴 或 Userscripts ,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展后才能安装此脚本。

(我已经安装了用户脚本管理器,让我安装!)

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

(我已经安装了用户样式管理器,让我安装!)

// ==UserScript==
// @name         ExHentai Reader Pro
// @namespace    EHReaderPro
// @version      4.5.0
// @description  E站 阅读加强 自适应点对点缩放+预载图片 v4 — 嵌入原网页,保留原有样式,向下滚动自动加载,失败自动重试,阅读记忆
// @author       EHReader
// @match        https://exhentai.org/s/*
// @match        https://e-hentai.org/s/*
// @run-at       document-end
// @grant        none
// ==/UserScript==

(function () {
"use strict";

// =================================================
// 全局配置与状态
// =================================================

const EHR = {
  version: "4.5.0",

  config: {
    mode: "auto",        // pixel=1:1像素(可横向滚动) | auto=自适应可视宽
    scale: 100,           // 缩放百分比
    preloadDown: 4,       // 向下预载页数(相对「当前可视的最后一页」)
    preloadUp: 1,         // 向上预载页数(仅滚动到顶触发)
    cacheLimit: 500,      // 超出此范围的页释放内存
    showImgInfo: true,    // 是否显示图片信息
  },

  state: {
    gid: "",
    startPage: 1,
    startKey: "",
    activePage: 1,
    totalPages: 0,
    pageKeys: new Map(),
    pageData: new Map(),
    loadedPages: new Set(),
    loadingPages: new Set(),
    container: null,
    baseI1Width: 0,       // 原网页初始灰色背景面板基准宽度
    currentI1Width: 0,    // 当前 #i1 应用的宽度
  },
};

const LINK_RE = /\/s\/([^/]+)\/(\d+)-(\d+)/;

// =================================================
// 配置持久化
// =================================================

function loadConfig() {
  try {
    const saved = JSON.parse(localStorage.getItem("EHReader_config") || "{}");
    Object.assign(EHR.config, saved);
  } catch (e) {}
}

function saveConfig() {
  localStorage.setItem("EHReader_config", JSON.stringify(EHR.config));
}

loadConfig();

// =================================================
// IndexedDB URL缓存(LRU,读不写、淘汰节流)
// =================================================

const EHCache = (() => {
  const DB_NAME = "EHReaderURLCache";
  const ST_NAME = "pages";
  const TOUCH_INTERVAL = 10 * 60 * 1000; // 记录超过 10 分钟未更新 ts 才回写
  const EVICT_EVERY = 25;                 // 每 25 次 put 才检查一次淘汰
  let _db = null;
  let _putCount = 0;

  async function openDB() {
    if (_db) return _db;
    return new Promise((res, rej) => {
      // v3:records 含 url/info/pageKey 字段,旧版记录兼容(缺字段默认空串)
      const req = indexedDB.open(DB_NAME, 3);
      req.onupgradeneeded = e => {
        const db = e.target.result;
        if (!db.objectStoreNames.contains(ST_NAME)) {
          const st = db.createObjectStore(ST_NAME, { keyPath: "key" });
          st.createIndex("ts", "ts", { unique: false });
        }
      };
      req.onsuccess = e => { _db = e.target.result; res(_db); };
      req.onerror   = e => rej(e.target.error);
    });
  }

  async function get(gid, page) {
    try {
      const db  = await openDB();
      const key = gid + "_" + page;
      const rec = await new Promise(res => {
        const req = db.transaction(ST_NAME, "readonly").objectStore(ST_NAME).get(key);
        req.onsuccess = e => res(e.target.result || null);
        req.onerror   = () => res(null);
      });
      if (!rec) return null;
      // LRU 时间戳只在过期时回写,避免每次读取都开写事务
      if (Date.now() - (rec.ts || 0) > TOUCH_INTERVAL) {
        rec.ts = Date.now();
        try { db.transaction(ST_NAME, "readwrite").objectStore(ST_NAME).put(rec); } catch (e) {}
      }
      return { url: rec.url, info: rec.info || "", pageKey: rec.pageKey || "" };
    } catch (e) { return null; }
  }

  async function put(gid, page, url, info, pageKey) {
    try {
      const db  = await openDB();
      const key = gid + "_" + page;
      return new Promise(res => {
        const tx = db.transaction(ST_NAME, "readwrite");
        const st = tx.objectStore(ST_NAME);
        st.put({ key, url, info: info || "", pageKey: pageKey || "", ts: Date.now() });
        tx.oncomplete = () => {
          if (++_putCount % EVICT_EVERY === 0) evict(db).then(res);
          else res();
        };
        tx.onerror = () => res();
      });
    } catch (e) {}
  }

  async function evict(db) {
    const maxRows = Math.max(10, EHR.config.cacheLimit || 500);
    return new Promise(res => {
      const tx  = db.transaction(ST_NAME, "readwrite");
      const st  = tx.objectStore(ST_NAME);
      const cnt = st.count();
      cnt.onsuccess = () => {
        let del = cnt.result - maxRows;
        if (del <= 0) return res();
        st.index("ts").openCursor().onsuccess = e => {
          const cur = e.target.result;
          if (cur && del-- > 0) { cur.delete(); cur.continue(); }
          else res();
        };
      };
      cnt.onerror = () => res();
      tx.onerror = () => res();
    });
  }

  async function getCount() {
    try {
      const db = await openDB();
      return new Promise(res => {
        const req = db.transaction(ST_NAME, "readonly").objectStore(ST_NAME).count();
        req.onsuccess = e => res(e.target.result);
        req.onerror   = () => res(0);
      });
    } catch (e) { return 0; }
  }

  async function remove(gid, page) {
    try {
      const db  = await openDB();
      const key = gid + "_" + page;
      return new Promise(res => {
        const tx = db.transaction(ST_NAME, "readwrite");
        tx.objectStore(ST_NAME).delete(key);
        tx.oncomplete = () => res();
        tx.onerror    = () => res();
      });
    } catch (e) {}
  }

  return { get, put, remove, getCount };
})();

// =================================================
// URL 解析
// =================================================

function parseURL(href) {
  const m = (href || location.href).match(LINK_RE);
  if (m) return { key: m[1], gid: m[2], page: Number(m[3]) };
  return { key: "", gid: "", page: 1 };
}

const _cur = parseURL();
EHR.state.gid        = _cur.gid;
EHR.state.startPage  = _cur.page;
EHR.state.startKey   = _cur.key;
EHR.state.activePage = _cur.page;
if (_cur.key) EHR.state.pageKeys.set(_cur.page, _cur.key);

// =================================================
// 从 DOM 采集页码→key 映射
// =================================================

function harvestPageKeys() {
  document.querySelectorAll("a[href]").forEach(a => {
    const m = a.href.match(LINK_RE);
    if (m) {
      const page = Number(m[3]);
      if (!EHR.state.pageKeys.has(page)) EHR.state.pageKeys.set(page, m[1]);
    }
  });
}

// =================================================
// 检测总页数
// =================================================

function detectTotalPages() {
  const sn = document.querySelector(".sn");
  if (sn) {
    const m = sn.textContent.match(/of\s+(\d+)/i);
    if (m) return Number(m[1]);
    const spans = sn.querySelectorAll("span");
    spans.forEach(s => {
      const n = s.textContent.match(/\d+/);
      if (n && Number(n[0]) > 1) EHR.state.totalPages = Math.max(EHR.state.totalPages, Number(n[0]));
    });
    if (EHR.state.totalPages > 1) return EHR.state.totalPages;
  }
  const scripts = document.querySelectorAll("script:not([src])");
  for (const s of scripts) {
    const m = s.textContent.match(/var\s+prl\s*=\s*(\d+)/);
    if (m && Number(m[1]) < 9999) return Number(m[1]);
  }
  return 0;
}

function extractTotalPagesFromDoc(doc) {
  const scripts = doc.querySelectorAll("script:not([src])");
  for (const s of scripts) {
    const m = s.textContent.match(/var\s+prl\s*=\s*(\d+)/);
    if (m && Number(m[1]) < 9999) return Number(m[1]);
  }
  return 0;
}

// =================================================
// 构造页面 URL
// =================================================

function buildPageURL(page) {
  const key = EHR.state.pageKeys.get(page);
  if (!key) return null;
  return `${location.origin}/s/${key}/${EHR.state.gid}-${page}`;
}

// =================================================
// HTTP fetch,带超时与重试(超时防止挂起的连接永久占用并发槽)
// =================================================

async function fetchDoc(url, retries = 2) {
  for (let i = 0; i <= retries; i++) {
    const ctrl  = new AbortController();
    const timer = setTimeout(() => ctrl.abort(), 20000);
    try {
      const res = await fetch(url, { credentials: "include", signal: ctrl.signal });
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      const text = await res.text();
      return new DOMParser().parseFromString(text, "text/html");
    } catch (e) {
      if (i === retries) return null;
      await new Promise(r => setTimeout(r, 600));
    } finally {
      clearTimeout(timer);
    }
  }
  return null;
}

// =================================================
// 并发控制 Semaphore(限制同时 fetch 数;按优先级出队,离当前阅读页近的先请求)
// =================================================

const _sem = (() => {
  const MAX = 3;
  let _running = 0;
  const _queue = [];
  function next() {
    while (_running < MAX && _queue.length) {
      let bi = 0, bp = _queue[0].prio();
      for (let i = 1; i < _queue.length; i++) {
        const p = _queue[i].prio();
        if (p < bp) { bp = p; bi = i; }
      }
      const job = _queue.splice(bi, 1)[0];
      _running++;
      let r;
      try { r = Promise.resolve(job.fn()); } catch (e) { r = Promise.reject(e); }
      r.then(job.res, job.rej).finally(() => { _running--; next(); });
    }
  }
  return {
    run(fn, prio) {
      const pf = typeof prio === "function" ? prio : () => (prio || 0);
      return new Promise((res, rej) => { _queue.push({ fn, res, rej, prio: pf }); next(); });
    }
  };
})();

function pagePrio(page) {
  return () => Math.abs(page - EHR.state.activePage);
}

// =================================================
// 解析单图页,获取图片URL、文件信息、nl 重载令牌、存储相邻页key
// =================================================

async function parsePage(url) {
  const doc = await fetchDoc(url);
  if (!doc) return null;

  // 采集相邻页 key:精确选择器优先,采集不到时降级为全量遍历(兼容改版)
  {
    let found = 0;
    for (const sel of ["#i2 a[href]", "#i3 a[href]", "#i4 a[href]", "#pnp a[href]", "a[onclick*='nl(']"]) {
      doc.querySelectorAll(sel).forEach(a => {
        const m = a.href && a.href.match(LINK_RE);
        if (m) { found++; const pg = Number(m[3]); if (!EHR.state.pageKeys.has(pg)) EHR.state.pageKeys.set(pg, m[1]); }
      });
    }
    if (!found) {
      doc.querySelectorAll("a[href]").forEach(a => {
        const m = a.href.match(LINK_RE);
        if (m) { const pg = Number(m[3]); if (!EHR.state.pageKeys.has(pg)) EHR.state.pageKeys.set(pg, m[1]); }
      });
    }
  }

  // 更新总页数
  if (!EHR.state.totalPages) {
    const t = extractTotalPagesFromDoc(doc);
    if (t) { EHR.state.totalPages = t; updateProgress(); }
  }

  // 找图片(多选择器兼容改版)
  const img = doc.querySelector("#img")
    || doc.querySelector("img[id='img']")
    || doc.querySelector("#i3 img")
    || doc.querySelector(".image-container img")
    || doc.querySelector("img[src*='ehgt.org']")
    || doc.querySelector("img[src*='hath.network']")
    || doc.querySelector("img[src*='exhentai.org/t/']")
    || doc.querySelector("img[src*='e-hentai.org/t/']");
  if (!img) return null;
  const imgSrc = img.src || img.dataset.src || img.getAttribute("data-src") || "";
  if (!imgSrc) return null;

  const imgInfo = extractImgInfo(doc);

  // 「图片加载失败?换一个服务器」令牌:onclick="return nl('xxxx')"
  let nl = "";
  const lf = doc.querySelector("#loadfail");
  if (lf) {
    const m = (lf.getAttribute("onclick") || "").match(/nl\(\s*['"]([^'"]+)['"]\s*\)/);
    if (m) nl = m[1];
  }

  return { url: imgSrc, info: imgInfo, nl };
}

// 从文档中提取图片信息字符串("filename :: W x H :: size")
function extractImgInfo(doc) {
  const candidates = [
    "#i4 > div:first-child",
    "#i4 div",
    "#i2 > div:last-child",
    "#i2 div",
    ".image-info",
    "[data-src] + div",
    "#img ~ div",
  ];
  const infoRE = /[\w\-. ]+\.\w{2,5}\s*::\s*\d+\s*x\s*\d+\s*::\s*[\d.,]+\s*[KMGkmg]?i?[Bb]/;

  for (const sel of candidates) {
    try {
      const els = doc.querySelectorAll(sel);
      for (const el of els) {
        const txt = el.textContent.replace(/\s+/g, " ").trim();
        if (infoRE.test(txt)) return txt.match(infoRE)[0];
      }
    } catch (e) {}
  }
  const bodyTxt = (doc.body || doc.documentElement).textContent.replace(/\s+/g, " ");
  const m = bodyTxt.match(infoRE);
  if (m) return m[0];
  const imgEl = doc.querySelector("#img");
  if (imgEl && imgEl.alt) return imgEl.alt;
  return "";
}

function extractCurrentImgInfo() {
  return extractImgInfo(document);
}

// =================================================
// 画廊索引:一次请求拿到约 20~40 页的 key,使各页可并行解析
// (原先只能靠「解析第 N 页 → 得到第 N+1 页 key」逐页串行,是向下加载慢的主因)
// =================================================

const GAL = { base: "", perPage: 0, done: new Set(), inflight: new Map(), fails: 0, disabled: false };

function initGallery() {
  const href = extractGalleryBackLink();
  if (!href) { GAL.disabled = true; return; }
  try {
    const u = new URL(href, location.href);
    u.search = ""; u.hash = "";
    GAL.base = u.href;
  } catch (e) { GAL.disabled = true; }
}

function galleryLoadIdx(idx) {
  if (GAL.disabled || GAL.done.has(idx)) return Promise.resolve();
  if (GAL.inflight.has(idx)) return GAL.inflight.get(idx);

  const p = (async () => {
    const url = GAL.base + (idx ? "?p=" + idx : "");
    const doc = await _sem.run(() => fetchDoc(url, 1), () => 0);
    const pages = new Set();
    if (doc) {
      doc.querySelectorAll("a[href*='/s/']").forEach(a => {
        const m = a.href.match(LINK_RE);
        if (m && m[2] === EHR.state.gid) {
          const pg = Number(m[3]);
          pages.add(pg);
          if (!EHR.state.pageKeys.has(pg)) EHR.state.pageKeys.set(pg, m[1]);
        }
      });
    }
    if (!pages.size) {
      // 请求失败或页面结构不符(如内容警告页):连续失败 3 次后停用,回退到逐页发现
      if (++GAL.fails >= 3) GAL.disabled = true;
      return;
    }
    GAL.fails = 0;
    GAL.done.add(idx);
    if (idx === 0 && !GAL.perPage) GAL.perPage = pages.size;

    if (!EHR.state.totalPages) {
      const gpc = doc.querySelector(".gpc");
      const m = gpc && gpc.textContent.match(/of\s+([\d,]+)\s+images?/i);
      if (m) { EHR.state.totalPages = Number(m[1].replace(/,/g, "")); updateProgress(); }
    }
  })();

  GAL.inflight.set(idx, p);
  const clear = () => GAL.inflight.delete(idx);
  p.then(clear, clear);
  return p;
}

// 确保 pageKeys 里有目标页的 key:先画廊索引,失败再逐页发现
async function ensureKey(page) {
  if (EHR.state.pageKeys.has(page)) return;
  if (!GAL.disabled) {
    try {
      if (!GAL.perPage) await galleryLoadIdx(0);
      if (!EHR.state.pageKeys.has(page) && GAL.perPage) {
        await galleryLoadIdx(Math.floor((page - 1) / GAL.perPage));
      }
    } catch (e) {}
  }
  if (!EHR.state.pageKeys.has(page)) await discoverKey(page);
}

// =================================================
// 单图页网络请求(in-flight 去重,结果写入内存缓存)
// =================================================

const _netInflight = new Map();

function fetchPageNet(page, nl) {
  nl = nl || "";
  const k = page + "|" + nl;
  if (_netInflight.has(k)) return _netInflight.get(k);
  const base = buildPageURL(page);
  if (!base) return Promise.resolve(null);
  const url = nl ? base + (base.includes("?") ? "&" : "?") + "nl=" + encodeURIComponent(nl) : base;

  const p = _sem.run(() => parsePage(url), pagePrio(page)).then(d => {
    if (d) {
      d.pageKey = EHR.state.pageKeys.get(page) || "";
      storePageData(page, d);
    }
    return d;
  }).catch(() => null);

  _netInflight.set(k, p);
  const clear = () => _netInflight.delete(k);
  p.then(clear, clear);
  return p;
}

function storePageData(page, data) {
  EHR.state.pageData.set(page, data);
  const maxCache = (EHR.config.cacheLimit || 500) * 2;
  if (EHR.state.pageData.size > maxCache) {
    const cur = EHR.state.activePage;
    const keys = [...EHR.state.pageData.keys()]
      .sort((a, b) => Math.abs(a - cur) - Math.abs(b - cur));
    keys.slice(maxCache).forEach(k => EHR.state.pageData.delete(k));
  }
}

// =================================================
// 解析某页数据(内存 → in-flight 去重 → IDB → 取 key → fetch)
// opts.fresh:跳过内存/IDB 缓存;opts.nl:使用「换服务器」令牌
// =================================================

const _inflightMap = new Map();

async function resolvePage(page, opts) {
  const fresh = !!(opts && opts.fresh);
  const nl    = (opts && opts.nl) || "";

  if (!fresh) {
    if (EHR.state.pageData.has(page)) return EHR.state.pageData.get(page);
    if (_inflightMap.has(page)) return _inflightMap.get(page);
  }

  const promise = (async () => {
    if (!fresh) {
      const cached = await EHCache.get(EHR.state.gid, page);
      if (cached && cached.url) {
        if (cached.pageKey && !EHR.state.pageKeys.has(page)) {
          EHR.state.pageKeys.set(page, cached.pageKey);
        }
        const data = { url: cached.url, info: cached.info || "", pageKey: cached.pageKey || "", nl: "" };
        EHR.state.pageData.set(page, data);
        return data;
      }
    }
    await ensureKey(page);
    // ensureKey/discoverKey 过程中可能已顺带解析过本页
    if (!fresh && EHR.state.pageData.has(page)) return EHR.state.pageData.get(page);
    return fetchPageNet(page, nl);
  })();

  if (!fresh) {
    _inflightMap.set(page, promise);
    const clear = () => { if (_inflightMap.get(page) === promise) _inflightMap.delete(page); };
    promise.then(clear, clear);
  }
  return promise;
}

// 逐页发现 key 的兜底方案(画廊索引不可用时)
const _discoverInflight = new Map();

async function discoverKey(targetPage) {
  if (EHR.state.pageKeys.has(targetPage)) return;
  if (_discoverInflight.has(targetPage)) return _discoverInflight.get(targetPage);
  if (!EHR.state.pageKeys.size) return;

  const p = (async () => {
    let nearest = -1, minDist = Infinity;
    EHR.state.pageKeys.forEach((_, pg) => {
      const d = Math.abs(pg - targetPage);
      if (d < minDist) { minDist = d; nearest = pg; }
    });
    if (nearest === -1) return;
    let cur = nearest;
    const dir = targetPage > nearest ? 1 : -1;
    const steps = Math.abs(targetPage - nearest) + 1;
    for (let i = 0; i < steps; i++) {
      if (EHR.state.pageKeys.has(targetPage)) break;
      const d = await fetchPageNet(cur);
      if (!d) break;
      cur += dir;
    }
  })();

  _discoverInflight.set(targetPage, p);
  try { await p; } finally { _discoverInflight.delete(targetPage); }
}

// =================================================
// 提取"返回图库预览"链接 href
// =================================================

function extractGalleryBackLink() {
  const imgInSb = document.querySelector("#i5 a[href*='/g/']");
  if (imgInSb) return imgInSb.href;
  const bImg = document.querySelector('a[href*="/g/"] img[src*="img/b.png"]');
  if (bImg) return bImg.closest("a").href;
  return "";
}

// =================================================
// 初始化原页面:隐藏导航/按钮/图库链接等,嵌入容器
// =================================================

function patchOriginalPage() {
  const hide = sel => { const el = document.querySelector(sel); if (el) el.style.display = "none"; };
  hide("#i2");
  hide("#i4");
  hide("#i5");
  hide("#i6");
  hide("#i3 > a");
  hide("#i3 > #img");

  const h1 = document.querySelector("#i1 h1");
  if (h1) h1.style.paddingBottom = "6px";

  document.body.style.padding = "0";
  document.documentElement.style.overflow = "auto";
  document.body.style.overflow = "auto";

  // 解除原网页容器宽度锁定(起始页小图会把面板锁窄,后续大图被裁)
  resetAncestorWidthLock();
}

function captureBaseI1Width() {
  const i1 = document.querySelector("#i1");
  if (i1) {
    const sw = parseFloat(i1.style.width);
    if (sw && sw > 0) {
      EHR.state.baseI1Width = sw;
    } else {
      const ow = i1.offsetWidth;
      if (ow && ow > 0) EHR.state.baseI1Width = ow;
    }
  }
}

function resetAncestorWidthLock() {
  captureBaseI1Width();
  const i1 = document.querySelector("#i1");
  if (i1) {
    i1.style.setProperty("box-sizing", "border-box", "important");
    i1.style.setProperty("max-width", "none", "important");
    i1.style.marginLeft  = "auto";
    i1.style.marginRight = "auto";
    if (EHR.state.baseI1Width > 0) {
      EHR.state.currentI1Width = EHR.state.baseI1Width;
      i1.style.setProperty("width", EHR.state.baseI1Width + "px", "important");
      i1.style.setProperty("min-width", EHR.state.baseI1Width + "px", "important");
    }
  }
  const i3 = document.querySelector("#i3");
  if (i3) {
    i3.style.setProperty("width", "auto", "important");
    i3.style.setProperty("max-width", "none", "important");
    i3.style.setProperty("min-width", "0", "important");
    i3.style.marginLeft  = "auto";
    i3.style.marginRight = "auto";
  }
}

// 持续防御:E站原生脚本可能在图片加载后重新给 #i1 写回固定宽度
function setupAncestorWidthGuard() {
  const i1 = document.querySelector("#i1");
  if (!i1) return;

  const mo = new MutationObserver(() => {
    if (EHR.state.currentI1Width > 0) {
      const curW = i1.style.getPropertyValue("width");
      const expected = EHR.state.currentI1Width + "px";
      if (curW !== expected) {
        i1.style.setProperty("width", expected, "important");
        i1.style.setProperty("min-width", expected, "important");
        i1.style.setProperty("max-width", "none", "important");
      }
    }
  });
  mo.observe(i1, { attributes: true, attributeFilter: ["style"] });
}

// =================================================
// 创建阅读器容器:直接插入 #i3 之后,在 #i1 内部
// =================================================

function createReaderContainer() {
  const container = document.createElement("div");
  container.id = "EHR_container";

  const i3 = document.querySelector("#i3");
  if (i3 && i3.parentNode) {
    i3.parentNode.insertBefore(container, i3.nextSibling);
  } else {
    const i1 = document.querySelector("#i1");
    if (i1) i1.appendChild(container);
    else document.body.appendChild(container);
  }

  EHR.state.container = container;
  return container;
}

// =================================================
// 已加载页登记(同步维护最大页码,避免每次遍历 Set)
// =================================================

let _maxLoaded = 0;
const _failedPages = new Set();

function markLoaded(page) {
  EHR.state.loadedPages.add(page);
  if (page > _maxLoaded) _maxLoaded = page;
}

function makeBox(page) {
  const box = document.createElement("div");
  box.className = "EHR_page";
  box.dataset.page = page;
  return box;
}

// =================================================
// 把当前页的主图移入容器(第一张)
// =================================================

function moveCurrentImage() {
  const imgEl = document.querySelector("#i3 #img") ||
                document.querySelector("#i3 a > img") ||
                document.querySelector("#img");

  const src  = imgEl ? (imgEl.src || imgEl.dataset.src || "") : "";
  const info = extractCurrentImgInfo();

  if (src) EHR.state.pageData.set(EHR.state.startPage, { url: src, info, pageKey: EHR.state.startKey, nl: "" });

  const box = makeBox(EHR.state.startPage);

  const img = new Image();
  img.referrerPolicy = "origin";
  img.src = src;
  img.style.display = "none";
  img.onload = () => {
    img.style.display = "";
    applyImageMode(img);
  };
  img.onerror = () => {
    img.alt = "当前页图片加载失败";
    img.style.display = "";
  };
  box.appendChild(img);

  if (EHR.config.showImgInfo && info) {
    const infoDiv = createImgInfoBar(info);
    infoDiv.dataset.infoPage = EHR.state.startPage;
    box.appendChild(infoDiv);
  }

  EHR.state.container.appendChild(box);
  markLoaded(EHR.state.startPage);
  observeBlock(box);
}

// =================================================
// 图片信息行
// =================================================

function createImgInfoBar(infoText) {
  const orig = document.querySelector("#i2 > div:last-child") ||
               document.querySelector("#i4 > div:first-child");
  let div;
  if (orig) {
    div = orig.cloneNode(false);
  } else {
    div = document.createElement("div");
  }
  div.className = (div.className ? div.className + " " : "") + "EHR_info_bar";
  div.textContent = infoText || "";
  div.style.display = EHR.config.showImgInfo ? "" : "none";
  return div;
}

function refreshInfoBars() {
  document.querySelectorAll(".EHR_info_bar").forEach(bar => {
    bar.style.display = EHR.config.showImgInfo ? "" : "none";
  });
}

// =================================================
// 加载框 & 失败状态
// =================================================

function createLoadingBox(page) {
  const div = document.createElement("div");
  div.className = "EHR_loading";
  div.innerHTML = `
    <div class="EHR_spinner"></div>
    <span>正在获取第 ${page} 页...</span>
  `;
  return div;
}

function setErrorState(loadingDiv, page, retryFn) {
  loadingDiv.innerHTML = `
    <div class="EHR_err_icon">!</div>
    <span>第 ${page} 页加载失败</span>
  `;
  if (typeof retryFn === "function") {
    const btn = document.createElement("button");
    btn.className = "EHR_retry_btn";
    btn.textContent = "重新加载";
    btn.onclick = () => {
      btn.remove();
      retryFn();
    };
    loadingDiv.appendChild(btn);
  }
}

// =================================================
// 页面块:数据就绪后填充图片与信息行(向上/向下共用)
// =================================================

function startLoad(box, page, data, autoRetries, onImgLoaded) {
  if (autoRetries === undefined) autoRetries = 3;

  box.querySelectorAll(":scope > img").forEach(i => i.remove());
  box.querySelectorAll(":scope > .EHR_loading").forEach(i => i.remove());

  const loadingEl = createLoadingBox(page);
  box.insertBefore(loadingEl, box.querySelector(".EHR_info_bar") || null);

  const img = new Image();
  img.referrerPolicy = "origin";
  img.decoding = "async";
  img.style.display = "none";
  box.insertBefore(img, loadingEl);

  img.onload = () => {
    loadingEl.remove();
    img.style.display = "";
    applyImageMode(img);
    EHCache.put(EHR.state.gid, page, data.url, data.info, data.pageKey || "").catch(() => {});
    if (page === EHR.state.activePage) applyPageUrl(page);
    if (typeof onImgLoaded === "function") onImgLoaded();
    ensureAhead();
  };

  img.onerror = async () => {
    img.remove();
    if (autoRetries > 0) {
      const retryLeft = autoRetries - 1;
      const span = loadingEl.querySelector("span");
      if (span) span.textContent = `正在重新获取第 ${page} 页... (剩余重试 ${retryLeft + 1} 次)`;
      // 清除缓存后重新获取;若页面提供了 nl 令牌则请求另一个图片服务器
      EHR.state.pageData.delete(page);
      await EHCache.remove(EHR.state.gid, page);
      let newData = null;
      try { newData = await resolvePage(page, { fresh: true, nl: data.nl || "" }); } catch (e) {}
      if (newData) {
        data.url  = newData.url;
        data.info = newData.info;
        data.nl   = newData.nl || "";
        startLoad(box, page, data, retryLeft, onImgLoaded);
      } else {
        setErrorState(loadingEl, page, () => startLoad(box, page, data, 3, onImgLoaded));
      }
    } else {
      setErrorState(loadingEl, page, () => startLoad(box, page, data, 3, onImgLoaded));
    }
  };

  img.src = data.url;
}

function fillBlock(box, page, data) {
  if (data.pageKey) EHR.state.pageKeys.set(page, data.pageKey);
  if (page === EHR.state.activePage) applyPageUrl(page);

  if (EHR.config.showImgInfo && data.info && !box.querySelector(".EHR_info_bar")) {
    const infoDiv = createImgInfoBar(data.info);
    infoDiv.dataset.infoPage = page;
    box.appendChild(infoDiv);
  }

  startLoad(box, page, data, 3, () => {
    if (EHR.config.showImgInfo && data.info && !box.querySelector(".EHR_info_bar")) {
      const infoDiv = createImgInfoBar(data.info);
      infoDiv.dataset.infoPage = page;
      box.appendChild(infoDiv);
    }
  });
}

// =================================================
// 向下加载:先同步插入占位块(页面高度立即延伸、可见 loading),
// 再并行解析;每页独立完成,不再等待整批 Promise.all
// =================================================

function spawnDownBlock(page) {
  const box = makeBox(page);
  markLoaded(page);
  EHR.state.container.appendChild(box);
  observeBlock(box);
  requestBlock(box, page, 0, false);
}

async function requestBlock(box, page, attempt, fresh) {
  box.querySelectorAll(":scope > .EHR_loading").forEach(e => e.remove());
  const loadingEl = createLoadingBox(page);
  box.appendChild(loadingEl);
  if (attempt > 0) {
    const span = loadingEl.querySelector("span");
    if (span) span.textContent = `正在重新获取第 ${page} 页...`;
  }

  EHR.state.loadingPages.add(page);
  _failedPages.delete(page);
  let data = null;
  try { data = await resolvePage(page, fresh ? { fresh: true } : undefined); } catch (e) {}
  EHR.state.loadingPages.delete(page);

  if (!data) {
    if (attempt < 2) {
      setTimeout(() => requestBlock(box, page, attempt + 1, false), 1500 * (attempt + 1));
      return;
    }
    _failedPages.add(page);
    setErrorState(loadingEl, page, () => requestBlock(box, page, 0, true));
    return;
  }

  loadingEl.remove();
  fillBlock(box, page, data);
  ensureAhead();
}

// 保证「当前可视的最后一页」之后有 preloadDown 页已发起加载。
// 由 IntersectionObserver、图片加载完成、滚动兜底共同调用;调用本身只做数值比较,开销极小。
// 只向前推进:向上翻阅已加载内容时不会再发起任何请求。
function ensureAhead() {
  const container = EHR.state.container;
  if (!container) return;

  let hi = 0;
  _visible.forEach(p => { if (p > hi) hi = p; });
  const anchor = hi || EHR.state.activePage;
  const limit  = anchor + EHR.config.preloadDown;
  const total  = EHR.state.totalPages;
  const loaded = EHR.state.loadedPages;

  let spawned = false;
  for (let p = _maxLoaded + 1; p <= limit; p++) {
    if (total && p > total) break;
    if (loaded.has(p) || EHR.state.loadingPages.has(p)) continue;
    if (_failedPages.has(p - 1)) break;      // 上一页彻底失败时停止向后推进,避免连锁报错
    spawnDownBlock(p);
    spawned = true;
  }
  if (spawned) cleanMemory();
}

// =================================================
// 创建页面块(仅供向上加载使用:数据就绪后一次性返回完整块)
// =================================================

async function createPageBlock(page) {
  if (EHR.state.loadedPages.has(page)) return null;
  if (EHR.state.loadingPages.has(page)) return null;
  EHR.state.loadingPages.add(page);

  let data = null;
  try { data = await resolvePage(page); } catch (e) {}
  EHR.state.loadingPages.delete(page);
  if (!data) return null;

  const box = makeBox(page);
  markLoaded(page);
  fillBlock(box, page, data);
  return box;
}

// =================================================
// 向上加载(行为保持不变:滚动到顶才触发)
// =================================================

let _loadingPrev = false;

async function loadPreviousPages() {
  if (_loadingPrev) return;
  _loadingPrev = true;
  try {
    const loaded = EHR.state.loadedPages;
    if (!loaded.size) return;
    let minLoaded = Infinity;
    loaded.forEach(p => { if (p < minLoaded) minLoaded = p; });

    const pages = [];
    for (let i = 1; i <= EHR.config.preloadUp; i++) {
      const page = minLoaded - i;
      if (page <= 0) break;
      if (loaded.has(page) || EHR.state.loadingPages.has(page)) continue;
      pages.push(page);
    }
    if (!pages.length) return;

    const results = await Promise.all(
      pages.map(page => createPageBlock(page).then(block => ({ page, block })))
    );
    results.sort((a, b) => b.page - a.page);
    for (const { block } of results) {
      if (block && EHR.state.container) {
        EHR.state.container.prepend(block);
        observeBlock(block);
      }
    }
    cleanMemory();
  } finally {
    _loadingPrev = false;
  }
}

// =================================================
// 滚动:向上触发加载 + 向下兜底
// =================================================

let _scrollTimer = null;
let _lastScrollY = 0;

function setupScrollLoader() {
  function onScroll() {
    if (_scrollTimer) return;
    _scrollTimer = setTimeout(() => {
      _scrollTimer = null;
      const curScrollY = window.scrollY;
      const scrollingUp = curScrollY < _lastScrollY;
      _lastScrollY = curScrollY;

      ensureAhead(); // 向下预载主要由 IntersectionObserver 驱动,这里仅作兜底
      if (scrollingUp && curScrollY < 80) loadPreviousPages();
    }, 200);
  }
  // 延迟 800ms 再开始监听:等浏览器 scroll-restore 完成,避免误触发向上加载
  setTimeout(() => {
    _lastScrollY = window.scrollY;
    window.addEventListener("scroll", onScroll, { passive: true });
  }, 800);
}

// =================================================
// 图片显示引擎
// =================================================

function getScaleRatio() {
  const scale = Number(EHR.config.scale);
  return Number.isFinite(scale) && scale > 0 ? scale / 100 : 1;
}

// 版面度量只算一次,批量刷新时共享,避免每张图都触发 getComputedStyle / 强制回流
function getLayoutMetrics() {
  const dpr = window.devicePixelRatio || 1;
  const viewportCSSW = document.documentElement.clientWidth || window.innerWidth;
  const i1 = document.querySelector("#i1");
  const i1Style = i1 ? getComputedStyle(i1) : null;
  const frameW = i1Style
    ? (parseFloat(i1Style.borderLeftWidth) || 0)
      + (parseFloat(i1Style.borderRightWidth) || 0)
      + (parseFloat(i1Style.paddingLeft) || 0)
      + (parseFloat(i1Style.paddingRight) || 0)
    : 0;
  return {
    dpr,
    screenCSSW: Math.max(0, viewportCSSW - frameW - 1),
    ratio: getScaleRatio(),
  };
}

function applyImageMode(img, metrics) {
  if (!img) return;
  if (!img.naturalWidth) {
    if (!img.width) { setTimeout(() => applyImageMode(img), 100); return; }
  }

  const nw = img.naturalWidth || img.width;
  const m  = metrics || getLayoutMetrics();
  const { dpr, screenCSSW, ratio } = m;

  img.style.removeProperty("width");
  img.style.removeProperty("max-width");
  img.style.removeProperty("height");
  img.style.height         = "auto";
  img.style.display        = "block";
  img.style.margin         = "0 auto";
  img.style.imageRendering = "pixelated";
  img.style.imageRendering = "-moz-crisp-edges";
  img.style.imageRendering = "crisp-edges";

  const container = EHR.state.container;

  if (EHR.config.mode === "pixel") {
    const cssW = (nw / dpr) * ratio;
    img.style.width    = cssW + "px";
    img.style.maxWidth = "none";
    if (container) container.style.overflowX = "visible";
  } else {
    let cssW;
    if (nw <= screenCSSW * dpr) {
      cssW = (nw / dpr) * ratio;
    } else {
      cssW = screenCSSW * ratio;
    }
    img.style.width    = cssW + "px";
    img.style.maxWidth = (screenCSSW * ratio) + "px";
    if (container) container.style.overflowX = "visible";
  }

  ensurePanelWidth();
}

// =================================================
// 面板自动扩容(rAF 合并;优先读内联样式宽度,避免逐图强制回流)
// =================================================

let _panelFitScheduled = false;

function ensurePanelWidth() {
  if (_panelFitScheduled) return;
  _panelFitScheduled = true;
  requestAnimationFrame(() => {
    _panelFitScheduled = false;
    const container = EHR.state.container;
    const i1 = document.querySelector("#i1");
    if (!container || !i1) return;

    let maxImgW = 0;
    container.querySelectorAll("img").forEach(img => {
      if (img.style.display === "none") return;
      let w = parseFloat(img.style.width);
      if (!(w > 0)) w = img.getBoundingClientRect().width;
      if (w > maxImgW) maxImgW = w;
    });

    if (!EHR.state.baseI1Width || EHR.state.baseI1Width <= 0) {
      const curW = parseFloat(i1.style.width) || i1.offsetWidth;
      EHR.state.baseI1Width = curW > 0 ? curW : (maxImgW > 0 ? maxImgW : 0);
    }

    const baseW = EHR.state.baseI1Width || 0;

    const i1Style = getComputedStyle(i1);
    const frameW = (parseFloat(i1Style.borderLeftWidth) || 0)
      + (parseFloat(i1Style.borderRightWidth) || 0)
      + (parseFloat(i1Style.paddingLeft) || 0)
      + (parseFloat(i1Style.paddingRight) || 0);

    let targetW = baseW;
    if (maxImgW + frameW > baseW) {
      targetW = Math.ceil(maxImgW + frameW);
    }

    const maxPanelW = Math.max(0, (document.documentElement.clientWidth || window.innerWidth) - 1);
    const scaleRatio = getScaleRatio();
    if (targetW > maxPanelW
        && EHR.config.mode !== "pixel"
        && scaleRatio <= 1) {
      targetW = maxPanelW;
    }

    if (targetW > 0) {
      EHR.state.currentI1Width = targetW;
      // 值未变化时不写样式,避免无谓的样式失效与 MutationObserver 回调
      if (i1.style.getPropertyValue("width") !== targetW + "px") {
        i1.style.setProperty("width", targetW + "px", "important");
        i1.style.setProperty("min-width", targetW + "px", "important");
        i1.style.setProperty("max-width", "none", "important");
      }
    }
  });
}

function refreshImages() {
  const m = getLayoutMetrics();
  document.querySelectorAll(".EHR_page img").forEach(img => applyImageMode(img, m));
  ensurePanelWidth();
}

let _refreshRaf = 0;
function scheduleRefreshImages() {
  if (_refreshRaf) return;
  _refreshRaf = requestAnimationFrame(() => { _refreshRaf = 0; refreshImages(); });
}

function setupResizeWatcher() {
  let tid = null;
  window.addEventListener("resize", () => {
    clearTimeout(tid);
    tid = setTimeout(refreshImages, 120);
  });
}

// =================================================
// IntersectionObserver:维护「可视页集合」,驱动页码、地址栏与向下预载
// =================================================

const _visible = new Set();
let _io = null;

function setupIO() {
  if (!("IntersectionObserver" in window)) return;
  _io = new IntersectionObserver(entries => {
    entries.forEach(en => {
      const pg = Number(en.target.dataset.page);
      if (en.isIntersecting) _visible.add(pg); else _visible.delete(pg);
    });
    schedulePageUpdate();
    ensureAhead();
  }, { root: null, rootMargin: "0px", threshold: 0 });
  document.querySelectorAll(".EHR_page[data-page]").forEach(b => _io.observe(b));
}

function observeBlock(block) {
  if (_io && block) _io.observe(block);
}

// 视口内最靠近顶部的页:优先用 IO 维护的集合,无数据时回退到逐块测量
function getTopVisiblePage() {
  if (_visible.size) {
    let lo = Infinity;
    _visible.forEach(p => { if (p < lo) lo = p; });
    return lo;
  }
  const blocks = document.querySelectorAll(".EHR_page[data-page]");
  let best = null, bestScore = Infinity;
  blocks.forEach(b => {
    const rect = b.getBoundingClientRect();
    if (rect.bottom <= 0 || rect.top >= window.innerHeight) return;
    if (rect.top < bestScore) { bestScore = rect.top; best = b; }
  });
  return best ? Number(best.dataset.page) : null;
}

let _pageUpdateTimer = null;

function applyPageUrl(page) {
  const key = EHR.state.pageKeys.get(page);
  if (!key || !EHR.state.gid) return;
  const newURL = `${location.origin}/s/${key}/${EHR.state.gid}-${page}`;
  if (location.href !== newURL) history.replaceState(null, "", newURL);
}

function schedulePageUpdate() {
  if (_pageUpdateTimer) return;
  _pageUpdateTimer = setTimeout(() => {
    _pageUpdateTimer = null;
    const page = getTopVisiblePage();
    if (!page) return;
    EHR.state.activePage = page;
    updateProgress();
    applyPageUrl(page);
    ensureAhead();
  }, 150);
}

function setupObserver() {
  setupIO();
  window.addEventListener("scroll", schedulePageUpdate, { passive: true });
  setTimeout(schedulePageUpdate, 300);
}

// =================================================
// 内存管理
// =================================================

function cleanMemory() {
  const cur   = EHR.state.activePage;
  const limit = EHR.config.cacheLimit;
  const boxMap = new Map();
  document.querySelectorAll(".EHR_page[data-page]").forEach(b => {
    boxMap.set(Number(b.dataset.page), b);
  });
  EHR.state.loadedPages.forEach(page => {
    if (EHR.state.loadingPages.has(page)) return;
    if (Math.abs(page - cur) > limit) {
      const box = boxMap.get(page);
      if (!box) return;
      const img = box.querySelector("img:not([data-src])");
      if (img && img.src && !img.src.startsWith("data:")) {
        // 先锁定块高度,释放图片后不会塌陷导致滚动位置跳动
        box.style.minHeight = box.offsetHeight + "px";
        img.dataset.src = img.src;
        img.src = "";
        img.style.display = "none";
      }
    }
  });
}

function restoreReleasedImages() {
  const vh = window.innerHeight;
  document.querySelectorAll("img[data-src]").forEach(img => {
    const rect = img.getBoundingClientRect();
    if (rect.top < vh * 2 && rect.bottom > -vh * 2) {
      const box = img.parentNode;
      img.onload = () => {
        img.style.display = "block";
        if (box && box.style) box.style.minHeight = "";
        applyImageMode(img);
      };
      img.src = img.dataset.src;
      img.removeAttribute("data-src");
    }
  });
}

function setupPerformance() {
  let t = null;
  function onPerf() {
    if (t) return;
    t = setTimeout(() => { t = null; restoreReleasedImages(); }, 200);
  }
  window.addEventListener("scroll", onPerf, { passive: true });
}

// =================================================
// 进度显示(右上角,始终可见)
// =================================================

let _progressEl = null;
function createProgress() {
  _progressEl = document.createElement("div");
  _progressEl.id = "EHR_progress";
  _progressEl.textContent = `${EHR.state.startPage} / ?`;
  document.body.appendChild(_progressEl);
}

function updateProgress() {
  if (_progressEl) _progressEl.textContent = `${EHR.state.activePage} / ${EHR.state.totalPages || "?"}`;
}

// =================================================
// 悬浮球
// =================================================

function createFloatBall() {
  const svgSettings = `<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>`;
  const svgHome = `<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/></svg>`;

  const ball = document.createElement("div");
  ball.id = "EHR_ball";
  ball.innerHTML = svgSettings;
  ball.title = "EH Reader 设置";
  document.body.appendChild(ball);

  ball.addEventListener("mousedown", () => ball.classList.add("EHR_ball_press"));
  ball.addEventListener("mouseup",   () => ball.classList.remove("EHR_ball_press"));
  ball.addEventListener("mouseleave",() => ball.classList.remove("EHR_ball_press"));
  ball.onclick = () => togglePanel();

  const homeBtn = document.createElement("div");
  homeBtn.id = "EHR_home_btn";
  homeBtn.innerHTML = svgHome;
  homeBtn.title = "返回图库预览";
  document.body.appendChild(homeBtn);

  homeBtn.addEventListener("mousedown", () => homeBtn.classList.add("EHR_ball_press"));
  homeBtn.addEventListener("mouseup",   () => homeBtn.classList.remove("EHR_ball_press"));
  homeBtn.addEventListener("mouseleave",() => homeBtn.classList.remove("EHR_ball_press"));
  homeBtn.onclick = () => {
    const href = extractGalleryBackLink();
    if (href) location.href = href;
  };

  function alignBall() {
    const syringe = document.querySelector("#eh-syringe-popup-button");
    let right = 20, bottom = 20, size = 42, fontSize = 20;
    if (syringe) {
      bottom   = parseFloat(syringe.style.bottom) || 12;
      right    = parseFloat(syringe.style.right)  || 12;
      size     = syringe.offsetHeight || 36;
      fontSize = Math.round(size * 0.5);
    }
    const gap = 8;
    ball.style.width    = size + "px";
    ball.style.height   = size + "px";
    ball.style.right    = right + "px";
    ball.style.bottom   = (bottom + size + gap) + "px";
    ball.style.fontSize = fontSize + "px";
    homeBtn.style.width    = size + "px";
    homeBtn.style.height   = size + "px";
    homeBtn.style.right    = right + "px";
    homeBtn.style.bottom   = (bottom + (size + gap) * 2) + "px";
    homeBtn.style.fontSize = (fontSize + 2) + "px";
  }

  alignBall();
  // EhSyringe 按钮出现后对齐一次即可;找到后立即断开 body 级观察,避免持续监听整个 DOM 子树
  const bodyObs = new MutationObserver(() => {
    if (document.querySelector("#eh-syringe-popup-button")) {
      alignBall();
      bodyObs.disconnect();
    }
  });
  bodyObs.observe(document.body, { childList: true, subtree: true });
  setTimeout(() => {
    bodyObs.disconnect();
    const syringe = document.querySelector("#eh-syringe-popup-button");
    if (syringe) {
      alignBall();
      new MutationObserver(alignBall).observe(syringe, { attributes: true, attributeFilter: ["style"] });
    }
  }, 2000);
}

// =================================================
// 设置面板
// =================================================

function togglePanel() {
  const old = document.querySelector("#EHR_panel");
  if (old) { old.remove(); return; }

  const panel = document.createElement("div");
  panel.id = "EHR_panel";
  panel.innerHTML = `
<div class="ehr_panel_title">⚙ EH Reader</div>

<div class="ehr_section">
  <div class="ehr_section_label">显示模式</div>
  <div class="ehr_radio_group">
    <label><input type="radio" name="ehrmode" value="auto"> 自适应</label>
    <label><input type="radio" name="ehrmode" value="pixel"> 像素100%</label>
  </div>
</div>

<div class="ehr_section">
  <div class="ehr_section_label">缩放 <span id="ehr_scale_val">${EHR.config.scale}%</span></div>
  <input id="ehr_scale" type="range" min="25" max="200" step="5" value="${EHR.config.scale}">
</div>

<div class="ehr_section ehr_row_group">
  <div class="ehr_row">
    <span class="ehr_row_label">向上预载</span>
    <input id="ehr_up" type="number" min="1" max="20" value="${EHR.config.preloadUp}">
  </div>
  <div class="ehr_row">
    <span class="ehr_row_label">向下预载</span>
    <input id="ehr_down" type="number" min="1" max="20" value="${EHR.config.preloadDown}">
  </div>
  <div class="ehr_row">
    <span class="ehr_row_label">缓存上限(张)</span>
    <input id="ehr_cache_limit" type="number" min="10" max="1000" step="10" value="${EHR.config.cacheLimit || 500}">
  </div>
</div>

<div class="ehr_section">
  <div class="ehr_section_label">显示图片信息</div>
  <label class="ehr_toggle_label">
    <input type="checkbox" id="ehr_show_info" ${EHR.config.showImgInfo ? "checked" : ""}>
    <span class="ehr_toggle_text">在每张图片下方显示文件名/尺寸/大小</span>
  </label>
</div>

<div class="ehr_section ehr_stats">
  <span>已加载 <b id="ehr_loaded">-</b> 张</span>
  <span>共 <b id="ehr_total">-</b> 页</span>
  <span id="ehr_cache_used" style="font-size:11px;color:#888;">缓存查询中…</span>
</div>

<div class="ehr_btns">
  <button id="ehr_apply">应用并刷新</button>
  <button id="ehr_reset">恢复默认</button>
</div>
`;

  document.body.appendChild(panel);
  positionPanel(panel);

  document.querySelector("#ehr_loaded").textContent = EHR.state.loadedPages.size;
  document.querySelector("#ehr_total").textContent  = EHR.state.totalPages || "?";

  document.querySelectorAll("[name=ehrmode]").forEach(r => {
    if (r.value === EHR.config.mode) r.checked = true;
    r.onchange = () => { EHR.config.mode = r.value; saveConfig(); refreshImages(); };
  });

  // 缩放:拖动时按帧合并刷新,松手后再写入配置
  const scaleEl = document.querySelector("#ehr_scale");
  scaleEl.oninput = function () {
    EHR.config.scale = Number(this.value);
    document.querySelector("#ehr_scale_val").textContent = this.value + "%";
    scheduleRefreshImages();
  };
  scaleEl.onchange = function () { saveConfig(); };

  document.querySelector("#ehr_show_info").onchange = function () {
    EHR.config.showImgInfo = this.checked;
    saveConfig();
    refreshInfoBars();
  };

  EHCache.getCount().then(count => {
    const el = document.querySelector("#ehr_cache_used");
    if (el) el.textContent = `已缓存 ${count} 张 / 上限 ${EHR.config.cacheLimit || 500} 张`;
  });

  document.querySelector("#ehr_apply").onclick = () => {
    EHR.config.preloadDown = Math.max(1, Number(document.querySelector("#ehr_down").value));
    EHR.config.preloadUp   = Math.max(1, Number(document.querySelector("#ehr_up").value));
    EHR.config.cacheLimit  = Math.max(10, Number(document.querySelector("#ehr_cache_limit").value));
    saveConfig();
    location.reload();
  };

  document.querySelector("#ehr_reset").onclick = () => {
    localStorage.removeItem("EHReader_config");
    location.reload();
  };
}

function positionPanel(panel) {
  const ball = document.querySelector("#EHR_ball");
  if (ball) {
    const ballRight  = parseFloat(ball.style.right)  || 20;
    const ballBottom = parseFloat(ball.style.bottom) || 20;
    const ballH      = ball.offsetHeight || 42;
    panel.style.right  = ballRight + "px";
    panel.style.bottom = (ballBottom + ballH + 10) + "px";
    panel.style.top    = "auto";
    panel.style.transform = "none";
  }
}

// =================================================
// 热键
// =================================================

function setupHotkeys() {
  document.addEventListener("keydown", e => {
    if (e.target.tagName === "INPUT") return;
    if (e.key === "ArrowRight" || e.key === "d") {
      const box = document.querySelector(`.EHR_page[data-page="${EHR.state.activePage + 1}"]`);
      if (box) box.scrollIntoView({ behavior: "smooth", block: "start" });
    }
    if (e.key === "ArrowLeft" || e.key === "a") {
      const box = document.querySelector(`.EHR_page[data-page="${EHR.state.activePage - 1}"]`);
      if (box) box.scrollIntoView({ behavior: "smooth", block: "start" });
    }
    if (e.key === "Escape") {
      const panel = document.querySelector("#EHR_panel");
      if (panel) panel.remove();
    }
  });
}

// =================================================
// CSS
// =================================================

function addCSS() {
  const css = `
/* ======== 原网页主面板:保留居中灰色背景与两侧深色背景,宽度随图片动态平滑过渡 ======== */
#i1 {
  box-sizing: border-box !important;
  margin-left: auto !important;
  margin-right: auto !important;
  max-width: none !important;
  transition: width 0.3s cubic-bezier(0.25, 0.1, 0.25, 1), min-width 0.3s cubic-bezier(0.25, 0.1, 0.25, 1);
}

#i3 {
  width: auto !important;
  max-width: none !important;
  min-width: 0 !important;
  margin-left: auto !important;
  margin-right: auto !important;
}

/* ======== 阅读器容器:在 #i1 内部,紧跟 #i3 ======== */
#EHR_container {
  display: block;
  width: 100%;
  margin: 0 auto;
  overflow-x: visible;
}

/* ======== 每页块:始终居中,不参与横向溢出决策 ======== */
.EHR_page {
  display: block;
  width: 100%;
  text-align: center;
  overflow-x: visible;
}

/* 图片本身 */
.EHR_page > img {
  height: auto;
  display: block;
  margin: 0 auto;
}

/* 图片信息行:继承原网页样式(居中),下方加 14px 间距 */
.EHR_info_bar {
  display: block;
  text-align: center;
  margin-bottom: 14px;
}

/* ======== 加载框 ======== */
.EHR_loading {
  height: 280px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  gap: 10px;
}

.EHR_spinner {
  width: 30px; height: 30px;
  border-radius: 50%;
  border: 3px solid #888;
  border-top-color: transparent;
  animation: EHRspin 1s linear infinite;
}

@keyframes EHRspin {
  from { transform: rotate(0deg); }
  to   { transform: rotate(360deg); }
}

.EHR_err_icon {
  width: 30px; height: 30px;
  border-radius: 50%;
  border: 3px solid #666;
  font-size: 16px;
  font-weight: bold;
  display: flex; align-items: center; justify-content: center;
}

.EHR_retry_btn {
  margin-top: 10px;
  padding: 5px 16px;
  background: #5c5c5c;
  color: #eee;
  border: none;
  border-radius: 5px;
  font-size: 13px;
  cursor: pointer;
  transition: background .15s;
}
.EHR_retry_btn:hover {
  background: #7a7a7a;
}

/* ======== 右上角进度 ======== */
#EHR_progress {
  position: fixed;
  right: 20px; top: 12px;
  background: rgba(0, 0, 0, 0.65);
  color: #eee;
  padding: 4px 11px;
  border-radius: 10px;
  z-index: 999999;
  font-size: 13px;
  pointer-events: none;
}

/* ======== 悬浮球(设置)& 主页按钮 ======== */
#EHR_ball, #EHR_home_btn {
  position: fixed;
  right: 20px; bottom: 20px;
  width: 42px; height: 42px;
  background: rgba(40, 40, 40, .55);
  color: rgba(238, 238, 238, .8);
  border-radius: 50%;
  cursor: pointer;
  z-index: 999999;
  display: flex;
  align-items: center;
  justify-content: center;
  user-select: none;
  box-shadow: 0 2px 8px rgba(0,0,0,.3);
  opacity: 0.5;
  transition: opacity .2s, background .2s, transform .12s, box-shadow .2s;
  box-sizing: border-box;
  padding: 0;
  line-height: 0;
  font-size: 0;
}
#EHR_ball svg, #EHR_home_btn svg {
  display: block;
  flex-shrink: 0;
  pointer-events: none;
}
#EHR_ball:hover, #EHR_home_btn:hover {
  opacity: 1;
  background: rgba(60, 60, 60, .95);
  box-shadow: 0 3px 12px rgba(0,0,0,.6);
}
#EHR_ball.EHR_ball_press, #EHR_home_btn.EHR_ball_press {
  transform: scale(.88);
  box-shadow: 0 1px 4px rgba(0,0,0,.4);
}

/* ======== 设置面板 ======== */
#EHR_panel {
  position: fixed;
  right: 72px;
  bottom: 70px;
  top: auto;
  width: 240px;
  padding: 0;
  background: rgba(22, 22, 22, 0.97);
  color: #e0e0e0;
  border-radius: 12px;
  z-index: 999999;
  font-size: 13px;
  line-height: 1.5;
  box-shadow: 0 6px 24px rgba(0,0,0,.7);
  overflow: hidden;
}

.ehr_panel_title {
  font-size: 15px;
  font-weight: bold;
  text-align: center;
  padding: 12px 16px 10px;
  background: rgba(255,255,255,.05);
  border-bottom: 1px solid #333;
  letter-spacing: 1px;
}

.ehr_section {
  padding: 9px 14px;
  border-bottom: 1px solid #2a2a2a;
}
.ehr_section:last-child { border-bottom: none; }

.ehr_section_label {
  font-size: 11px;
  color: #888;
  text-transform: uppercase;
  letter-spacing: .5px;
  margin-bottom: 5px;
}

.ehr_radio_group {
  display: flex;
  gap: 16px;
  justify-content: center;
  align-items: center;
}
.ehr_radio_group label {
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 5px;
  line-height: 1;
}
.ehr_radio_group label input[type=radio] {
  margin: 0;
  vertical-align: middle;
  position: relative;
  top: 0;
}

#EHR_panel input[type=range] {
  width: 100%;
  accent-color: #7a7a7a;
}

.ehr_row_group { display: flex; flex-direction: column; gap: 5px; }
.ehr_row {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.ehr_row_label { font-size: 12px; color: #ccc; }
#EHR_panel input[type=number] {
  width: 64px;
  background: #2c2c2c;
  color: #eee;
  border: 1px solid #444;
  border-radius: 5px;
  padding: 3px 6px;
  font-size: 12px;
  text-align: left;
}

.ehr_toggle_label {
  display: flex;
  align-items: flex-start;
  justify-content: center;
  gap: 6px;
  cursor: pointer;
}
.ehr_toggle_text { font-size: 12px; color: #ccc; line-height: 1.4; }
#EHR_panel input[type=checkbox] { margin-top: 2px; accent-color: #9a9a9a; }

.ehr_stats {
  display: flex;
  flex-wrap: wrap;
  gap: 6px 10px;
  color: #999;
  font-size: 12px;
}
.ehr_stats b { color: #ddd; }

.ehr_btns {
  display: flex;
  gap: 8px;
  padding: 10px 14px 12px;
  border-top: 1px solid #2a2a2a;
}
#EHR_panel button {
  flex: 1;
  padding: 6px 0;
  border-radius: 7px;
  border: none;
  background: #3a3a3a;
  color: #ddd;
  cursor: pointer;
  font-size: 12px;
  transition: background .15s;
}
#EHR_panel button:hover { background: #505050; color: #fff; }
#EHR_panel #ehr_apply { background: #4a4a6a; }
#EHR_panel #ehr_apply:hover { background: #5a5a8a; }
`;

  const style = document.createElement("style");
  style.id = "EHR_main_style";
  style.textContent = css;
  document.head.appendChild(style);
}

// =================================================
// 主入口
// =================================================

function init() {
  console.log("[EHReader] Init v" + EHR.version);

  harvestPageKeys();
  EHR.state.totalPages = detectTotalPages();
  initGallery();           // 必须在 patchOriginalPage 之前读取返回图库链接

  addCSS();
  patchOriginalPage();
  createReaderContainer();
  setupObserver();         // 先建 IntersectionObserver,后续每个页块创建时即登记
  moveCurrentImage();
  createFloatBall();
  createProgress();
  setupScrollLoader();     // 向上加载(滚动到顶)+ 向下兜底
  setupResizeWatcher();
  setupAncestorWidthGuard();
  setupPerformance();
  setupHotkeys();

  // 不再等待 900ms:立即开始向下预载(起始页本身已在 DOM 中,不受 scroll-restore 影响)
  ensureAhead();
  updateProgress();

  console.log("[EHReader] page:", EHR.state.startPage, "total:", EHR.state.totalPages);
}

init();

})();