☰

CUMS.net Cleaner + Downloader

Removes ads, AI promos, popunders/tab-unders and the anti-devtools loop. Adds a Download button under the video and a floating Batch Download selector (fresh signed link per video, chunked download to disk with resume).

スクリプトをインストールするには、Tampermonkey, Greasemonkey や Violentmonkey のような拡張機能のインストールが必要です。

スクリプトをインストールするには、 Tampermonkey や Violentmonkey のような拡張機能のインストールが必要です。

スクリプトをインストールするには、Tampermonkey や Violentmonkey のような拡張機能のインストールが必要です。

スクリプトをインストールするには、Tampermonkey や Userscripts のような拡張機能のインストールが必要です。

このスクリプトをインストールするには、Tampermonkeyなどの拡張機能をインストールする必要があります。

このスクリプトをインストールするには、ユーザースクリプト管理ツールの拡張機能をインストールする必要があります。

(ユーザースクリプト管理ツールは設定済みなのでインストール!)

このスタイルをインストールするには、Stylusなどの拡張機能をインストールする必要があります。

このスタイルをインストールするには、Stylus などの拡張機能をインストールする必要があります。

このスタイルをインストールするには、Stylus tなどの拡張機能をインストールする必要があります。

このスタイルをインストールするには、ユーザースタイル管理用の拡張機能をインストールする必要があります。

このスタイルをインストールするには、ユーザースタイル管理用の拡張機能をインストールする必要があります。

このスタイルをインストールするには、ユーザースタイル管理用の拡張機能をインストールする必要があります。

(ユーザースタイル管理ツールは設定済みなのでインストール!)

このスクリプトの質問や評価の投稿はこちら、通報はこちらへお寄せください
// ==UserScript==
// @name         CUMS.net Cleaner + Downloader
// @namespace    cums_revamped
// @version      2.6.0
// @description  Removes ads, AI promos, popunders/tab-unders and the anti-devtools loop. Adds a Download button under the video and a floating Batch Download selector (fresh signed link per video, chunked download to disk with resume).
// @license      GPLv2

// @match        *://cums.net/*
// @match        *://*.cums.net/*
// @run-at       document-start
// @grant        GM_download
// @grant        GM_xmlhttpRequest
// @grant        GM_setClipboard
// @grant        GM_registerMenuCommand
// @grant        GM_openInTab
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_deleteValue
// @grant        GM_listValues
// @grant        GM_addValueChangeListener
// @grant        GM_removeValueChangeListener
// @connect      cums.net
// @connect      *
// ==/UserScript==

/*
 * DOWNLOADS: files are fetched in ranged chunks into the browser's private storage for this site
 *   (OPFS, on disk), then saved as a normal browser download. A failed/stopped download keeps its
 *   finished chunks and resumes next time. Without OPFS or byte ranges it falls back to GM_download;
 *   for that path: Tampermonkey > Settings > Config mode: Advanced > Downloads BETA > whitelist .mp4.
 *
 * LAYOUT
 *   Part 1  Cleaner: unchanged logic. Because this script now uses GM_* APIs it runs in
 *           Tampermonkey's sandbox, so the cleaner is injected into the page as a <script>
 *           (its window.open / setInterval / appendChild patches must live in the page).
 *           If the page refuses the injection, it runs here instead (CSS + element removal still work).
 *   Part 2  MP4 Link Grabber 3.1.0, kept whole. Changes are marked [cums]: AbortSignal support in
 *           grab()/download(), and the floating "MP4" pill is off (menu command still works).
 *           2.4.0: "early seek" in capture tabs — the moment the file's header is in (loadedmetadata)
 *           the player is sent far ahead, so even a short video makes a second request straight to
 *           the signed fsN URL before it is fully buffered.
 *           2.4.1: preload hold off (it broke background tabs); capture tabs boot the site's lazy
 *           player themselves and wait until the <video> actually has a source.
 *           2.5.0: shorts viewer gets a Download action in each clip's rail (no batch selector there).
 *           2.5.1: plus a site-styled Download button beside the feed's up/down arrows (clip on screen).
 *           2.6.0: that button no longer drops on hover; shorts get a media-control bar (loop untouched).
 *   Part 3  Download UI + engine: single button under the player, floating batch selector, progress
 *           dialog, chunked disk download with resume.
 */

(function () {
  'use strict';

  // ======================= settings =======================
  const CLEANER_CFG = {
    blockAnalytics: true, // Google Analytics + Yandex Metrica/Webvisor (session recording)
    debug: false,
  };
  const DL_CFG = {
    fastPath: true,        // first try the page's own file link (JSON-LD "vfile" URL -> redirect to ?t=…&exp=…); MP4 Grabber if that fails
    grabRetries: 3,        // MP4 Grabber re-attempts after the first try (4 tries total)
    minTokenLifeSec: 120,  // fetch a new token if the one in hand expires sooner than this
    diskResume: true,      // chunked download into the browser's private disk storage (OPFS) with resume; false = GM_download
    chunkMB: 8,            // size of each ranged request / file part on disk
    connections: 4,        // parallel chunk requests per video
    chunkRetries: 5,       // per chunk, before the video counts as failed for this attempt
    chunkTimeoutSec: 120,
    itemRetries: 2,        // whole-video retries (fresh link, resumes from the parts on disk)
    keepPartialDays: 7,    // unfinished downloads older than this are deleted
    yieldToPlayback: true, // while you watch a video on the page, downloads back off so it can buffer
    playbackMinSec: 10,    //   below this many seconds buffered ahead: no new chunks
    playbackTargetSec: 30, //   below this: one connection; at/above: all connections
    maxRateMBps: 0,        // overall download speed cap in MB/s (0 = no cap)
    debug: false,
  };

  // =====================================================================================
  //  PART 1 — Cleaner (injected into the page)
  // =====================================================================================
  function pageCleaner(CFG) {
    'use strict';
    try { document.documentElement.setAttribute('data-cums-cleaner', '1'); } catch (e) {}
    const log = (...a) => CFG.debug && console.log('[cleaner]', ...a);

    // ---------- 1. Kill the popunder config before adv.js can read it ----------
    try {
      Object.defineProperty(window, 'CUMS_POPUNDER', {
        configurable: false,
        get: () => undefined,
        set: () => {},
      });
    } catch (e) {}
    try {
      // Ad network queue (smartfloralab / ExoClick-style "AdProvider")
      Object.defineProperty(window, 'AdProvider', {
        configurable: false,
        get: () => ({ push() {} }),
        set: () => {},
      });
    } catch (e) {}

    // ---------- 2. Neutralise window.open (popups / "swap" tab-unders) ----------
    const fakeWin = {
      closed: true, close() {}, focus() {}, blur() {}, postMessage() {},
      location: { href: '', assign() {}, replace() {} }, document: { write() {}, close() {} },
    };
    try {
      Object.defineProperty(window, 'open', {
        configurable: false, writable: false,
        value: function (url) { log('blocked window.open', url); return fakeWin; },
      });
    } catch (e) { window.open = () => fakeWin; }

    // ---------- 3. Anti-devtools "debugger" loop ----------
    const hasDebugger = (fn) => {
      try { return typeof fn === 'function' ? /\bdebugger\b/.test(Function.prototype.toString.call(fn))
                                           : /\bdebugger\b/.test(String(fn)); } catch (e) { return false; }
    };
    const _setInterval = window.setInterval, _setTimeout = window.setTimeout;
    window.setInterval = function (fn, ...r) { return hasDebugger(fn) ? 0 : _setInterval.call(this, fn, ...r); };
    window.setTimeout  = function (fn, ...r) { return hasDebugger(fn) ? 0 : _setTimeout.call(this, fn, ...r); };

    // ---------- 4. Script blocking ----------
    const BAD_SRC = [
      /\/js\/adv\.js/i,            // popunder engine
      /\/js\/search-ad\.js/i,      // ads in search
      /smartfloralab\.com/i,       // ad network (ad-provider.js, popunder link)
      /cum\.giving/i, /rndomnm\.com/i,
      /exoclick|exosrv|magsrv|juicyads|trafficjunky|tsyndicate|popads|popcash|adsterra|clickadu/i,
    ];
    if (CFG.blockAnalytics) BAD_SRC.push(/googletagmanager\.com|google-analytics\.com|mc\.webvisor\.org|mc\.yandex\./i);

    const BAD_INLINE = [
      /CUMS_POPUNDER/, /AdProvider/, /setInterval\(\s*function\s*\(\)\s*\{\s*debugger/,
    ];
    if (CFG.blockAnalytics) BAD_INLINE.push(/\bgtag\(|\bym\(|dataLayer/);

    const isBadScript = (s) => {
      if (!s || s.tagName !== 'SCRIPT') return false;
      const src = s.src || s.getAttribute('src') || '';
      if (src) return BAD_SRC.some((r) => r.test(src));
      const txt = s.textContent || '';
      return BAD_INLINE.some((r) => r.test(txt));
    };
    const kill = (s) => { s.type = 'javascript/blocked'; s.remove(); log('blocked script', s.src || s.textContent.slice(0, 60)); };

    // 4a. Dynamically inserted scripts (deferred-tags loader, ad loaders)
    const wrapInsert = (proto, name) => {
      const orig = proto[name];
      proto[name] = function (node, ...rest) {
        if (node && node.tagName === 'SCRIPT' && isBadScript(node)) { log('blocked insert', node.src); return node; }
        if (node && node.tagName === 'IFRAME' && BAD_SRC.some((r) => r.test(node.src || ''))) return node;
        return orig.call(this, node, ...rest);
      };
    };
    wrapInsert(Node.prototype, 'appendChild');
    wrapInsert(Node.prototype, 'insertBefore');

    // 4b. Parser-inserted scripts (incl. the base64 document.write body)
    new MutationObserver((muts) => {
      for (const m of muts) for (const n of m.addedNodes) {
        if (n.nodeType !== 1) continue;
        if (n.tagName === 'SCRIPT') { if (isBadScript(n)) kill(n); continue; }
        n.querySelectorAll && n.querySelectorAll('script').forEach((s) => isBadScript(s) && kill(s));
        scrub(n);
      }
    }).observe(document.documentElement, { childList: true, subtree: true });

    // Firefox: stop execution outright
    document.addEventListener('beforescriptexecute', (e) => { if (isBadScript(e.target)) { e.preventDefault(); kill(e.target); } }, true);

    // ---------- 5. Element removal (ads + AI promos) ----------
    const AD_SELECTORS = [
      '[data-adv]',                     // every ad slot on the site is tagged with this
      '.promo-banner',                  // "AI RolePlay" header bar
      '.topbar-links',                  // "Undress AI / AI Porn / AI Jerk Off"
      '.promo-card',                    // fake "video" cards in Related ("AI ...", "Try for Free!")
      '.video-under-tab-ad',            // "LIVE CAMS" button
      '.adv-slider-zone', '.adv', 'ins[data-zoneid]', '.exo_wrapper', '[class*="exo-video-slider"]',
      'a[href*="/out.php"]', 'a[href*="cum.giving"]', 'a[href*="rndomnm.com"]', 'a[href*="smartfloralab"]',
      'iframe[src*="smartfloralab"]', 'iframe[src*="cum.giving"]',
      'a[href="/advertise/"]',
    ];
    const AI_TEXT = /\b(undress\s*ai|ai\s*(porn|jerk|roleplay|role\s*play|girl(friend)?s?|slut|sex|chat|companion|generator)|nudify|create\s+(and\s+\w+\s+)?your\s+ai)\b/i;

    function scrub(root) {
      root = root || document;
      if (!root.querySelectorAll) return;
      root.querySelectorAll(AD_SELECTORS.join(',')).forEach((el) => {
        // If the ad link is the only thing in a wrapper (e.g. .video-details-wrapper), drop the wrapper too
        const p = el.parentElement;
        el.remove();
        if (p && p.matches && p.matches('.video-details-wrapper') && !p.textContent.trim()) p.remove();
      });
      // Catch-all for AI promos that slip through without the usual markers
      root.querySelectorAll('a[target="_blank"], .thumbnail').forEach((el) => {
        const t = (el.textContent || '') + ' ' + (el.getAttribute('title') || '');
        if (AI_TEXT.test(t) && !(el.href && new URL(el.href, location.href).host.endsWith('cums.net'))) {
          (el.closest('.thumbnail') || el).remove();
        }
      });
    }

    // CSS hide as a first line of defence (prevents flash before removal)
    const css = AD_SELECTORS.join(',\n') + ' { display: none !important; }\n' +
      // Undo scroll-lock / leftover overlays some ad scripts leave behind
      'html.ad-lock, body.ad-lock { overflow: auto !important; }';
    const style = document.createElement('style');
    style.textContent = css;
    (document.head || document.documentElement).appendChild(style);

    // ---------- 6. Click guard: ad links never fire, even if re-injected ----------
    document.addEventListener('click', (e) => {
      const a = e.target.closest && e.target.closest('a[href]');
      if (a && AD_SELECTORS.some((sel) => { try { return a.matches(sel); } catch (_) { return false; } })) {
        e.preventDefault(); e.stopImmediatePropagation();
      }
    }, true);

    document.addEventListener('DOMContentLoaded', () => scrub(document));
    window.addEventListener('load', () => scrub(document));
  }

  (function injectCleaner() {
    // document-start can run before <html> exists; wait for it.
    if (!document.documentElement) {
      const mo = new MutationObserver(() => { if (document.documentElement) { mo.disconnect(); injectCleaner(); } });
      mo.observe(document, { childList: true });
      return;
    }
    let ok = false;
    try {
      const s = document.createElement('script');
      s.textContent = `(${pageCleaner})(${JSON.stringify(CLEANER_CFG)});`;
      (document.head || document.documentElement).appendChild(s);
      s.remove();
      ok = document.documentElement.getAttribute('data-cums-cleaner') === '1';
    } catch (e) { /* fall through */ }
    if (!ok) { try { pageCleaner(CLEANER_CFG); } catch (e) { console.warn('[cleaner] fallback failed', e); } }
  })();

  // =====================================================================================
  //  PART 2 — MP4 Link Grabber (sandbox; signed-URL capture + GM_download)
  // =====================================================================================
  const MP4Grabber = (function () {
    'use strict';

    /* ------------------------------------------------------------------ *
     *  Config
     * ------------------------------------------------------------------ */
    const BUTTON_DELAY_MS = 2500;        // wait this long after page load before adding the button
    const SEEK_SETTLE_MS = 3500;         // how long to let the player fetch after the seek
    const TOKEN_KEYS = ['t', 'token', 'tok', 'hash', 'md5', 'sig', 'signature', 'sign', 's', 'h', 'k', 'key',
      'auth', 'st', 'hdnts', 'wmsauthsign', 'secure', 'acl', 'verify'];
    const EXPIRY_KEYS = ['exp', 'expires', 'expire', 'expiry', 'expiration', 'e', 'ex', 'x', 'ttl', 'valid',
      'validto', 'until', 'deadline', 'ts', 'time'];
    const PREVIEW_RE = /(preview|trailer|teaser|sample|thumb|_prev\b|\/prev\/)/i;
    const MAX_SCAN = 5 * 1024 * 1024;
    const MSG_KEY = '__mp4LinkGrabber_v2';
    const SHOW_GRABBER_BUTTON = false;   // [cums] floating "MP4" pill off; menu command still opens the dialog
    const EARLY_SEEK = true;             // [cums] capture tabs: seek ahead at loadedmetadata (short videos)
    // [cums] Keep OFF. Holding players at preload="none" means nothing loads until play(), and Chrome
    // won't start media in a background tab that has never been shown, so background capture always
    // failed and fell through to a visible tab. With preload left as the site sets it ("auto") the
    // file starts loading on its own and loadedmetadata still fires early enough for the early seek.
    const EARLY_SEEK_HOLD_PRELOAD = false;

    let IS_TOP = true;
    try { IS_TOP = window.top === window.self; } catch (_) { IS_TOP = false; }

    const nowSec = () => Math.floor(Date.now() / 1000);
    const sleep = ms => new Promise(r => setTimeout(r, ms));

    /* ------------------------------------------------------------------ *
     *  URL analysis
     * ------------------------------------------------------------------ */
    function asTimestamp(v) {
      if (!/^\d{9,13}$/.test(v)) return null;
      let n = Number(v);
      if (v.length === 13) n = Math.floor(n / 1000);
      const now = nowSec();
      return (n > now - 86400 * 365 && n < now + 86400 * 365 * 5) ? n : null;
    }

    // Keep raw (undecoded) key/value so the token is rebuilt byte-for-byte.
    function splitQuery(search) {
      if (!search || search === '?') return [];
      return search.replace(/^\?/, '').split('&').filter(Boolean).map(p => {
        const i = p.indexOf('=');
        const rawKey = i < 0 ? p : p.slice(0, i);
        const rawVal = i < 0 ? '' : p.slice(i + 1);
        let key = rawKey, val = rawVal;
        try { key = decodeURIComponent(rawKey.replace(/\+/g, ' ')); } catch (_) { /* keep raw */ }
        try { val = decodeURIComponent(rawVal); } catch (_) { /* keep raw */ }
        return { rawKey, rawVal, key, val, hasEq: i >= 0 };
      });
    }
    const rawParam = p => (p.hasEq ? `${p.rawKey}=${p.rawVal}` : p.rawKey);
    function decodeSafe(s) { try { return decodeURIComponent(s); } catch (_) { return s; } }

    function analyze(raw) {
      let u;
      try { u = new URL(raw, location.href); } catch (_) { return null; }
      if (u.protocol !== 'http:' && u.protocol !== 'https:') return null;
      if (!/\.mp4$/i.test(u.pathname)) return null;

      const params = splitQuery(u.search);
      let expiry = null, token = null;
      for (const p of params) {
        if (!expiry && EXPIRY_KEYS.includes(p.key.toLowerCase()) && asTimestamp(p.val) !== null) expiry = p;
      }
      if (!expiry) for (const p of params) if (p.val.length >= 10 && asTimestamp(p.val) !== null) { expiry = p; break; }
      for (const p of params) {
        if (!token && p !== expiry && TOKEN_KEYS.includes(p.key.toLowerCase()) && p.val.length >= 6) token = p;
      }
      if (!token) {
        for (const p of params) {
          if (p !== expiry && p.val.length >= 16 && !/^\d+$/.test(p.val) && /^[\w\-+/=.~%]+$/.test(p.val)) { token = p; break; }
        }
      }
      const file = decodeSafe(u.pathname.split('/').pop() || 'video.mp4');
      const q = file.match(/(?:^|\D)(\d{3,4})p(?![a-z])/i) || u.pathname.match(/\/(\d{3,4})p\//i);
      u.hash = '';
      return {
        href: u.href, origin: u.origin, path: u.pathname, file,
        quality: q ? parseInt(q[1], 10) : null,
        preview: PREVIEW_RE.test(u.pathname),
        params, token, expiry,
        expSec: expiry ? asTimestamp(expiry.val) : null,
      };
    }

    // "<origin><path>?<token>&<expiry>&<other params>"
    function buildUrl(entry, origin) {
      const a = entry.signed || entry.plain;
      const parts = [];
      if (a.token) parts.push(rawParam(a.token));
      if (a.expiry) parts.push(rawParam(a.expiry));
      for (const p of a.params) if (p !== a.token && p !== a.expiry) parts.push(rawParam(p));
      return (origin || a.origin) + a.path + (parts.length ? '?' + parts.join('&') : '');
    }

    /* ------------------------------------------------------------------ *
     *  Store
     * ------------------------------------------------------------------ */
    const store = new Map();
    const seen = new Set();
    const relayQueue = [];

    function cleanUrl(s) {
      return String(s).trim()
        .replace(/\\u002[fF]/g, '/').replace(/\\u0026/g, '&').replace(/\\\//g, '/')
        .replace(/&amp;/g, '&')
        .replace(/[)\]}>,;'"]+$/, '');
    }

    function add(raw, source, referer) {
      if (!raw || typeof raw !== 'string' || !/mp4/i.test(raw)) return;
      const a = analyze(cleanUrl(raw));
      if (!a || seen.has(a.href)) return;
      seen.add(a.href);
      let e = store.get(a.path);
      if (!e) {
        e = {
          key: a.path, path: a.path, file: a.file, quality: a.quality, preview: a.preview,
          origins: new Set(), signed: null, plain: null, sources: new Set(),
          referer: referer || location.href, order: store.size,
        };
        store.set(a.path, e);
      }
      e.origins.add(a.origin);
      e.sources.add(source);
      if (a.token) {
        if (!e.signed || (a.expSec || 0) >= (e.signed.expSec || 0)) e.signed = a;
      } else if (!e.plain) {
        e.plain = a;
      }
      if (!IS_TOP) relayQueue.push(a.href);
      scheduleUpdate();
    }

    /* ------------------------------------------------------------------ *
     *  Passive (read-only, local) scanning — only runs when you ask
     * ------------------------------------------------------------------ */
    const ABS_RE = /(?:https?:)?\/\/[^\s"'<>`\\()[\]{}|^]+?\.mp4(?![\w.])(?:\?[^\s"'<>`\\()[\]{}|^#]*)?/gi;
    const REL_RE = /["'=(]\s*(\/[^\s"'<>`\\()/][^\s"'<>`\\()]*?\.mp4(?![\w.])(?:\?[^\s"'<>`\\()#]*)?)/gi;
    const ENC_RE = /https?%3A%2F%2F[^\s"'<>&]+/gi;

    function scanText(text, source) {
      if (!text || typeof text !== 'string') return;
      if (text.length > MAX_SCAN) text = text.slice(0, MAX_SCAN);
      if (!/mp4/i.test(text)) return;
      const t = text.replace(/\\u002[fF]/g, '/').replace(/\\u0026/g, '&').replace(/\\\//g, '/').replace(/&amp;/g, '&');
      let m;
      ABS_RE.lastIndex = 0;
      while ((m = ABS_RE.exec(t))) add(m[0], source);
      REL_RE.lastIndex = 0;
      while ((m = REL_RE.exec(t))) add(m[1], source);
      const enc = t.match(ENC_RE);
      if (enc) for (const s of enc) { const d = decodeSafe(s); if (/\.mp4/i.test(d)) add(d, source); }
      // [cums] player setup keeps its sources base64-encoded: { 'src': '<base64>', … }
      const B64_RE = /['"]src['"]\s*:\s*['"]([A-Za-z0-9+/=]{24,})['"]/g;
      while ((m = B64_RE.exec(text))) { try { const d = atob(m[1]); if (/\.mp4/i.test(d)) add(d, source); } catch (_) { /* not base64 */ } }
    }

    const DOM_SEL = 'video,audio,source,a[href],link[href],meta[content],embed,object,param,' +
      '[data-src],[data-url],[data-video],[data-mp4],[data-file],[data-href],[data-config],[data-setup],[data-sources]';

    function passiveScan() {
      for (const el of document.querySelectorAll(DOM_SEL)) {
        if (el instanceof HTMLMediaElement) {
          if (el.currentSrc) add(el.currentSrc, 'player');
          if (el.src) add(el.src, 'player');
        }
        for (const at of el.attributes) {
          const v = at.value;
          if (!v || !/mp4/i.test(v)) continue;
          if (/^\S+$/.test(v) && /\.mp4(\?|#|$)/i.test(v)) add(v, 'page');
          else scanText(v, 'page');
        }
      }
      for (const s of document.querySelectorAll('script:not([src])')) scanText(s.textContent, 'script');
      // The browser's own log of requests already made by the page (read-only).
      try { for (const en of performance.getEntriesByType('resource')) add(en.name, 'network'); } catch (_) { /* ignore */ }
    }

    /* ------------------------------------------------------------------ *
     *  Active capture
     *
     *  Why this is done the way it is (progressive MP4 from nginx):
     *  - The browser only adds a request to its resource log (Resource Timing) when that
     *    request ENDS. A player streaming a big byte range keeps one request open for a
     *    long time, so a URL is usually only visible after the NEXT seek closes it.
     *  - Seeking just past the buffered end often doesn't open a new request at all: the
     *    running download simply continues into that region.
     *  So: (1) make sure the player has started, (2) seek to the middle of a large unbuffered
     *  gap (forces a new byte-range request), (3) seek to a second, distant gap (closes
     *  request #2 so it gets logged), (4) poll the log until a signed URL shows up, retrying
     *  the seek pair up to 3 times, (5) put the player back exactly as it was.
     * ------------------------------------------------------------------ */
    const ROUNDS = 3;

    function bufferedRanges(v) {
      const out = [];
      try { for (let i = 0; i < v.buffered.length; i++) out.push([v.buffered.start(i), v.buffered.end(i)]); } catch (_) { /* ignore */ }
      return out.sort((a, b) => a[0] - b[0]);
    }

    // minGap: smallest gap (seconds) worth seeking into. Early seek passes a smaller value for short clips.
    function unbufferedGaps(v, minGap = 4) {
      const dur = v.duration;
      if (!isFinite(dur) || dur <= 0) return [];
      const endPad = Math.min(1, dur * 0.05);
      const gaps = [];
      let cursor = 0;
      for (const [s, e] of bufferedRanges(v)) {
        if (s - cursor > minGap) gaps.push([cursor, s]);
        cursor = Math.max(cursor, e);
      }
      if (dur - endPad - cursor > minGap) gaps.push([cursor, dur - endPad]);
      return gaps;
    }

    // Middle of the unbuffered gap whose middle is farthest from `avoid` (seconds).
    // Far jumps can't be satisfied by an already-running download, so a new request is made.
    function pickSeekTarget(v, avoid, minGap) {
      const gaps = unbufferedGaps(v, minGap);
      if (!gaps.length) return null;
      let best = null, bestDist = -1;
      for (const [s, e] of gaps) {
        const mid = (s + e) / 2;
        const dist = Math.abs(mid - avoid) + (e - s) * 0.25; // also favour big gaps
        if (dist > bestDist) { bestDist = dist; best = mid; }
      }
      return best;
    }

    function waitForEvent(v, names, ms) {
      return new Promise(resolve => {
        let done = false;
        const finish = ev => {
          if (done) return; done = true;
          names.forEach(n => v.removeEventListener(n, finish));
          resolve(ev ? ev.type : 'timeout');
        };
        names.forEach(n => v.addEventListener(n, finish));
        setTimeout(() => finish(null), ms);
      });
    }

    // Read-only observer on the browser's resource log. Kept alive while the dialog is open
    // (and for a while after a capture) so requests that finish late are still caught.
    let liveObs = null, liveObsTimer = null;
    function startLiveObserver(stopAfterMs, includeBuffered) {
      if (!liveObs) {
        try {
          liveObs = new PerformanceObserver(list => list.getEntries().forEach(en => add(en.name, 'player request')));
          liveObs.observe({ type: 'resource', buffered: !!includeBuffered });
        } catch (_) { liveObs = null; }
      }
      clearTimeout(liveObsTimer);
      if (stopAfterMs) liveObsTimer = setTimeout(stopLiveObserver, stopAfterMs);
    }
    function stopLiveObserver() {
      clearTimeout(liveObsTimer);
      try { liveObs && liveObs.disconnect(); } catch (_) { /* ignore */ }
      liveObs = null;
    }

    function scanResourceLog() {
      try { for (const en of performance.getEntriesByType('resource')) add(en.name, 'network'); } catch (_) { /* ignore */ }
      for (const v of document.querySelectorAll('video')) { if (v.currentSrc) add(v.currentSrc, 'player'); }
    }

    const signedSnapshot = () => new Set([...store.values()].filter(e => e.signed).map(e => e.signed.href));
    const hasNewSigned = snap => [...store.values()].some(e => e.signed && !snap.has(e.signed.href));

    async function waitForNewSigned(snap, ms) {
      const end = Date.now() + ms;
      while (Date.now() < end) {
        scanResourceLog();
        if (hasNewSigned(snap)) return true;
        await sleep(300);
      }
      scanResourceLog();
      return hasNewSigned(snap);
    }

    // play() can stay pending forever in a background tab that was never shown; never await it bare.
    const tryPlay = (v, ms) => Promise.race([
      Promise.resolve().then(() => v.play()).then(() => true, () => false),
      sleep(ms || 2000).then(() => false),
    ]);
    let lastStartBlocked = false;
    let lastFullyBuffered = false;

    /* ------------------------------------------------------------------ *
     *  [cums] Early seek (capture tabs only)
     *
     *  A short video arrives in ONE request to the vfile link, so the player never makes the
     *  follow-up range request to the signed fsN URL that the seek trick depends on, and by the
     *  time normal capture starts the whole file is buffered. Instead:
     *  - hold the player at preload="none" so nothing downloads until capture presses play;
     *  - the moment the file header is parsed (loadedmetadata), only the start of the file is in,
     *    so jump to the middle of the unbuffered part. That forces a new byte-range request, which
     *    goes straight to the redirected (signed) URL;
     *  - jump to a second, distant point so that request closes and the resource log records it;
     *  - put the player back where it was.
     *  Still a race: a file of a few MB on a fast connection can arrive before loadedmetadata.
     * ------------------------------------------------------------------ */
    let earlySeekP = null;                   // captureFromVideo waits for a running early seek
    let earlySeekDisarm = null;
    const isMainVideo = v => v instanceof HTMLMediaElement && v.tagName === 'VIDEO' &&
      !v.classList.contains('hover-preview-video') && !v.closest('.thumbnail');

    async function earlySeek(v) {
      const dur = v.duration;
      if (!isFinite(dur) || dur <= 0) return false;
      const minGap = Math.min(4, Math.max(0.5, dur * 0.15));
      const a = pickSeekTarget(v, 0, minGap);
      if (a === null) return false;          // already fully buffered; nothing left to request
      const snap = signedSnapshot();
      const t0 = v.currentTime, muted = v.muted;
      try {
        v.muted = true;
        v.currentTime = a;
        await waitForEvent(v, ['seeked'], 4000);
        await waitForEvent(v, ['progress', 'canplay'], 1500);
        if (!hasNewSigned(snap)) {
          const b = pickSeekTarget(v, a, minGap);
          if (b !== null) {
            v.currentTime = b;
            await waitForEvent(v, ['seeked'], 4000);
          }
        }
      } catch (_) { /* ignore */ } finally {
        try { v.currentTime = t0; v.muted = muted; } catch (_) { /* ignore */ }
      }
      // the restore seek closes the last open request; give the log a moment
      return waitForNewSigned(snap, 2000);
    }

    function armEarlySeek() {
      const done = new WeakMap();            // video -> src already handled
      const released = new WeakSet();        // videos whose loading we no longer hold back
      const hold = v => {
        if (!EARLY_SEEK_HOLD_PRELOAD || released.has(v) || !isMainVideo(v) || v.autoplay) return;
        if (v.getAttribute('preload') !== 'none') v.setAttribute('preload', 'none');
      };
      const onMeta = ev => {
        const v = ev.target;
        if (!isMainVideo(v)) return;
        released.add(v);
        const src = v.currentSrc || v.src;
        if (done.get(v) === src) return;
        done.set(v, src);
        const p = earlySeek(v).catch(() => false);
        earlySeekP = p;
        p.finally(() => { if (earlySeekP === p) earlySeekP = null; });
      };
      const onPlay = ev => { if (ev.target instanceof HTMLMediaElement) released.add(ev.target); };
      // media events don't bubble, but they do pass through document in the capture phase
      document.addEventListener('loadedmetadata', onMeta, true);
      document.addEventListener('play', onPlay, true);

      let mo = null;
      if (EARLY_SEEK_HOLD_PRELOAD) {
        mo = new MutationObserver(muts => {
          for (const m of muts) {
            if (m.type === 'attributes') { if (m.target.tagName === 'VIDEO') hold(m.target); continue; }
            for (const n of m.addedNodes) {
              if (n.nodeType !== 1) continue;
              if (n.tagName === 'VIDEO') hold(n);
              else if (n.querySelectorAll) n.querySelectorAll('video').forEach(hold);
            }
          }
        });
        const watch = () => mo.observe(document.documentElement, { childList: true, subtree: true, attributes: true, attributeFilter: ['preload'] });
        if (document.documentElement) watch();
        else {
          const wait = new MutationObserver(() => { if (document.documentElement) { wait.disconnect(); watch(); } });
          wait.observe(document, { childList: true });
        }
      }
      earlySeekDisarm = () => {
        document.removeEventListener('loadedmetadata', onMeta, true);
        document.removeEventListener('play', onPlay, true);
        try { mo && mo.disconnect(); } catch (_) { /* ignore */ }
        earlySeekDisarm = null;
      };
    }

    async function ensureStarted(v, report) {
      const hasData = () => v.readyState >= 2 && bufferedRanges(v).length > 0 && isFinite(v.duration);
      if (hasData()) return true;
      report('Starting playback so the player opens the file…');
      await tryPlay(v, 3000);
      await waitForEvent(v, ['playing', 'canplay'], 8000);
      const end = Date.now() + 4000;
      while (!hasData() && Date.now() < end) await sleep(200);
      if (!hasData()) lastStartBlocked = true;
      return hasData();
    }

    async function seekTo(v, t) {
      v.currentTime = t;
      await waitForEvent(v, ['seeked'], 5000);
      await waitForEvent(v, ['progress', 'canplay', 'playing'], 2500); // new request is delivering data
      await sleep(400);
    }

    async function captureFromVideo(v, snap, report) {
      const wasPaused = v.paused, t0 = v.currentTime, muted = v.muted;
      let found = false;
      try {
        v.muted = true;
        if (!(await ensureStarted(v, report))) {
          report('The player did not start (blocked or not ready). Press play on the video once, then capture again.');
          found = await waitForNewSigned(snap, 1500);
          return found;
        }
        // [cums] starting playback fired loadedmetadata; let the early seek finish before seeking here
        if (earlySeekP) { report('Seeking ahead before the video finishes buffering…'); await earlySeekP; }
        if (v.paused) await tryPlay(v, 2000);
        // Starting playback alone may already have logged it — a short video's first request
        // completes quickly (whole file), so give that longer.
        const short = isFinite(v.duration) && (v.duration <= 180 || pickSeekTarget(v, v.currentTime) === null);
        found = await waitForNewSigned(snap, short ? 4000 : 800);
        for (let round = 1; round <= ROUNDS && !found; round++) {
          const a = pickSeekTarget(v, v.currentTime);
          if (a === null) {
            lastFullyBuffered = true;
            report('The whole video was downloaded before capture started, so there is no new request to catch. Use "Reload & capture" (batch mode retries this automatically).');
            break;
          }
          report(`Attempt ${round}/${ROUNDS}: seeking to ${a.toFixed(0)}s to force a new request…`);
          await seekTo(v, a);
          const b = pickSeekTarget(v, a);
          if (b !== null) {
            report(`Attempt ${round}/${ROUNDS}: seeking to ${b.toFixed(0)}s so the previous request closes and gets logged…`);
            await seekTo(v, b);
          }
          found = await waitForNewSigned(snap, 2500);
        }
        return found;
      } finally {
        try {
          v.currentTime = t0;
          if (wasPaused) v.pause();
          v.muted = muted;
        } catch (_) { /* ignore */ }
      }
    }

    async function captureLocal(report) {
      startLiveObserver(IS_TOP ? 0 : 120000);
      const snap = signedSnapshot();
      passiveScan();
      if (hasNewSigned(snap)) return { videos: 0, found: true };
      const vids = [...document.querySelectorAll('video')];
      let found = false;
      for (const v of vids) {
        if (await captureFromVideo(v, snap, report)) { found = true; break; }
      }
      // the restore seek can close the last open request — give it a moment to be logged
      if (!found) found = await waitForNewSigned(snap, 2000);
      return { videos: vids.length, found };
    }

    // Top window: capture locally and ask same-page iframes (embedded players) to do the same.
    async function captureAll(report) {
      const snap = signedSnapshot();
      const frames = [...document.querySelectorAll('iframe')];
      for (const f of frames) {
        try { f.contentWindow.postMessage({ [MSG_KEY + '_capture']: 1 }, '*'); } catch (_) { /* ignore */ }
      }
      const res = await captureLocal(report);
      if (!hasNewSigned(snap) && frames.length) {
        report('Waiting for embedded players…');
        const end = Date.now() + 25000;
        while (!hasNewSigned(snap) && Date.now() < end) await sleep(300);
      }
      if (!res.videos && !frames.length) report('No <video> element on this page.');
      return hasNewSigned(snap);
    }

    // Last resort, only from "Get token": one request to see if the server redirects to a signed URL.
    function probeRedirect(url, referer) {
      return new Promise(resolve => {
        let settled = false, req = null;
        const finish = v => {
          if (settled) return;
          settled = true; resolve(v || null);
          try { req && req.abort && req.abort(); } catch (_) { /* ignore */ }
        };
        try {
          req = GM_xmlhttpRequest({
            method: 'GET', url, timeout: 15000,
            headers: { Range: 'bytes=0-0', Referer: referer || location.href },
            onreadystatechange: r => { if (r.readyState >= 2 && r.finalUrl) finish(r.finalUrl); },
            onload: r => finish(r.finalUrl), onerror: () => finish(null),
            ontimeout: () => finish(null), onabort: () => finish(null),
          });
        } catch (_) { finish(null); }
        setTimeout(() => finish(null), 16000);
      });
    }

    // [cums] The token lives only on the REDIRECT TARGET of the player's source link
    // (cums.net/vfile/… -> fsN.cums.net/…?t=…&exp=…). The request log records the URL that was
    // asked for, not where it was redirected, which is why seeking was needed (the follow-up
    // range requests go straight to the redirected URL). Short videos load in one request and never
    // make a follow-up. Following the redirect directly needs no player and no seeking.
    async function resolveRedirects(report) {
      const cands = [...store.values()]
        .filter(e => !e.signed && e.plain && !e.preview && !e.redirectTried)
        .sort((a, b) => (b.quality || 0) - (a.quality || 0));
      for (const e of cands) {
        e.redirectTried = true;
        report(`Following the ${e.quality ? e.quality + 'p ' : ''}file link to the file server…`);
        const final = await probeRedirect(e.plain.href, e.referer);
        if (final && final !== e.plain.href) add(final, 'redirect', e.referer);
        if (currentResult(true).ok) return true;
      }
      return currentResult(true).ok;
    }

    /* ------------------------------------------------------------------ *
     *  Updates / iframe relay
     * ------------------------------------------------------------------ */
    let updTimer = null;
    function scheduleUpdate() {
      if (updTimer) return;
      updTimer = setTimeout(() => {
        updTimer = null;
        if (!IS_TOP) {
          if (relayQueue.length) {
            const batch = relayQueue.splice(0, relayQueue.length);
            try { window.top.postMessage({ [MSG_KEY]: batch, referer: location.href }, '*'); } catch (_) { /* ignore */ }
          }
        } else {
          ui.refresh();
        }
      }, 250);
    }

    // Passive listener only; does nothing unless the top window asks.
    window.addEventListener('message', ev => {
      const d = ev.data;
      if (!d || typeof d !== 'object') return;
      if (IS_TOP && Array.isArray(d[MSG_KEY])) {
        const ref = typeof d.referer === 'string' ? d.referer : undefined;
        d[MSG_KEY].slice(0, 500).forEach(u => { if (typeof u === 'string') add(u, 'iframe', ref); });
      }
      if (!IS_TOP && d[MSG_KEY + '_scan']) { startLiveObserver(120000); passiveScan(); scheduleUpdate(); }
      if (!IS_TOP && d[MSG_KEY + '_capture']) { captureLocal(() => {}).then(scheduleUpdate); }
    });

    function askFramesToScan() {
      for (const f of document.querySelectorAll('iframe')) {
        try { f.contentWindow.postMessage({ [MSG_KEY + '_scan']: 1 }, '*'); } catch (_) { /* ignore */ }
      }
    }

    if (!IS_TOP) return; // iframes: nothing else to do

    /* ------------------------------------------------------------------ *
     *  Results (plain objects for integrators)
     * ------------------------------------------------------------------ */
    function sortEntries() {
      const rank = e => (e.signed ? 0 : e.preview ? 2 : 1);
      return [...store.values()].sort((a, b) =>
        rank(a) - rank(b) || (b.quality || 0) - (a.quality || 0) || a.order - b.order);
    }

    function describe(e) {
      const a = e.signed || e.plain;
      return {
        file: e.file,
        quality: e.quality,
        preview: e.preview,
        signed: !!e.signed,
        expired: !!(e.signed && e.signed.expSec && e.signed.expSec <= nowSec()),
        mp4Url: a.origin + a.path,
        servers: [...e.origins],
        token: a.token ? { name: a.token.key, value: a.token.val, raw: a.token.rawVal } : null,
        expiry: a.expiry ? {
          name: a.expiry.key, value: a.expiry.val, epoch: a.expSec,
          iso: a.expSec ? new Date(a.expSec * 1000).toISOString() : null,
        } : null,
        completedUrl: buildUrl(e, a.origin),
        referer: e.referer,
        foundVia: [...e.sources],
      };
    }

    function currentResult(requireSigned) {
      const files = sortEntries().map(describe);
      const best = files.find(f => f.signed && !f.expired && !f.preview) ||
        files.find(f => f.signed && !f.expired) ||
        (requireSigned ? null : (files.find(f => !f.preview) || files[0] || null));
      return { ok: !!best, pageUrl: location.href, title: document.title, files, best };
    }

    /* ------------------------------------------------------------------ *
     *  Batch worker: runs ONLY in a tab opened by MP4Grabber.grab()
     * ------------------------------------------------------------------ */
    const JOB_PREFIX = 'mp4grab:job:';
    const RES_PREFIX = 'mp4grab:res:';
    const STATUS_PREFIX = 'mp4grab:status:';

    function normUrl(u) {
      try { const x = new URL(u, location.href); return x.origin + x.pathname.replace(/\/+$/, '') + x.search; } catch (_) { return String(u); }
    }

    function findMyJob() {
      try {
        const m = location.hash.match(/mp4grab-([\w-]+)/);
        if (m) { const j = GM_getValue(JOB_PREFIX + m[1], null); if (j) return j; }
        // Fallback (e.g. a challenge page reloaded without the #marker): recent job for this exact URL.
        const here = normUrl(location.href);
        for (const k of GM_listValues()) {
          if (!k.startsWith(JOB_PREFIX)) continue;
          const j = GM_getValue(k, null);
          if (j && Date.now() - j.created < 5 * 60e3 && normUrl(j.url) === here) return j;
        }
      } catch (_) { /* GM storage unavailable */ }
      return null;
    }

    async function runJob(job) {
      const status = msg => { try { GM_setValue(STATUS_PREFIX + job.id, { msg, at: Date.now() }); } catch (_) { /* ignore */ } };
      const fail = (reason, extra) => GM_setValue(RES_PREFIX + job.id,
        { ...currentResult(job.requireSigned), ok: false, reason, ...extra });

      // [cums] Follow the page's source links first: no player, no seeking, works for any length.
      passiveScan();
      if (!(await resolveRedirects(status))) {
        status('Page loaded; waiting for the player…');
        // [cums] The site now builds the player lazily (first touch, or idle after load). The bare
        // <video id="player"> is in the markup from the start but has no source until then, so
        // "a <video> exists" is no longer "the player is ready". A synthetic pointerdown takes the
        // site's own "visitor touched the page" path: it boots the player without asking it to play.
        try { document.dispatchEvent(new Event('pointerdown', { bubbles: true })); } catch (_) { /* ignore */ }
        const sourced = () => [...document.querySelectorAll('video')].some(v => isMainVideo(v) &&
          (v.currentSrc || v.getAttribute('src') || v.querySelector('source[src]')));
        const end = Date.now() + job.waitForPlayerMs;
        while (!sourced() && Date.now() < end) await sleep(500);
        // no sourced <video>: fall back to the old test (embedded players live in iframes)
        if (!sourced() && !document.querySelector('video, iframe')) return fail('no-player');
        await sleep(job.settleMs);

        startLiveObserver(0, true);            // normally already running since document-start
        lastStartBlocked = false;
        lastFullyBuffered = false;
        passiveScan();
        // The player's own source link (currentSrc) is now known too; seeking is the last resort.
        if (!(await resolveRedirects(status)) && !currentResult(true).ok) await captureAll(status);
        passiveScan();
      }
      stopLiveObserver();

      const res = currentResult(job.requireSigned);
      if (job.interactive) {
        try { GM_deleteValue(JOB_PREFIX + job.id); } catch (_) { /* ignore */ }
        ui.open(res.ok ? 'Captured after reload.' : 'Reloaded, but no signed URL was seen. Make sure the video can play, then try "Capture from player".');
        return;
      }
      if (res.ok) return GM_setValue(RES_PREFIX + job.id, { ...res, reason: null });
      return fail(lastStartBlocked && document.hidden ? 'background-media-blocked'
        : lastFullyBuffered ? 'fully-buffered' : 'no-signed-url');
    }

    // Manual mode: reload this tab with the observer running from the very start.
    function reloadAndCapture() {
      const id = Date.now().toString(36) + Math.random().toString(36).slice(2, 8);
      GM_setValue(JOB_PREFIX + id, {
        id, url: location.href, created: Date.now(), interactive: true,
        waitForPlayerMs: 25000, settleMs: 1500, requireSigned: true,
      });
      location.reload();
    }

    /* ------------------------------------------------------------------ *
     *  Public API (for the batch script)
     * ------------------------------------------------------------------ */
    function runAttempt(pageUrl, attempt, foreground, o) {
      return new Promise(resolve => {
        const id = Date.now().toString(36) + Math.random().toString(36).slice(2, 8);
        const job = {
          id, url: pageUrl, created: Date.now(), attempt,
          waitForPlayerMs: o.waitForPlayerMs, settleMs: o.settleMs, requireSigned: o.requireSigned,
        };
        let tab = null, finished = false, timer = null;
        const ls = [];
        const finish = r => {
          if (finished) return;
          finished = true;
          clearTimeout(timer);
          ls.forEach(l => { try { GM_removeValueChangeListener(l); } catch (_) { /* ignore */ } });
          for (const p of [JOB_PREFIX, RES_PREFIX, STATUS_PREFIX]) { try { GM_deleteValue(p + id); } catch (_) { /* ignore */ } }
          if (tab && !o.keepTabOpen) { try { tab.close(); } catch (_) { /* ignore */ } }
          resolve({ ...r, attempt, foreground });
        };
        const empty = reason => ({ ok: false, reason, pageUrl, files: [], best: null });
        // [cums] cancelling the queue closes the capture tab right away
        if (o.signal) {
          if (o.signal.aborted) { finish(empty('cancelled')); return; }
          o.signal.addEventListener('abort', () => finish(empty('cancelled')), { once: true });
        }

        GM_setValue(JOB_PREFIX + id, job);
        ls.push(GM_addValueChangeListener(RES_PREFIX + id, (k, old, val) => { if (val) finish(val); }));
        ls.push(GM_addValueChangeListener(STATUS_PREFIX + id, (k, old, val) => {
          if (val && o.onProgress) { try { o.onProgress({ pageUrl, attempt, foreground, message: val.msg }); } catch (_) { /* ignore */ } }
        }));
        timer = setTimeout(() => finish(empty('timeout')), o.attemptTimeoutMs);

        const u = new URL(pageUrl, location.href);
        u.hash = 'mp4grab-' + id;
        try {
          tab = GM_openInTab(u.href, { active: foreground, insert: true, setParent: true });
          if (tab) tab.onclose = () => finish(empty('tab-closed'));
        } catch (err) {
          finish(empty('open-failed: ' + err));
        }
      });
    }

    /**
     * Open pageUrl in a (background) tab, capture the signed MP4 URL(s), close the tab.
     * Retries automatically. Resolves (never rejects) with:
     *   { ok, reason, pageUrl, title, files: [FileInfo], best: FileInfo|null, attempt, attempts, foreground }
     */
    async function grab(pageUrl, opts) {
      const o = {
        retries: 3,                 // re-attempts after the first try (4 tries total)
        backgroundAttempts: 2,      // tries done in a background tab before switching to a visible one
        allowForeground: true,      // may open a visible tab if background tabs can't play video
        attemptTimeoutMs: 90000,    // per try (background tabs are throttled, so be generous)
        waitForPlayerMs: 25000,     // how long the tab waits for a <video>/<iframe> to appear
        settleMs: 1500,             // pause after the player appears, before touching it
        requireSigned: true,        // ok only if a signed (tokened) URL was captured
        keepTabOpen: false,
        onProgress: null,           // fn({ pageUrl, attempt, foreground, message })
        signal: null,               // [cums] AbortSignal: stop retrying and close the tab
        ...(opts || {}),
      };
      const total = 1 + Math.max(0, o.retries);
      let forceForeground = false, last = null;
      for (let attempt = 1; attempt <= total; attempt++) {
        if (o.signal && o.signal.aborted) return { ok: false, reason: 'cancelled', pageUrl, files: [], best: null, attempt, attempts: attempt - 1, foreground: false };
        const foreground = o.allowForeground && (forceForeground || attempt > o.backgroundAttempts);
        if (o.onProgress) { try { o.onProgress({ pageUrl, attempt, foreground, message: `Attempt ${attempt}/${total} (${foreground ? 'visible' : 'background'} tab)` }); } catch (_) { /* ignore */ } }
        last = await runAttempt(pageUrl, attempt, foreground, o);
        if (last.ok) return { ...last, attempts: attempt };
        if (last.reason === 'cancelled') return { ...last, ok: false, attempts: attempt };
        if (last.reason === 'background-media-blocked' && o.allowForeground) forceForeground = true;
        await sleep(1000);
      }
      return { ...last, ok: false, attempts: total };
    }

    /** Capture on the CURRENT page (no new tab). Same result shape as grab(), minus attempt fields. */
    async function captureHere(opts) {
      const o = { requireSigned: true, onProgress: null, ...(opts || {}) };
      startLiveObserver(60000);
      const rep = msg => { if (o.onProgress) { try { o.onProgress({ pageUrl: location.href, message: msg }); } catch (_) { /* ignore */ } } };
      passiveScan();
      if (!(await resolveRedirects(rep))) await captureAll(rep);   // [cums] redirect first, seeking last
      passiveScan();
      const res = currentResult(o.requireSigned);
      return { ...res, reason: res.ok ? null : 'no-signed-url' };
    }

    /** Download a FileInfo (e.g. result.best) with GM_download. Resolves on completion, rejects on error. */
    function download(fileInfo, opts) {
      const o = { name: null, server: null, onProgress: null, saveAs: false, signal: null, ...(opts || {}) };
      return new Promise((resolve, reject) => {
        if (!fileInfo || !fileInfo.completedUrl) { reject(new Error('No completedUrl to download')); return; }
        // [cums] AbortSignal support: aborts the GM_download transfer
        let handle = null;
        const onAbort = () => { try { handle && handle.abort && handle.abort(); } catch (_) { /* ignore */ } reject(new DOMException('Cancelled', 'AbortError')); };
        const off = () => { if (o.signal) o.signal.removeEventListener('abort', onAbort); };
        if (o.signal) { if (o.signal.aborted) { onAbort(); return; } o.signal.addEventListener('abort', onAbort, { once: true }); }
        let url = fileInfo.completedUrl;
        if (o.server) { const u = new URL(url); const s = new URL(o.server); u.protocol = s.protocol; u.host = s.host; url = u.href; }
        let name = (o.name || fileInfo.file || 'video.mp4').replace(/[\\:*?"<>|]+/g, '_').trim();
        if (!/\.mp4$/i.test(name)) name += '.mp4';
        try {
          handle = GM_download({
            url, name, saveAs: o.saveAs,
            headers: { Referer: fileInfo.referer || location.href },
            onprogress: p => { if (o.onProgress) { try { o.onProgress({ loaded: p.loaded || p.done || 0, total: p.total || p.totalSize || 0 }); } catch (_) { /* ignore */ } } },
            onload: () => { off(); resolve({ url, name }); },
            onerror: err => { off(); reject(Object.assign(new Error(explainDlError(err)), { code: err && err.error, details: err && err.details })); },
            ontimeout: () => { off(); reject(new Error('Download timed out')); },
          });
        } catch (err) { reject(err); }
      });
    }

    const MP4Grabber = { grab, captureHere, download, version: '3.1.0' };
    try { window.MP4Grabber = MP4Grabber; } catch (_) { /* ignore */ }


    /* ------------------------------------------------------------------ *
     *  UI
     * ------------------------------------------------------------------ */
    function h(tag, props, ...kids) {
      const el = document.createElement(tag);
      for (const [k, v] of Object.entries(props || {})) {
        if (v == null || v === false) continue;
        if (k === 'class') el.className = v;
        else if (k.startsWith('on') && typeof v === 'function') el.addEventListener(k.slice(2), v);
        else if (k === 'value') el.value = v;
        else el.setAttribute(k, v === true ? '' : v);
      }
      for (const k of kids.flat()) if (k != null && k !== false) el.append(k instanceof Node ? k : String(k));
      return el;
    }

    function fmtBytes(n) {
      if (!n && n !== 0) return '?';
      const u = ['B', 'KB', 'MB', 'GB']; let i = 0;
      while (n >= 1024 && i < u.length - 1) { n /= 1024; i++; }
      return `${n.toFixed(i ? 1 : 0)} ${u[i]}`;
    }

    function fmtRemaining(sec) {
      const neg = sec < 0; let s = Math.abs(sec);
      const d = Math.floor(s / 86400); s %= 86400;
      const hh = Math.floor(s / 3600); s %= 3600;
      const mm = Math.floor(s / 60); s %= 60;
      const txt = (d ? `${d}d ` : '') + (d || hh ? `${hh}h ` : '') + `${mm}m ${s}s`;
      return neg ? `expired ${txt} ago` : `valid for ${txt}`;
    }

    function explainDlError(err) {
      const code = err && err.error;
      let det = err && err.details;
      det = det ? ` (${typeof det === 'string' ? det : JSON.stringify(det)})` : '';
      const map = {
        not_enabled: 'Downloads are disabled in Tampermonkey settings.',
        not_whitelisted: 'Tampermonkey blocked the file type. Settings → Config mode: Advanced → Downloads BETA → add .mp4 to "Whitelisted File Extensions".',
        not_permitted: 'Tampermonkey lacks the browser "downloads" permission — allow it when prompted or set Download Mode to "Browser API".',
        not_supported: 'This download mode is not supported by the browser.',
        not_succeeded: 'The server refused or the transfer failed — the token may be expired or tied to another IP/referrer. Reload the page and capture again.',
      };
      return (map[code] || `Download failed: ${code || 'unknown error'}`) + det;
    }

    const CSS = `
      :host { all: initial; }
      * { box-sizing: border-box; font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; }
      .open { position: fixed; top: 8px; left: 50%; transform: translateX(-50%); z-index: 2147483647;
        background: #1f6feb; color: #fff; border: 0; border-radius: 999px; padding: 6px 16px;
        font-size: 13px; font-weight: 600; cursor: pointer; box-shadow: 0 2px 10px rgba(0,0,0,.4); }
      .open:hover { background: #388bfd; }
      .overlay { position: fixed; inset: 0; z-index: 2147483647; background: rgba(0,0,0,.55);
        display: flex; align-items: flex-start; justify-content: center; padding-top: 48px; }
      .dlg { width: min(1000px, 96vw); height: min(680px, 88vh); background: #16181d; color: #e6e6e6;
        border-radius: 10px; display: grid; grid-template-rows: auto auto 1fr; overflow: hidden;
        box-shadow: 0 10px 40px rgba(0,0,0,.6); font-size: 13px; }
      .hdr { display: flex; align-items: center; gap: 8px; padding: 10px 14px; border-bottom: 1px solid #2a2e36; }
      .hdr .title { font-weight: 700; font-size: 14px; flex: 1; }
      .gstatus { padding: 6px 14px; color: #9aa3ae; font-size: 12px; border-bottom: 1px solid #2a2e36; min-height: 28px; }
      .body { display: grid; grid-template-columns: 330px 1fr; min-height: 0; }
      .list { overflow: auto; border-right: 1px solid #2a2e36; }
      .item { padding: 8px 12px; border-bottom: 1px solid #22262d; cursor: pointer; }
      .item:hover { background: #1d2129; }
      .item.sel { background: #22324d; }
      .name { word-break: break-all; font-weight: 600; }
      .sub { color: #9aa3ae; font-size: 11px; word-break: break-all; margin-top: 2px; }
      .badge { display: inline-block; font-size: 11px; padding: 1px 6px; border-radius: 4px; margin: 4px 4px 0 0; color: #fff; }
      .ok { background: #1a7f37; } .warn { background: #9a6700; } .bad { background: #b42318; }
      .info { background: #2f5fa7; } .mute { background: #3a3f48; }
      .detail { padding: 14px 16px; overflow: auto; }
      .empty { padding: 18px; color: #9aa3ae; line-height: 1.5; }
      .lbl { display: block; color: #9aa3ae; font-size: 11px; text-transform: uppercase; letter-spacing: .05em; margin: 14px 0 4px; }
      .val { background: #0e1014; border: 1px solid #2a2e36; border-radius: 6px; padding: 6px 8px; word-break: break-all;
        font-family: ui-monospace, Consolas, monospace; font-size: 12px; user-select: text; }
      .hint { color: #9aa3ae; font-size: 12px; margin-top: 4px; }
      textarea, input, select { width: 100%; background: #0e1014; color: #e6e6e6; border: 1px solid #2a2e36; border-radius: 6px;
        padding: 6px 8px; font-family: ui-monospace, Consolas, monospace; font-size: 12px; }
      textarea { resize: vertical; min-height: 70px; }
      .row { display: flex; gap: 8px; flex-wrap: wrap; margin-top: 16px; }
      button.b { background: #2a2e36; color: #e6e6e6; border: 1px solid #3a3f48; border-radius: 6px; padding: 7px 12px; cursor: pointer; font-size: 13px; }
      button.b:hover { background: #343a44; }
      button.primary { background: #1f6feb; border-color: #1f6feb; color: #fff; font-weight: 700; }
      button.primary:hover { background: #388bfd; }
      button:disabled { opacity: .5; cursor: default; }
      .prog { height: 6px; background: #0e1014; border-radius: 3px; overflow: hidden; margin-top: 14px; }
      .prog > div { height: 100%; width: 0; background: #2ea043; transition: width .2s; }
      .status { margin-top: 6px; color: #9aa3ae; min-height: 1.3em; word-break: break-word; }
      .status.err { color: #ff7b72; }
    `;

    const ui = (() => {
      let host, root, openBtn, overlay = null, listEl, detailEl, gStatusEl, captureBtn;
      let selectedKey = null, tick = null, lastDetailSig = '', busy = false;
      const chosenOrigin = {};
      const nameOverride = {};
      const state = {};
      const st = key => (state[key] = state[key] || { status: '', err: false, progress: 0, dl: null });

      function mount() {
        if (host || !document.documentElement) return;
        host = document.createElement('div');
        host.style.cssText = 'all: initial; position: fixed; z-index: 2147483647;';
        root = host.attachShadow({ mode: 'closed' });
        root.append(h('style', null, CSS));
        openBtn = h('button', { class: 'open', title: 'Show MP4 files on this page', onclick: () => open() }, 'MP4');
        root.append(openBtn);
        for (const t of ['keydown', 'keyup', 'keypress']) root.addEventListener(t, ev => ev.stopPropagation());
        document.documentElement.append(host);
      }

      function statusOf(e) {
        if (e.signed) {
          if (e.signed.expSec && e.signed.expSec <= nowSec()) return ['Expired', 'bad'];
          return ['Signed', 'ok'];
        }
        if (e.preview) return ['Preview · no token needed', 'info'];
        return ['No token yet', 'warn'];
      }

      const sorted = sortEntries;

      function currentUrl(e) {
        const a = e.signed || e.plain;
        return buildUrl(e, chosenOrigin[e.key] || a.origin);
      }

      function setGlobal(txt) { if (gStatusEl) gStatusEl.textContent = txt; }

      async function runCapture() {
        if (busy) return;
        busy = true; if (captureBtn) captureBtn.disabled = true;
        const before = signedSnapshot();
        await captureAll(setGlobal);
        const fresh = [...store.values()].filter(e => e.signed && !before.has(e.signed.href));
        setGlobal(fresh.length
          ? `Captured ${fresh.length} signed URL${fresh.length > 1 ? 's' : ''} from the player.`
          : 'No new signed URL seen yet. Still listening — a late request will appear here automatically. If the video is fully buffered, reload the page and capture earlier.');
        if (fresh.length) selectedKey = fresh.sort((a, b) => (b.quality || 0) - (a.quality || 0))[0].key;
        busy = false; if (captureBtn) captureBtn.disabled = false;
        if (!overlay) stopLiveObserver();
        lastDetailSig = '';
        refresh(true);
      }

      function open(msg) {
        mount();
        if (overlay) { if (msg) setGlobal(msg); return; }
        overlay = h('div', { class: 'overlay', onclick: ev => { if (ev.target === overlay) close(); } });
        listEl = h('div', { class: 'list' });
        detailEl = h('div', { class: 'detail' });
        gStatusEl = h('div', { class: 'gstatus' }, msg || 'Local scan done. Use "Capture from player" if the signed file isn\'t listed yet. For short videos use "Reload & capture".');
        captureBtn = h('button', { class: 'b primary', onclick: runCapture, title: 'Seek past the buffered part so the player requests the file again, and record that request' }, 'Capture from player');
        overlay.append(h('div', { class: 'dlg' },
          h('div', { class: 'hdr' },
            h('div', { class: 'title' }, 'MP4 files on this page'),
            captureBtn,
            h('button', { class: 'b', onclick: reloadAndCapture, title: 'Reload this page with capture listening from the very first request (needed for short videos)' }, 'Reload & capture'),
            h('button', { class: 'b', onclick: () => { passiveScan(); askFramesToScan(); refresh(true); setGlobal('Rescanned (local, read-only).'); } }, 'Rescan'),
            h('button', { class: 'b', onclick: close }, 'Close')),
          gStatusEl,
          h('div', { class: 'body' }, listEl, detailEl)));
        root.append(overlay);
        root.addEventListener('keydown', onEsc);
        startLiveObserver(0);       // read-only; catches requests that finish while the dialog is open
        passiveScan();
        askFramesToScan();
        lastDetailSig = '';
        refresh(true);
        tick = setInterval(updateCountdown, 1000);
      }

      function onEsc(ev) { if (ev.key === 'Escape' && overlay) close(); }

      function close() {
        if (!overlay) return;
        overlay.remove(); overlay = null; gStatusEl = null; captureBtn = null;
        root.removeEventListener('keydown', onEsc);
        clearInterval(tick); tick = null;
        if (!busy) stopLiveObserver();
      }

      function refresh(forceDetail) {
        if (!host) return;
        openBtn.textContent = store.size ? `MP4 · ${store.size}` : 'MP4';
        if (!overlay) return;
        renderList();
        renderDetail(forceDetail);
      }

      function renderList() {
        const items = sorted();
        if (selectedKey && !store.has(selectedKey)) selectedKey = null;
        if (!selectedKey && items.length) selectedKey = items[0].key;
        listEl.replaceChildren();
        if (!items.length) {
          listEl.append(h('div', { class: 'empty' },
            'No .mp4 files found yet. Start the video, then press "Capture from player".'));
          return;
        }
        for (const e of items) {
          const [label, cls] = statusOf(e);
          const a = e.signed || e.plain;
          listEl.append(h('div', {
            class: 'item' + (e.key === selectedKey ? ' sel' : ''),
            onclick: () => { selectedKey = e.key; lastDetailSig = ''; refresh(true); },
          },
          h('div', { class: 'name' }, e.file),
          h('div', { class: 'sub' }, new URL(a.origin).host + e.path.replace(/[^/]+$/, '')),
          h('span', { class: 'badge ' + cls }, label),
          e.quality ? h('span', { class: 'badge mute' }, `${e.quality}p`) : null,
          e.origins.size > 1 ? h('span', { class: 'badge mute' }, `${e.origins.size} servers`) : null));
        }
      }

      let countdownEl = null, countdownEntry = null;
      function updateCountdown() {
        if (countdownEl && countdownEntry && countdownEntry.signed && countdownEntry.signed.expSec) {
          countdownEl.textContent = fmtRemaining(countdownEntry.signed.expSec - nowSec());
        }
      }

      function renderDetail(force) {
        const e = selectedKey && store.get(selectedKey);
        const sig = e ? [e.key, e.signed && e.signed.href, e.plain && e.plain.href, e.origins.size].join('|') : '';
        if (!force && sig === lastDetailSig) return;
        lastDetailSig = sig;
        detailEl.replaceChildren();
        countdownEl = null; countdownEntry = null;
        if (!e) { detailEl.append(h('div', { class: 'empty' }, 'Select a file on the left.')); return; }

        const a = e.signed || e.plain;
        const s = st(e.key);
        const [label, cls] = statusOf(e);
        const origin = chosenOrigin[e.key] || a.origin;

        let serverField = null;
        if (e.origins.size > 1) {
          const sel = h('select', {
            onchange: ev => { chosenOrigin[e.key] = ev.target.value; lastDetailSig = ''; renderDetail(true); },
          }, [...e.origins].map(o => {
            const opt = h('option', { value: o }, new URL(o).host + (o === a.origin ? '  (token captured here)' : ''));
            if (o === origin) opt.selected = true;
            return opt;
          }));
          serverField = [h('span', { class: 'lbl' }, 'File server'), sel,
            h('div', { class: 'hint' }, 'Mirrors usually share the signing secret, but not always.')];
        }

        let tokenNode;
        if (a.token) tokenNode = h('div', { class: 'val' }, `${a.token.key} = ${a.token.val}`);
        else if (e.preview) tokenNode = h('div', { class: 'val' }, '— none (preview file, served without a token)');
        else tokenNode = h('div', { class: 'val' }, '— none captured yet (press "Get token")');

        let expNode;
        if (a.expiry && a.expSec) {
          countdownEl = h('div', { class: 'hint' });
          countdownEntry = e;
          expNode = [h('div', { class: 'val' },
            `${a.expiry.key} = ${a.expiry.val}   →   ${new Date(a.expSec * 1000).toLocaleString()}`), countdownEl];
        } else {
          expNode = h('div', { class: 'val' }, a.token ? '— no expiry parameter in this URL' : '—');
        }

        const nameInput = h('input', {
          value: nameOverride[e.key] || e.file,
          oninput: ev => { nameOverride[e.key] = ev.target.value; },
        });
        const progBar = h('div');
        progBar.style.width = `${Math.round((s.progress || 0) * 100)}%`;
        const statusEl = h('div', { class: 'status' + (s.err ? ' err' : '') }, s.status);
        const setStatus = (txt, err) => { s.status = txt; s.err = !!err; statusEl.textContent = txt; statusEl.className = 'status' + (err ? ' err' : ''); };
        const setProgress = f => { s.progress = f; progBar.style.width = `${Math.round(f * 100)}%`; };

        const dlBtn = h('button', { class: 'b primary', disabled: !!s.dl }, 'Download');
        const cancelBtn = h('button', { class: 'b', hidden: !s.dl }, 'Cancel');
        const tokBtn = h('button', { class: 'b' }, e.signed ? 'Re-capture token' : 'Get token');

        dlBtn.addEventListener('click', () => {
          const url = currentUrl(e);
          let name = (nameInput.value || e.file).replace(/[\\/:*?"<>|]+/g, '_').trim() || 'video.mp4';
          if (!/\.mp4$/i.test(name)) name += '.mp4';
          if (e.signed && e.signed.expSec && e.signed.expSec <= nowSec()) {
            setStatus('Warning: this token has expired — the server will probably refuse it. Reload the page and capture again.', true);
          } else setStatus('Starting download…');
          setProgress(0);
          const done = () => { s.dl = null; dlBtn.disabled = false; cancelBtn.hidden = true; };
          try {
            s.dl = GM_download({
              url, name, saveAs: false,
              headers: { Referer: e.referer || location.href },
              onprogress: p => {
                const total = p.total || p.totalSize || 0;
                const loaded = p.loaded || p.done || 0;
                if (total) { setProgress(loaded / total); setStatus(`Downloading… ${fmtBytes(loaded)} / ${fmtBytes(total)}`); }
                else setStatus(`Downloading… ${fmtBytes(loaded)}`);
              },
              onload: () => { done(); setProgress(1); setStatus(`Download complete: ${name}`); },
              onerror: err => { done(); setStatus(explainDlError(err), true); },
              ontimeout: () => { done(); setStatus('Download timed out.', true); },
            });
            dlBtn.disabled = true; cancelBtn.hidden = false;
          } catch (err) { done(); setStatus('GM_download threw: ' + err, true); }
        });

        cancelBtn.addEventListener('click', () => {
          try { s.dl && s.dl.abort && s.dl.abort(); } catch (_) { /* ignore */ }
          s.dl = null; dlBtn.disabled = false; cancelBtn.hidden = true; setStatus('Download cancelled.');
        });

        tokBtn.addEventListener('click', async () => {
          if (busy) return;
          tokBtn.disabled = true;
          const before = e.signed && e.signed.href;
          const got = () => !!e.signed && e.signed.href !== before && (!e.signed.expSec || e.signed.expSec > nowSec());
          busy = true;
          await captureAll(txt => setStatus(txt));
          busy = false;
          if (!overlay) stopLiveObserver();
          if (!got() && !e.signed && (e.plain)) {
            setStatus('Player capture found nothing — asking the file server once (redirect check)…');
            const final = await probeRedirect(e.plain.href, e.referer);
            if (final) add(final, 'redirect', e.referer);
          }
          const ok = got();
          s.status = ok ? 'New token captured ✔'
            : e.signed ? 'No newer token seen — the one shown is what the player is currently using.'
              : 'No token found. Play the video, then try again (seeking must reach an unbuffered part).';
          s.err = !ok && !e.signed;
          tokBtn.disabled = false;
          lastDetailSig = '';
          refresh(true);
        });

        detailEl.append(...[
          h('div', { class: 'name' }, e.file),
          h('span', { class: 'badge ' + cls }, label),
          e.quality ? h('span', { class: 'badge mute' }, `${e.quality}p`) : null,
          serverField,
          h('span', { class: 'lbl' }, 'MP4 URL'),
          h('div', { class: 'val' }, origin + e.path),
          h('span', { class: 'lbl' }, 'Token'), tokenNode,
          h('span', { class: 'lbl' }, 'Expiry'), expNode,
          h('span', { class: 'lbl' }, 'Completed URL'),
          h('textarea', { readonly: true, rows: 3, onfocus: ev => ev.target.select() }, currentUrl(e)),
          h('span', { class: 'lbl' }, 'Save as'), nameInput,
          h('div', { class: 'row' },
            dlBtn, cancelBtn,
            h('button', { class: 'b', onclick: () => { try { GM_setClipboard(currentUrl(e), 'text'); setStatus('URL copied.'); } catch (_) { setStatus('Copy failed.', true); } } }, 'Copy URL'),
            h('button', { class: 'b', onclick: () => window.open(currentUrl(e), '_blank', 'noopener') }, 'Open in tab'),
            tokBtn),
          h('div', { class: 'prog' }, progBar),
          statusEl,
          h('div', { class: 'hint' }, `Found via: ${[...e.sources].join(', ')}  ·  Referer: ${e.referer}`),
        ].flat().filter(Boolean));
        updateCountdown();
      }

      return { mount, refresh: () => refresh(false), open };
    })();

    /* ------------------------------------------------------------------ *
     *  Boot — normal pages: only the button, after load. Job tabs: observer now, capture after load.
     * ------------------------------------------------------------------ */
    try { GM_registerMenuCommand('Show MP4 files on this page', () => ui.open()); } catch (_) { /* ignore */ }

    function maybeShowButton(triesLeft) {
      if (document.querySelector('video, iframe')) { ui.mount(); return; }
      if (triesLeft > 0) setTimeout(() => maybeShowButton(triesLeft - 1), 3000);
    }

    const job = findMyJob();   // only true in a tab opened by grab() or "Reload & capture"
    if (job) startLiveObserver(0, true);   // read-only; must be listening before the player's first request
    if (job && EARLY_SEEK) armEarlySeek(); // [cums] before the player exists, so its first load can be held back
    const whenLoaded = fn => (document.readyState === 'complete' ? fn() : window.addEventListener('load', fn, { once: true }));
    // [cums] capture tab: once the link is reported, stop the player so it doesn't keep downloading
    // the video while the tab is being closed.
    function releaseMedia() {
      for (const v of document.querySelectorAll('video')) {
        try { v.pause(); v.removeAttribute('src'); v.querySelectorAll('source').forEach(s => s.remove()); v.load(); } catch (_) { /* ignore */ }
      }
    }
    if (job) {
      whenLoaded(() => runJob(job).catch(err => {
        try { GM_setValue(RES_PREFIX + job.id, { ok: false, reason: 'worker-error: ' + err, pageUrl: location.href, files: [], best: null }); } catch (_) { /* ignore */ }
      }).finally(() => {
        if (earlySeekDisarm) earlySeekDisarm();
        if (!job.interactive) releaseMedia();
      }));
    } else {
      if (SHOW_GRABBER_BUTTON) whenLoaded(() => setTimeout(() => maybeShowButton(10), BUTTON_DELAY_MS));
    }
    return MP4Grabber;
  })();

  // =====================================================================================
  //  PART 3 — Downloader UI (single button under the player + floating batch selector)
  //  Runs in Tampermonkey's sandbox. MP4Grabber (above) supplies signed links.
  //  Files are fetched in ranged chunks and kept on disk (the browser's private
  //  per-site storage, OPFS) so a failed or interrupted download resumes where it stopped.
  // =====================================================================================
  if (!MP4Grabber) return;                         // iframes: grabber only
  if (/mp4grab-/.test(location.hash)) return;      // tab opened by MP4Grabber.grab(): capture only, no UI

  const log = (...a) => DL_CFG.debug && console.log('%c[cums-dl]', 'color:#e91e63;font-weight:bold', ...a);
  const nowSec = () => Math.floor(Date.now() / 1000);
  const abortErr = () => new DOMException('Cancelled', 'AbortError');
  const sleep = (ms, signal) => new Promise((res, rej) => {
    const t = setTimeout(res, ms);
    if (signal) signal.addEventListener('abort', () => { clearTimeout(t); rej(abortErr()); }, { once: true });
  });
  const anySignal = (...sigs) => {
    const c = new AbortController();
    for (const s of sigs) {
      if (!s) continue;
      if (s.aborted) { c.abort(); break; }
      s.addEventListener('abort', () => c.abort(), { once: true });
    }
    return c.signal;
  };
  const fmtBytes = (n) => (!n ? '—' : n < 1048576 ? `${Math.max(1, Math.round(n / 1024))} KB`
    : n < 1073741824 ? `${Math.round(n / 1048576)} MB` : `${(n / 1073741824).toFixed(2)} GB`);
  const mmss = (ms) => { const s = Math.max(0, Math.floor(ms / 1000)); return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`; };
  const CHUNK = Math.max(1, DL_CFG.chunkMB) * 1048576;

  // ---------- page / URL helpers ----------
  const PAGE_RE = /^\/(video|shorts)\/(\d+)/;
  const IS_VIDEO_PAGE = PAGE_RE.test(location.pathname);
  // Shorts viewer (/shorts/ and /shorts/<id>/): a vertical feed of many clips. It gets a Download
  // action in each clip's side rail instead of the button under the player, and no batch selector.
  const IS_SHORTS = /^\/shorts(\/|$)/.test(location.pathname);
  const idFromUrl = (u) => {
    try { const m = PAGE_RE.exec(new URL(u, location.href).pathname); return m ? m[2] : null; } catch (_) { return null; }
  };
  const isVideoHref = (u) => {
    try {
      const x = new URL(u, location.href);
      return /(^|\.)cums\.net$/i.test(x.hostname) && PAGE_RE.test(x.pathname);
    } catch (_) { return false; }
  };
  const pageUrlOf = (u) => { const x = new URL(u, location.href); x.hash = ''; return x.href; };

  // "Watch <title> Porn Video | CUMS."  ->  "<title>"
  const cleanTitle = (t) => String(t || '')
    .replace(/\s+/g, ' ')
    .replace(/^\s*Watch\s+/i, '')
    .replace(/\s*[|–-]\s*CUMS\.?\s*$/i, '')
    .replace(/\s+Porn Video\s*$/i, '')
    .trim();
  const fileName = (t) =>
    ((cleanTitle(t) || 'video').replace(/[\\/:*?"<>|\u0000-\u001f]+/g, '').replace(/\s+/g, ' ').trim().slice(0, 150) || 'video') + '.mp4';
  const resolutionOf = (file) => { const m = /(?:^|\D)(\d{3,4})p(?![a-z])/i.exec(file || ''); return m ? `${m[1]}p` : ''; };

  // File name comes from the page's <title>; og:title / <h1> only if the title is empty.
  function titleFromDoc(doc) {
    const t = cleanTitle(doc.title);
    if (t) return t;
    const og = doc.querySelector('meta[property="og:title"]')?.getAttribute('content');
    const h1 = doc.querySelector('h1.browse-title, .video-title-row h1, h1')?.textContent;
    return cleanTitle(og || h1 || '');
  }
  const thumbFromDoc = (doc) => doc.querySelector('meta[property="og:image"]')?.getAttribute('content') || '';

  // Every quality the page offers, highest first. The player's sources are links on the site
  // itself (".../vfile/<id>/.../mp4/<id>_2160p.mp4"), base64 in the player setup script and plain
  // in one JSON-LD block per quality. Each one redirects to the signed fsN.cums.net URL.
  function sourcesFromDoc(doc, base) {
    const found = new Map();
    const addSrc = (u, res) => {
      if (typeof u !== 'string' || !/\.mp4(\?|$)/i.test(u)) return;
      let href;
      try { href = new URL(u.replace(/&amp;/g, '&'), base).href; } catch (_) { return; }
      const r = +res || parseInt(resolutionOf(href), 10) || 0;
      if (!found.has(href) || r > found.get(href)) found.set(href, r);
    };
    const html = doc.documentElement ? doc.documentElement.innerHTML : '';
    // player setup: { 'src': '<base64>', … 'res': '2160' }
    for (const m of html.matchAll(/['"]src['"]\s*:\s*['"]([A-Za-z0-9+/=]{24,})['"][^}]*?['"]res['"]\s*:\s*['"]?(\d{3,4})/g)) {
      try { addSrc(atob(m[1]), m[2]); } catch (_) { /* not base64 */ }
    }
    for (const s of doc.querySelectorAll('script[type="application/ld+json"]')) {
      try {
        const j = JSON.parse(s.textContent);
        for (const o of Array.isArray(j) ? j : [j]) if (o) addSrc(o.contentUrl);
      } catch (_) { /* malformed JSON-LD */ }
    }
    for (const m of html.matchAll(/https?:\/\/[^"'\s<>]+\/vfile\/[^"'\s<>]+?\.mp4/gi)) addSrc(m[0]);
    return [...found].map(([url, res]) => ({ url, res })).sort((a, b) => b.res - a.res);
  }

  // One small request (default: ranged GET bytes 0-0). Returns where the server ended up after
  // redirects, the HTTP status and the full file size. GM_xmlhttpRequest reports the final URL,
  // which the page's own request log does not.
  function probe(url, referer, signal, { method = 'GET', range = true } = {}) {
    return new Promise((resolve) => {
      let done = false, req = null;
      const finish = (r) => {
        if (done) return;
        done = true;
        clearTimeout(timer);
        try { req && req.abort && req.abort(); } catch (_) { /* ignore */ }
        if (!r) return resolve({ finalUrl: null, status: 0, total: 0, rangeOk: false });
        const h = String(r.responseHeaders || '');
        const cr = /content-range:\s*bytes\s+\d+-\d+\/(\d+)/i.exec(h);
        const cl = /content-length:\s*(\d+)/i.exec(h);
        resolve({
          finalUrl: r.finalUrl || null, status: r.status || 0,
          total: cr ? +cr[1] : (r.status === 200 && cl ? +cl[1] : 0),
          rangeOk: r.status === 206 && !!cr,
        });
      };
      const timer = setTimeout(() => finish(null), 16000);
      if (signal) signal.addEventListener('abort', () => finish(null), { once: true });
      try {
        req = GM_xmlhttpRequest({
          method, url, timeout: 15000,
          headers: range ? { Range: 'bytes=0-0', Referer: referer } : { Referer: referer },
          onreadystatechange: (r) => { if (r.readyState >= 2 && r.finalUrl && r.status) finish(r); },
          onload: finish, onerror: () => finish(null), ontimeout: () => finish(null), onabort: () => finish(null),
        });
      } catch (_) { finish(null); }
    });
  }

  // A signed URL (…/240344_1080p.mp4?t=…&exp=…) as a FileInfo that MP4Grabber.download() accepts.
  function toFileInfo(href, referer) {
    if (!href) return null;
    let u;
    try { u = new URL(href); } catch (_) { return null; }
    if (!/\.mp4$/i.test(u.pathname)) return null;
    const t = u.searchParams.get('t');
    const exp = Number(u.searchParams.get('exp'));
    if (!t || !exp) return null;
    return {
      file: decodeURIComponent(u.pathname.split('/').pop() || 'video.mp4'),
      signed: true, expired: exp <= nowSec(), preview: false,
      completedUrl: href, referer, servers: [u.origin], mp4Url: u.origin + u.pathname,
      token: { name: 't', value: t, raw: t },
      expiry: { name: 'exp', value: String(exp), epoch: exp, iso: new Date(exp * 1000).toISOString() },
      foundVia: ['redirect'],
    };
  }
  const lifeLeft = (fi) => (fi && fi.expiry && fi.expiry.epoch ? fi.expiry.epoch - nowSec() : Infinity);

  const hostOf = (u) => { try { return new URL(u).host; } catch (_) { return '?'; } };

  // Follow one quality link to its signed URL. Tries a ranged GET, a plain GET (stopped at the
  // headers) and a HEAD, since servers differ in which of these they redirect.
  async function followRedirect(src, referer, signal) {
    const tried = [];
    for (const v of [{ method: 'GET', range: true }, { method: 'GET', range: false }, { method: 'HEAD', range: false }]) {
      if (signal.aborted) throw abortErr();
      const p = await probe(src, referer, signal, v);
      const fi = toFileInfo(p.finalUrl, referer);
      if (fi && lifeLeft(fi) > DL_CFG.minTokenLifeSec) {
        if (!p.rangeOk) Object.assign(p, await probe(fi.completedUrl, referer, signal));
        return { fi: Object.assign(fi, { total: p.total, rangeOk: p.rangeOk }), note: '' };
      }
      tried.push(`${v.method}${v.range ? '+range' : ''} → ${p.status ? `HTTP ${p.status}` : 'no answer'}${p.finalUrl ? ` at ${hostOf(p.finalUrl)}` : ''}`);
    }
    return { fi: null, note: tried.join(', ') };
  }

  // ---------- fresh signed link for ONE video (+ its size), highest resolution first ----------
  // report(text) feeds the second line of the Status column.
  async function resolveLink(q, signal, report) {
    let why = '';
    if (DL_CFG.fastPath) {
      try {
        report('Reading the video page…');
        const r = await fetch(q.url, { credentials: 'include', signal });
        if (!r.ok) throw new Error(`video page HTTP ${r.status}`);
        const doc = new DOMParser().parseFromString(await r.text(), 'text/html');
        const t = titleFromDoc(doc);
        if (t) { q.title = t; q.titleFromPage = true; }
        if (!q.thumb) q.thumb = thumbFromDoc(doc);
        const srcs = sourcesFromDoc(doc, q.url);
        q.offered = srcs.map((s) => (s.res ? `${s.res}p` : '?'));
        const fails = [];
        for (const s of srcs) {
          const label = s.res ? `${s.res}p` : resolutionOf(s.url) || 'file';
          report(`Following the ${label} link to the file server…`);
          const { fi, note } = await followRedirect(s.url, q.url, signal);
          if (fi) { log('signed link via redirect', label, fi.completedUrl); return fi; }
          fails.push(`${label}: ${note}`);
        }
        why = srcs.length ? `no signed redirect (${fails.join('; ')})` : 'no video links in the page';
      } catch (e) {
        if (e.name === 'AbortError' || signal.aborted) throw abortErr();
        why = e.message;
      }
      if (signal.aborted) throw abortErr();
      console.warn('[cums-dl] direct link failed, using player capture:', why, q.url);
    }
    const total = 1 + DL_CFG.grabRetries;
    let tryText = '';
    const res = await MP4Grabber.grab(q.url, {
      retries: DL_CFG.grabRetries,
      signal,
      onProgress: (p) => {
        if (!p.attempt) return;
        const head = `Try ${p.attempt}/${total} (${p.foreground ? 'visible' : 'background'} tab)`;
        const msg = /^Attempt \d/.test(p.message || '') ? 'opening the video page…' : (p.message || '');
        tryText = `${head}: ${msg}`;
        report(why && p.attempt === 1 && /^Attempt/.test(p.message || '') ? `${why} → player capture. ${tryText}` : tryText);
      },
    });
    if (signal.aborted) throw abortErr();
    if (!res.ok || !res.best) throw new Error(`No signed link after ${res.attempts || total} tries (${res.reason || 'unknown'})`);
    if (!q.titleFromPage && res.title) { q.title = cleanTitle(res.title) || q.title; q.titleFromPage = true; }
    const fi = res.best;
    report('Checking file size…');
    const p = await probe(fi.completedUrl, fi.referer || q.url, signal);
    if (signal.aborted) throw abortErr();
    return Object.assign(fi, { total: p.total, rangeOk: p.rangeOk });
  }

  // One link fetch at a time (the grabber opens a tab per try). Refreshes for the video that is
  // downloading jump the queue ahead of early fetches for later videos.
  // An urgent task also interrupts an early fetch that is running (that video is re-queued).
  const linkQ = [];
  let linkCurrent = null;
  function linkTask(fn, urgent, preempt) {
    return new Promise((resolve, reject) => {
      const t = { fn, resolve, reject, urgent, preempt };
      if (urgent) {
        linkQ.unshift(t);
        if (linkCurrent && !linkCurrent.urgent && linkCurrent.preempt) linkCurrent.preempt();
      } else linkQ.push(t);
      pumpLinks();
    });
  }
  async function pumpLinks() {
    if (linkCurrent) return;
    const t = linkQ.shift();
    if (!t) return;
    linkCurrent = t;
    try { t.resolve(await t.fn()); } catch (e) { t.reject(e); } finally { linkCurrent = null; pumpLinks(); }
  }

  // ---------- on-disk temp storage (this script's own "cumsdl" folder in OPFS) ----------
  const Store = (() => {
    let probeP = null;
    function dir() {
      if (!probeP) {
        probeP = (async () => {
          try {
            if (!DL_CFG.diskResume || !navigator.storage?.getDirectory) return null;
            const root = await navigator.storage.getDirectory();
            const d = await root.getDirectoryHandle('cumsdl', { create: true });
            const h = await d.getFileHandle('.probe', { create: true });
            if (typeof h.createWritable !== 'function') return null;
            const w = await h.createWritable();
            await w.write(new Uint8Array([1]));
            await w.close();
            await d.removeEntry('.probe');
            return d;
          } catch (e) {
            log('disk storage unavailable:', e.message);
            return null;
          }
        })();
      }
      return probeP;
    }
    async function job(id) { const d = await dir(); return d ? d.getDirectoryHandle(id, { create: true }) : null; }
    async function readManifest(jd) {
      try { return JSON.parse(await (await (await jd.getFileHandle('manifest.json')).getFile()).text()); } catch (_) { return null; }
    }
    async function writeManifest(jd, m) {
      const w = await (await jd.getFileHandle('manifest.json', { create: true })).createWritable();
      await w.write(JSON.stringify(m));
      await w.close();
    }
    async function remove(id) {
      const d = await dir();
      if (!d || !id) return;
      try { await d.removeEntry(id, { recursive: true }); } catch (_) { /* ignore */ }
    }
    async function list() {
      const d = await dir();
      const out = [];
      if (!d) return out;
      for await (const [name, h] of d.entries()) if (h.kind === 'directory') out.push({ name, handle: h, manifest: await readManifest(h) });
      return out;
    }
    async function size(h) {
      let n = 0;
      for await (const [, c] of h.entries()) n += c.kind === 'file' ? (await c.getFile()).size : await size(c);
      return n;
    }
    return { dir, job, readManifest, writeManifest, remove, list, size };
  })();

  const segName = (i) => `s${String(i).padStart(6, '0')}`;
  const segIndex = (n) => (/^s\d{6}$/.test(n) ? +n.slice(1) : -1);
  const jobIdOf = (fi) => (fi.file || 'video.mp4').replace(/\.mp4$/i, '').replace(/[^\w.-]+/g, '_');

  async function janitor() {
    const now = Date.now();
    for (const it of await Store.list()) {
      const m = it.manifest;
      const leftover = m && m.state === 'saved' && now - (m.savedAt || 0) > 10 * 60 * 1000;
      const stale = !m || (m.state !== 'saved' && now - (m.updated || 0) > DL_CFG.keepPartialDays * 86400000);
      if (leftover || stale) { await Store.remove(it.name); log('removed temp files:', it.name); }
    }
  }

  // Bytes already on disk for a video (by page id) -> fraction, or undefined if none.
  async function partialFor(vid) {
    for (const it of await Store.list()) {
      const m = it.manifest;
      if (!m || m.vid !== vid || m.state === 'saved' || !m.total) continue;
      let bytes = 0;
      for await (const [name, h] of it.handle.entries()) if (h.kind === 'file' && segIndex(name) >= 0) bytes += (await h.getFile()).size;
      return bytes / m.total;
    }
    return undefined;
  }

  // ---------- give a video you're watching room to buffer ----------
  // Seconds buffered ahead of the playhead for the video(s) being watched on this page.
  // Ignores paused players, hover previews and anything already buffered to its end.
  function playbackAhead() {
    let worst = Infinity;
    for (const v of document.querySelectorAll('video')) {
      if (v.paused || v.ended || v.classList.contains('hover-preview-video') || v.closest('.thumbnail')) continue;
      if (!isFinite(v.duration) || v.duration <= 0) continue;
      let ahead = 0;
      const b = v.buffered;
      for (let i = 0; i < b.length; i++) {
        if (b.start(i) <= v.currentTime + 0.5 && b.end(i) > v.currentTime) ahead = Math.max(ahead, b.end(i) - v.currentTime);
      }
      if (v.currentTime + ahead >= v.duration - 0.5) continue;
      worst = Math.min(worst, ahead);
    }
    return worst;
  }
  // How many chunk requests may run right now: none while the watched video is close to running
  // dry, one while it is below its target, all of them otherwise.
  function allowedConnections() {
    if (!DL_CFG.yieldToPlayback) return { n: DL_CFG.connections, note: '' };
    const ahead = playbackAhead();
    if (ahead < DL_CFG.playbackMinSec) return { n: 0, note: `paused – the video you’re watching has ${Math.floor(ahead)}s buffered` };
    if (ahead < DL_CFG.playbackTargetSec) return { n: 1, note: `slowed – letting the video you’re watching buffer (${Math.floor(ahead)}s)` };
    return { n: DL_CFG.connections, note: '' };
  }

  // ---------- ranged chunk fetch (GM_xmlhttpRequest: no CORS limits, sends Referer) ----------
  function fetchRange(url, referer, start, end, signal, onBytes) {
    return new Promise((resolve, reject) => {
      if (signal.aborted) { reject(abortErr()); return; }
      let req = null, done = false;
      const fin = (fn, v) => { if (done) return; done = true; signal.removeEventListener('abort', onAbort); fn(v); };
      const onAbort = () => { try { req && req.abort(); } catch (_) { /* ignore */ } fin(reject, abortErr()); };
      signal.addEventListener('abort', onAbort);
      const fail = (msg, status) => fin(reject, Object.assign(new Error(msg), { status }));
      try {
        req = GM_xmlhttpRequest({
          method: 'GET', url, responseType: 'arraybuffer', timeout: DL_CFG.chunkTimeoutSec * 1000,
          headers: { Range: `bytes=${start}-${end}`, Referer: referer },
          onprogress: (p) => { if (onBytes) onBytes(p.loaded || 0); },
          onload: (r) => {
            if (r.status !== 206) return fail(`HTTP ${r.status}`, r.status);
            const buf = r.response;
            const want = end - start + 1;
            if (!buf || buf.byteLength !== want) return fail(`short chunk (${buf ? buf.byteLength : 0} of ${want} bytes)`);
            fin(resolve, buf);
          },
          onerror: (r) => fail('network error', r && r.status),
          ontimeout: () => fail('chunk timed out'),
          onabort: () => fin(reject, abortErr()),
        });
      } catch (e) { fin(reject, e); }
    });
  }

  // Save a disk-backed Blob through a normal browser download, then remove the temp copy
  // (a page can't see when the browser finishes writing, so: 30 s + 1 s per 25 MB).
  function saveBlob(blob, name, jobId, savedAt) {
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = name;
    a.dataset.cdlUi = '';
    a.style.display = 'none';
    document.body.appendChild(a);
    a.click();
    a.remove();
    setTimeout(async () => {
      URL.revokeObjectURL(url);
      // Only remove the copy this save made (a newer run of the same file may be using the folder now).
      try {
        const m = await Store.readManifest(await Store.job(jobId));
        if (!m || (m.state === 'saved' && m.savedAt === savedAt)) await Store.remove(jobId);
      } catch (_) { /* ignore */ }
    }, 30000 + Math.ceil(blob.size / (25 * 1048576)) * 1000);
  }

  // Download q.fi to disk in chunks; resumes from chunks already saved for the same file.
  // relink() fetches a new token when the server refuses the current one (403/410).
  async function diskDownload(q, signal, relink, onUpdate) {
    const total = q.total;
    const jobId = jobIdOf(q.fi);
    q.jobId = jobId;
    let jd = await Store.job(jobId);
    const old = await Store.readManifest(jd);
    if (old && (old.state === 'saved' || old.total !== total || old.chunk !== CHUNK)) { await Store.remove(jobId); jd = await Store.job(jobId); }
    const m = { jobId, vid: q.key, file: q.fi.file, title: q.title, total, chunk: CHUNK, state: 'partial', updated: Date.now() };
    await Store.writeManifest(jd, m);

    const n = Math.ceil(total / CHUNK);
    const sizeOf = (i) => Math.min(CHUNK, total - i * CHUNK);
    const have = new Set();
    let doneBytes = 0;
    for await (const [name, h] of jd.entries()) {
      const i = segIndex(name);
      if (i < 0 || i >= n || h.kind !== 'file') continue;
      const s = (await h.getFile()).size;
      if (s === sizeOf(i)) { have.add(i); doneBytes += s; }
    }
    if (doneBytes) q.resumedAt = doneBytes / total;
    const todo = [];
    for (let i = 0; i < n; i++) if (!have.has(i)) todo.push(i);

    // progress + speed
    const live = new Map();
    let lastT = Date.now(), lastB = doneBytes, speed = 0, throttle = '';
    const runStart = Date.now(), runStartBytes = doneBytes;
    const report = (note) => {
      let b = doneBytes;
      for (const v of live.values()) b += v;
      q.bytes = Math.min(total, b);
      q.pct = q.bytes / total;
      const t = Date.now();
      if (t - lastT >= 1000) { speed = speed ? speed * 0.6 + ((q.bytes - lastB) / ((t - lastT) / 1000)) * 0.4 : (q.bytes - lastB) / ((t - lastT) / 1000); lastT = t; lastB = q.bytes; }
      q.detail = note || `${fmtBytes(q.bytes)} of ${fmtBytes(total)}${speed > 0 ? ` · ${(speed / 1048576).toFixed(1)} MB/s` : ''}${q.resumedAt ? ` · resumed at ${Math.floor(q.resumedAt * 100)}%` : ''}${throttle ? ` · ${throttle}` : ''}`;
      onUpdate();
    };
    report();

    const inner = new AbortController();
    const sig = anySignal(signal, inner.signal);
    let next = 0;
    let active = 0;
    // Waits until another chunk may start: playback priority + optional speed cap.
    const gate = async () => {
      for (;;) {
        if (sig.aborted) throw abortErr();
        const { n: allowed, note } = allowedConnections();
        const cap = DL_CFG.maxRateMBps * 1048576;
        const secs = (Date.now() - runStart) / 1000;
        const overCap = cap > 0 && secs > 1 && (q.bytes - runStartBytes) / secs > cap;
        const t = note || (overCap ? `capped at ${DL_CFG.maxRateMBps} MB/s` : '');
        if (t !== throttle) { throttle = t; report(); }
        if (active < allowed && !overCap) return;
        await sleep(500, sig);
      }
    };
    const worker = async () => {
      while (next < todo.length) {
        await gate();
        if (next >= todo.length) break;
        const i = todo[next++];
        active++;
        try {
        const start = i * CHUNK;
        const end = start + sizeOf(i) - 1;
        for (let attempt = 0; ; attempt++) {
          if (sig.aborted) throw abortErr();
          try {
            const buf = await fetchRange(q.fi.completedUrl, q.fi.referer || q.url, start, end, sig, (b) => { live.set(i, b); report(); });
            live.delete(i);
            const w = await (await jd.getFileHandle(segName(i), { create: true })).createWritable();
            try { await w.write(buf); await w.close(); } catch (e) { try { await w.abort(); } catch (_) { /* ignore */ } throw e; }
            doneBytes += buf.byteLength;
            report();
            break;
          } catch (e) {
            live.delete(i);
            if (e.name === 'AbortError' || sig.aborted) throw abortErr();
            const refused = e.status === 401 || e.status === 403 || e.status === 410 || lifeLeft(q.fi) < 30;
            if (attempt >= DL_CFG.chunkRetries) throw new Error(`chunk ${i + 1}/${n}: ${e.message}`);
            if (refused) {
              report(`Link refused (${e.message}) – getting a fresh one…`);
              await relink();
            } else {
              report(`Chunk ${i + 1}/${n}: ${e.message} – retrying`);
              await sleep(1000 * (attempt + 1), sig);
            }
          }
        }
        } finally { active--; }
      }
    };
    const results = await Promise.allSettled(
      Array.from({ length: Math.min(DL_CFG.connections, todo.length) }, () => worker().catch((e) => { inner.abort(); throw e; })));
    if (signal.aborted) throw abortErr();
    const err = results.find((r) => r.status === 'rejected' && r.reason && r.reason.name !== 'AbortError');
    if (err) { m.updated = Date.now(); await Store.writeManifest(jd, m).catch(() => {}); throw err.reason; }

    q.saving = true;
    report('Saving to your downloads…');
    const files = [];
    for (let i = 0; i < n; i++) files.push(await (await jd.getFileHandle(segName(i))).getFile());
    const blob = new Blob(files, { type: 'video/mp4' });
    if (blob.size !== total) throw new Error(`assembled ${blob.size} of ${total} bytes`);
    const savedAt = Date.now();
    await Store.writeManifest(jd, { ...m, state: 'saved', savedAt, updated: savedAt });
    saveBlob(blob, fileName(q.title), jobId, savedAt);
  }

  // Fallback when disk storage or byte ranges aren't available: Tampermonkey saves it (no resume).
  async function gmDownload(q, signal, onUpdate) {
    q.detail = 'Saving through Tampermonkey (no resume for this file)';
    onUpdate();
    await MP4Grabber.download(q.fi, {
      name: fileName(q.title),
      signal,
      onProgress: ({ loaded, total }) => {
        q.bytes = loaded;
        if (total) q.total = q.total || total;
        q.pct = total ? loaded / total : null;
        q.detail = `${fmtBytes(loaded)}${total ? ` of ${fmtBytes(total)}` : ''} · via Tampermonkey (no resume)`;
        onUpdate();
      },
    });
  }

  // ---------- leave-page guard while a queue runs ----------
  let busyCount = 0;
  const onBeforeUnload = (e) => { e.preventDefault(); e.returnValue = ''; };
  function guardUnload(delta) {
    busyCount = Math.max(0, busyCount + delta);
    if (busyCount) window.addEventListener('beforeunload', onBeforeUnload);
    else window.removeEventListener('beforeunload', onBeforeUnload);
  }

  // ---------- site-styled buttons (Sign Up look: btn-gradient) ----------
  const ICONS = {
    download: '<svg class="cdl-ico" viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M11 3h2v9.17l3.59-3.58L18 10l-6 6-6-6 1.41-1.41L11 12.17V3zM4 18h16v2H4z"/></svg>',
    batch: '<svg class="cdl-ico" viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M3 4h4v4H3V4zm2 1.5L4.3 6.2l-.8-.8-.7.7L4.3 7.6 6.7 5.2 6 4.5 5 5.5zM9 5h12v2H9V5zM3 10h4v4H3v-4zm6 1h12v2H9v-2zM3 16h4v4H3v-4zm6 1h7v2H9v-2zm10-1h2v3.17l1.09-1.08L23.5 18.5 20 22l-3.5-3.5 1.41-1.41L19 18.17V16z"/></svg>',
    close: '<svg class="cdl-ico" viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M6.4 5 12 10.6 17.6 5 19 6.4 13.4 12l5.6 5.6-1.4 1.4-5.6-5.6L6.4 19 5 17.6l5.6-5.6L5 6.4z"/></svg>',
  };
  function siteButton(icon, text, cls = 'btn btn-gradient') {
    const btn = document.createElement('button');
    btn.type = 'button';
    btn.className = `${cls} cdl-btn`;
    btn.innerHTML = `${ICONS[icon]}<span></span>`;
    const label = btn.querySelector('span');
    const setText = (t) => { if (label.textContent !== t) label.textContent = t; };
    setText(text);
    return { btn, setText };
  }

  // ---------- small confirm dialog (selection "click outside" + stop download) ----------
  let dialogOpen = false;
  function confirmDialog({ title, text, primary, secondary, danger }) {
    return new Promise((resolve) => {
      dialogOpen = true;
      const wrap = document.createElement('div');
      wrap.className = 'cdl-backdrop cdl-over';
      wrap.dataset.cdlUi = '';
      wrap.innerHTML = `
        <div class="cdl-modal cdl-confirm" role="alertdialog" aria-modal="true">
          <h3 class="cdl-title"></h3>
          <p class="cdl-text"></p>
          <div class="cdl-foot">
            <button type="button" class="cdl-btn2" data-act="secondary"></button>
            <button type="button" class="cdl-btn2 ${danger ? 'cdl-danger' : 'cdl-main'}" data-act="primary"></button>
          </div>
        </div>`;
      wrap.querySelector('.cdl-title').textContent = title;
      wrap.querySelector('.cdl-text').textContent = text;
      wrap.querySelector('[data-act="primary"]').textContent = primary;
      wrap.querySelector('[data-act="secondary"]').textContent = secondary;
      const onKey = (e) => { if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); done('secondary'); } };
      const done = (v) => {
        wrap.remove();
        document.removeEventListener('keydown', onKey, true);
        dialogOpen = false;
        resolve(v);
      };
      wrap.addEventListener('click', (e) => {
        const act = e.target.closest('[data-act]')?.dataset.act;
        if (act) done(act);
        else if (e.target === wrap) done('secondary');
      });
      document.addEventListener('keydown', onKey, true);
      document.body.appendChild(wrap);
      wrap.querySelector('[data-act="secondary"]').focus();
    });
  }

  // ---------- thumbnail hover preview inside the progress dialog ----------
  let previewEl = null;
  function showPreview(src, anchor) {
    if (!src) return;
    if (!previewEl) {
      previewEl = document.createElement('img');
      previewEl.className = 'cdl-preview';
      previewEl.dataset.cdlUi = '';
      document.body.appendChild(previewEl);
    }
    previewEl.src = src;
    const r = anchor.getBoundingClientRect();
    previewEl.style.left = `${Math.min(innerWidth - 330, r.right + 10)}px`;
    previewEl.style.top = `${Math.max(8, Math.min(innerHeight - 190, r.top - 70))}px`;
    previewEl.style.display = 'block';
  }
  const hidePreview = () => { if (previewEl) previewEl.style.display = 'none'; };

  // ---------- progress dialog (single + batch share one layout; batch adds the checkbox + # columns) ----------
  const LOCKED = new Set(['downloading', 'done', 'failed', 'cancelled']);

  function createPanel({ queue, batchMode, heading, onToggle }) {
    const wrap = document.createElement('div');
    wrap.className = 'cdl-backdrop';
    wrap.dataset.cdlUi = '';
    wrap.innerHTML = `
      <div class="cdl-modal" role="dialog" aria-modal="true">
        <h3 class="cdl-title"></h3>
        <p class="cdl-warn">⚠️ Keep this tab open while downloading. Links are fetched for every video up front; each one may open the video briefly in a background tab.${batchMode ? ' Untick a video that hasn’t started to skip it.' : ''} If a download stops, finished parts stay on disk and the next attempt resumes.</p>
        <div class="cdl-tablewrap">
          <table class="cdl-table">
            <thead><tr>${batchMode ? '<th class="c-chk" title="Include"><input type="checkbox" class="cdl-chkall" checked aria-label="Include all"></th><th>#</th>' : ''}<th>Thumbnail</th><th>Link</th><th>Video</th><th>Resolution</th><th>Size</th><th>Status</th><th>Progress</th></tr></thead>
            <tbody></tbody>
          </table>
        </div>
        <div class="cdl-foot">
          <span class="cdl-cache"></span>
          <button type="button" class="cdl-btn2 cdl-clear" hidden>Delete unfinished downloads</button>
          <button type="button" class="cdl-btn2 cdl-main" data-role="main">Cancel</button>
        </div>
      </div>`;
    document.body.appendChild(wrap);
    const modal = wrap.firstElementChild;
    const $ = (s) => modal.querySelector(s);
    const titleEl = $('.cdl-title');
    titleEl.textContent = heading;
    const tbody = $('tbody');
    const mainBtn = $('[data-role="main"]');
    let closed = false;
    let ended = false;

    for (const q of queue) {
      const tr = document.createElement('tr');
      tr.innerHTML = `${batchMode ? '<td class="c-chk"><input type="checkbox" class="cdl-chk" aria-label="Include"></td><td class="c-n"></td>' : ''}
        <td class="c-thumb"><div class="cdl-hover">Hover</div></td>
        <td class="c-link"><a class="cdl-link" target="_blank" rel="noopener">Open Page</a></td>
        <td class="c-name"></td><td class="c-res"></td><td class="c-size"></td>
        <td class="c-status"><div class="cdl-st1"></div><div class="cdl-st2"></div></td>
        <td class="c-prog"><div class="cdl-progwrap"><div class="cdl-bar"><i></i></div><span></span></div></td>`;
      if (batchMode) tr.querySelector('.c-n').textContent = q.n;
      tr.querySelector('.cdl-link').href = q.url;
      tr._q = q;
      q.row = tr;
      tbody.appendChild(tr);
    }
    tbody.addEventListener('change', (e) => {
      const cb = e.target.closest('.cdl-chk');
      const q = cb && cb.closest('tr')._q;
      if (!q) return;
      if (ended || LOCKED.has(q.state)) { cb.checked = q.checked; return; }
      onToggle && onToggle(q, cb.checked);
    });
    if (batchMode) {
      $('.cdl-chkall').addEventListener('change', (e) => {
        for (const q of queue) if (!ended && !LOCKED.has(q.state) && q.checked !== e.target.checked) onToggle && onToggle(q, e.target.checked);
        ui.refreshAll();
      });
    }
    tbody.addEventListener('mouseover', (e) => {
      const h = e.target.closest('.cdl-hover');
      if (h) showPreview(h.closest('tr')._q.thumb, h);
    });
    tbody.addEventListener('mouseout', (e) => { if (e.target.closest('.cdl-hover')) hidePreview(); });

    // Green fill across the dialog: share of the included videos that is finished (by size when known).
    const updateFill = () => {
      const live = queue.filter((x) => x.checked && x.state !== 'failed' && x.state !== 'cancelled');
      const w = (x) => x.total || 0;
      const tw = live.reduce((s, x) => s + w(x), 0);
      const prog = (x) => (x.state === 'done' ? 1 : Math.min(1, x.pct || 0));
      const f = !live.length ? 0 : tw && live.every(w) ? live.reduce((s, x) => s + w(x) * prog(x), 0) / tw : live.reduce((s, x) => s + prog(x), 0) / live.length;
      modal.style.setProperty('--fill', `${Math.min(100, f * 100).toFixed(1)}%`);
    };

    const STATUS = {
      pending: (q) => (q.checked ? 'Queued' : 'Skipped'),
      linking: () => 'Getting link',
      ready: (q) => (q.checked ? 'Link ready' : 'Skipped'),
      downloading: (q) => (q.saving ? 'Saving' : q.retry ? `Downloading (retry ${q.retry})` : 'Downloading'),
      done: () => 'Done', failed: () => 'Failed', cancelled: () => 'Cancelled',
    };

    const ui = {
      onMain: null,
      onUpdate: null,
      update(q) {
        if (!closed && q.row) {
          const r = q.row;
          r.classList.toggle('cdl-skip', !q.checked);
          const cb = r.querySelector('.cdl-chk');
          if (cb) { cb.checked = !!q.checked; cb.disabled = ended || LOCKED.has(q.state); cb.title = cb.disabled ? '' : q.checked ? 'Untick to skip' : 'Tick to include'; }
          const name = r.querySelector('.c-name');
          if (name.textContent !== q.title) { name.textContent = q.title; name.title = q.title; }
          r.querySelector('.c-res').textContent = (q.fi && resolutionOf(q.fi.file)) || '—';
          r.querySelector('.c-size').textContent = q.total ? fmtBytes(q.total) : '—';
          const ticking = q.state === 'linking' || (q.state === 'downloading' && !q.saving);
          const st1 = r.querySelector('.cdl-st1');
          st1.textContent = STATUS[q.state](q) + (ticking && q.since ? ` · ${mmss(Date.now() - q.since)}` : '');
          const td = r.querySelector('.c-status');
          td.dataset.state = q.checked || LOCKED.has(q.state) ? q.state : 'skipped';
          const st2 = r.querySelector('.cdl-st2');
          const detail = q.state === 'pending' && !q.checked ? 'Tick to include' : q.detail || '';
          if (st2.textContent !== detail) st2.textContent = detail;
          td.title = [st1.textContent, detail].filter(Boolean).join('\n');
          const bar = r.querySelector('.cdl-bar');
          const indeterminate = q.state === 'downloading' && q.pct == null;
          bar.classList.toggle('cdl-indet', indeterminate);
          const pct = Math.floor((q.state === 'done' ? 1 : q.pct || 0) * 100);
          bar.querySelector('i').style.width = indeterminate ? '' : `${pct}%`;
          r.querySelector('.c-prog span').textContent = indeterminate ? '…' : `${pct}%`;
          updateFill();
        }
        if (ui.onUpdate) ui.onUpdate(q);
      },
      refreshAll() { queue.forEach((q) => ui.update(q)); },
      setMain(text, disabled = false) { mainBtn.textContent = text; mainBtn.disabled = disabled; },
      async finish(text) {
        ended = true;
        clearInterval(ticker);
        titleEl.textContent = text;
        $('.cdl-warn').hidden = true;
        ui.setMain('Close');
        ui.refreshAll();
        await showCache();
      },
      close() {
        if (closed) return;
        closed = true;
        clearInterval(ticker);
        hidePreview();
        wrap.remove();
      },
    };
    const ticker = setInterval(() => { for (const q of queue) if (q.state === 'linking' || q.state === 'downloading') ui.update(q); }, 1000);

    async function showCache() {
      if (!(await Store.dir())) return;
      const partial = (await Store.list()).filter((it) => it.manifest?.state !== 'saved');
      let bytes = 0;
      for (const it of partial) bytes += await Store.size(it.handle);
      $('.cdl-cache').textContent = partial.length ? `Unfinished downloads kept for resume: ${fmtBytes(bytes)}` : '';
      $('.cdl-clear').hidden = !partial.length;
    }
    $('.cdl-clear').addEventListener('click', async () => {
      for (const it of await Store.list()) if (it.manifest?.state !== 'saved') await Store.remove(it.name);
      await showCache();
    });
    mainBtn.addEventListener('click', () => ui.onMain && ui.onMain());
    ui.refreshAll();
    return ui;
  }

  // ---------- queue runner (used by single AND batch) ----------
  // Link loop: fetches links for every ticked video, in order, as soon as the dialog opens.
  // Download loop: one video at a time, in order, each in parallel ranged chunks.
  let running = false;

  async function runQueue(queue, { heading, batchMode, onUpdate }) {
    running = true;
    for (const q of queue) Object.assign(q, { checked: true, state: 'pending', pct: 0, bytes: 0, detail: '' });
    const ctrl = new AbortController();
    let cancelled = false;
    let finished = false;
    let wake = null;
    let wakeP = null;
    const resetWake = () => { wakeP = new Promise((r) => { wake = r; }); };
    resetWake();
    const notify = () => { const w = wake; resetWake(); w(); };

    const panel = createPanel({
      queue, batchMode, heading,
      onToggle: (q, on) => {
        q.checked = on;
        if (!on && q.state === 'linking' && q.linkCtrl) q.linkCtrl.abort();
        panel.update(q);
        notify();
      },
    });
    panel.onUpdate = onUpdate || null;
    const upd = (q) => panel.update(q);
    guardUnload(1);

    panel.onMain = async () => {
      if (finished) { panel.close(); return; }
      if (cancelled) return;
      if (queue.some((q) => q.state === 'downloading' || q.state === 'linking')) {
        const c = await confirmDialog({
          title: queue.length > 1 ? 'Stop the batch?' : 'Stop the download?',
          text: `${queue.length > 1 ? 'The video in progress stops and the rest are skipped.' : 'The download stops.'} Finished parts stay on disk, so starting it again resumes.`,
          primary: 'Stop', secondary: 'Keep downloading', danger: true,
        });
        if (c !== 'primary' || finished) return;
      }
      cancelled = true;
      panel.setMain('Cancelling…', true);
      ctrl.abort();
      notify();
    };

    const applyLink = (q, fi) => {
      q.fi = fi;
      if (fi.total) q.total = fi.total;
    };

    async function getLink(q) {
      q.linkCtrl = new AbortController();
      const sig = anySignal(ctrl.signal, q.linkCtrl.signal);
      q.state = 'linking';
      q.since = Date.now();
      q.detail = 'Waiting for its turn…';
      upd(q);
      let preempted = false;
      try {
        const fi = await linkTask(() => {
          if (sig.aborted) throw abortErr();
          q.since = Date.now();
          return resolveLink(q, sig, (t) => { q.detail = t; upd(q); });
        }, false, () => { preempted = true; q.linkCtrl.abort(); });
        applyLink(q, fi);
        q.state = 'ready';
        q.detail = fi.expiry && fi.expiry.epoch ? `Token valid until ${new Date(fi.expiry.epoch * 1000).toLocaleTimeString()}` : '';
      } catch (e) {
        if (ctrl.signal.aborted) { q.state = 'cancelled'; q.detail = ''; }
        else if (q.linkCtrl.signal.aborted) { q.state = 'pending'; q.detail = preempted ? 'Paused for another video’s link refresh' : ''; }   // unticked or interrupted
        else { q.state = 'failed'; q.detail = e.message; q.error = e.message; }
      }
      upd(q);
      notify();
    }

    const linkLoop = (async () => {
      while (!cancelled && !finished) {
        const q = queue.find((x) => x.checked && x.state === 'pending' && !x.fi);
        if (!q) { await wakeP; continue; }
        await getLink(q);
      }
    })();

    async function downloadItem(q) {
      q.state = 'downloading';
      q.since = Date.now();
      q.retry = 0;
      upd(q);
      let relinkP = null;
      const relink = () => (relinkP = relinkP || linkTask(() => resolveLink(q, ctrl.signal, (t) => { q.detail = `New link: ${t}`; upd(q); }), true)
        .then((fi) => {
          if (q.total && fi.total && fi.total !== q.total) throw new Error('file size changed with the new link');
          applyLink(q, fi);
          return fi;
        })
        .finally(() => { relinkP = null; }));
      const disk = await Store.dir();
      for (let attempt = 0; ; attempt++) {
        try {
          if (lifeLeft(q.fi) < DL_CFG.minTokenLifeSec) { q.detail = 'Token about to expire – getting a fresh one…'; upd(q); await relink(); }
          if (disk && q.fi.rangeOk && q.total) await diskDownload(q, ctrl.signal, relink, () => upd(q));
          else await gmDownload(q, ctrl.signal, () => upd(q));
          q.state = 'done';
          q.pct = 1;
          q.detail = `Saved as ${fileName(q.title)}`;
          break;
        } catch (e) {
          if (e.name === 'AbortError' || ctrl.signal.aborted) {
            q.state = 'cancelled';
            q.detail = q.bytes && disk ? `Stopped at ${Math.floor((q.pct || 0) * 100)}% – start again to resume` : '';
            break;
          }
          console.error('[cums-dl]', q.url, e);
          if (attempt < DL_CFG.itemRetries) {
            q.retry = attempt + 1;
            q.detail = `${e.message} – retrying${disk ? ' from where it stopped' : ''}…`;
            upd(q);
            try { await sleep(2000, ctrl.signal); await relink(); } catch (e2) { if (ctrl.signal.aborted) continue; q.detail = e2.message; }
            continue;
          }
          q.state = 'failed';
          q.error = e.message;
          q.detail = `${e.message}${disk && q.bytes ? ' · finished parts kept – try again to resume' : ''}`;
          break;
        }
      }
      q.saving = false;
      upd(q);
      notify();
    }

    // Download loop
    for (;;) {
      if (cancelled) break;
      const q = queue.find((x) => x.checked && (x.state === 'pending' || x.state === 'linking' || x.state === 'ready'));
      if (!q) {
        if (queue.some((x) => x.state === 'linking')) { await wakeP; continue; }
        break;
      }
      if (q.state !== 'ready') { await wakeP; continue; }
      await downloadItem(q);
    }

    finished = true;
    notify();
    await linkLoop;
    for (const q of queue) {
      if (q.state === 'pending' || q.state === 'ready' || q.state === 'linking') {
        q.state = cancelled && q.checked ? 'cancelled' : 'pending';
        q.checked = q.state === 'cancelled' ? q.checked : false;
        q.detail = '';
        upd(q);
      }
    }
    running = false;
    guardUnload(-1);
    const ok = queue.filter((q) => q.state === 'done').length;
    const wanted = queue.filter((q) => q.state !== 'pending').length;
    await panel.finish(queue.length === 1
      ? (ok ? 'Download complete' : queue[0].state === 'cancelled' ? 'Download stopped' : 'Download failed')
      : ok === wanted ? `All downloads complete (${ok})` : `Finished – ${ok} of ${wanted} saved`);
    return { ok, queue };
  }

  // ---------- main player on video / shorts pages ----------
  function mainPlayerEl() {
    if (!IS_VIDEO_PAGE) return null;
    const cands = document.querySelectorAll('#player-container-fluid, #video .player-container, .video-js, #player-facade, video');
    for (const el of cands) {
      if (el.closest('.thumbnail') || el.closest('[data-cdl-ui]') || el.classList.contains('hover-preview-video')) continue;
      if (!el.getClientRects().length) continue;
      return el.closest('#player-container-fluid') || el.closest('.player-container') || el.closest('.video-js') || el;
    }
    return null;
  }

  function currentEntry() {
    const el = mainPlayerEl();
    const key = idFromUrl(location.href) || document.querySelector('#video[data-id]')?.dataset.id;
    if (!el || !key) return null;
    return { el, key, url: pageUrlOf(location.href), title: titleFromDoc(document), thumb: thumbFromDoc(document) };
  }

  // ---------- single download button (below the video, right-aligned) ----------
  const single = { bar: null, setText: null, rest: 'Download', q: null };

  function renderSingle() {
    if (!single.setText) return;
    const q = single.q;
    if (!q || !running) return single.setText(single.rest);
    if (q.state === 'downloading') return single.setText(q.saving ? 'Saving…' : q.pct != null ? `Downloading ${Math.floor(q.pct * 100)}%` : 'Downloading…');
    if (q.state === 'linking' || q.state === 'ready') return single.setText('Getting link…');
    single.setText(single.rest);
  }

  function refreshResumeLabel() {
    const id = idFromUrl(location.href);
    if (!id || running) return;
    partialFor(id).then((p) => {
      if (running || p === undefined) return;
      single.rest = `Resume (${Math.floor(p * 100)}%)`;
      renderSingle();
    }).catch(() => {});
  }

  async function startSingle() {
    if (running) return;
    const cur = currentEntry();
    const url = pageUrlOf(location.href);
    const q = { n: 1, key: cur ? cur.key : idFromUrl(url), url, title: titleFromDoc(document) || 'video', thumb: thumbFromDoc(document) };
    single.q = q;
    const { ok } = await runQueue([q], { heading: 'Downloading video', batchMode: false, onUpdate: renderSingle });
    single.rest = ok ? 'Saved ✓' : q.state === 'failed' ? 'Failed – retry' : 'Download';
    renderSingle();
    if (ok) setTimeout(() => { if (!running) { single.rest = 'Download'; renderSingle(); } }, 4000);
    else refreshResumeLabel();
  }

  function buildSingleButton() {
    if (!IS_VIDEO_PAGE) return;
    if (single.bar && single.bar.isConnected) return;
    const player = mainPlayerEl();
    if (!player) return;
    // Under #video on normal video pages; directly under the player elsewhere (shorts).
    const anchor = document.querySelector('.video-player-wrapper #video') || player;
    const { btn, setText } = siteButton('download', single.rest);
    btn.setAttribute('aria-label', 'Download video');
    btn.addEventListener('click', (e) => { e.preventDefault(); e.stopPropagation(); startSingle(); });
    const bar = document.createElement('div');
    bar.className = 'cdl-single-bar';
    bar.dataset.cdlUi = '';
    bar.appendChild(btn);
    anchor.after(bar);
    Object.assign(single, { bar, setText });
    renderSingle();
    refreshResumeLabel();
  }

  // ---------- shorts viewer: a Download action in every clip's rail ----------
  // Each clip is an <article class="shorts-slide" data-video-id="…"> with a .shorts-actions rail
  // (like, comments, share…). The button borrows the rail's own .shorts-action look. Its click is
  // taken at the window capture phase, before the feed's handlers, so the site never sees it (no
  // play/pause toggle, no rail handler). The download itself is the same single-video queue as on
  // the watch page, pointed at the clip's watch page (/video/<id>/<slug>/): the shorts page holds
  // the links of every clip in the feed, the watch page only this one.
  const shorts = { q: null, rest: new Map() };

  function shortEntry(slide) {
    const key = slide && slide.dataset.videoId;
    if (!key || !/^\d+$/.test(key) || +key === 0) return null;            // ad slots carry no clip id
    const a = slide.querySelector('.shorts-title[href]');
    const v = slide.querySelector('video');
    let url;
    try { url = pageUrlOf(a ? a.href : `/video/${key}/`); } catch (_) { return null; }
    return {
      key, url,
      title: cleanTitle(a ? a.textContent : '') || `Video ${key}`,
      thumb: (v && (v.dataset.poster || v.poster)) || '',
    };
  }

  function shortLabel(key) {
    const q = shorts.q;
    if (running && q && q.key === key) {
      if (q.state === 'downloading') return q.saving ? 'Saving' : q.pct != null ? `${Math.floor(q.pct * 100)}%` : '…';
      if (q.state === 'linking' || q.state === 'ready') return 'Link…';
    }
    return shorts.rest.get(key) || 'Download';
  }

  // ---- a second, prominent copy: site-styled button beside the feed's up/down arrows ----
  // It acts on the clip on screen (.shorts-slide.is-current). The arrows only exist on desktop
  // layouts; when they are hidden, this button hides too and the rail button remains.
  const shortsFloat = { btn: null, setText: null };
  // the clip on screen; null while an ad slot is on screen (no clip to download)
  const currentSlide = () => {
    const c = document.querySelector('.shorts-slide.is-current');
    if (c) return c.dataset.videoId ? c : null;
    return document.querySelector('.shorts-slide[data-video-id]');   // before the feed marks one
  };

  function floatLabel() {
    const q = shorts.q;
    if (running && q) {
      if (q.state === 'downloading') return q.saving ? 'Saving…' : q.pct != null ? `Downloading ${Math.floor(q.pct * 100)}%` : 'Downloading…';
      return 'Getting link…';
    }
    const cur = currentSlide();
    const rest = cur ? shorts.rest.get(cur.dataset.videoId) : null;
    return rest === 'Saved ✓' ? 'Saved ✓' : rest === 'Retry' ? 'Failed – retry' : 'Download';
  }

  function placeShortsFloat() {
    const b = shortsFloat.btn;
    if (!b) return;
    const arrows = [...document.querySelectorAll('.shorts-nav .shorts-nav-btn')]
      .map((x) => x.getBoundingClientRect()).filter((r) => r.width > 0 && r.height > 0);
    if (!arrows.length) { b.classList.add('cdl-hidden'); return; }
    b.classList.remove('cdl-hidden');
    const top = Math.min(...arrows.map((r) => r.top));
    const bottom = Math.max(...arrows.map((r) => r.bottom));
    const leftEdge = Math.min(...arrows.map((r) => r.left));
    const rightEdge = Math.max(...arrows.map((r) => r.right));
    const w = b.offsetWidth || 140;
    const vw = document.documentElement.clientWidth;
    // right of the arrows; flip to their left if it would run off the screen
    let left = rightEdge + 12;
    if (left + w > vw - 8) left = Math.max(8, leftEdge - 12 - w);
    // Centred with `top`, not a CSS transform: the site's .btn hover style sets its own transform,
    // which replaced translateY(-50%) and dropped the button by half its height under the cursor.
    const h = b.offsetHeight || 36;
    const l = `${Math.round(left)}px`, t = `${Math.round((top + bottom) / 2 - h / 2)}px`;
    if (b.style.left !== l) b.style.left = l;
    if (b.style.top !== t) b.style.top = t;
  }

  function buildShortsFloat() {
    if (shortsFloat.btn && shortsFloat.btn.isConnected) { placeShortsFloat(); return; }
    const { btn, setText } = siteButton('download', floatLabel());
    btn.classList.add('cdl-shorts-float');
    btn.dataset.cdlUi = '';
    btn.setAttribute('aria-label', 'Download this video');
    btn.addEventListener('click', (e) => {
      e.preventDefault();
      e.stopPropagation();
      if (!running) startShort(currentSlide());
    });
    document.body.appendChild(btn);
    Object.assign(shortsFloat, { btn, setText });
    placeShortsFloat();
    // the label follows the clip on screen: the feed moves .is-current as you scroll
    const feed = document.getElementById('shorts-feed') || document.querySelector('.shorts-feed');
    if (feed) new MutationObserver(renderShorts).observe(feed, { subtree: true, attributes: true, attributeFilter: ['class'] });
    // the arrows can move without a window resize (sidebar, header); a cheap re-check covers it
    setInterval(() => { if (!document.hidden) placeShortsFloat(); }, 1000);
  }

  // ---- media controls for the clip on screen ----
  // The feed's videos have no controls, and a tap layer plus the rail sit on top of each video, so
  // native controls would be covered. This is one small bar of our own, laid over the bottom of the
  // current clip: play/pause, time, seek, mute and volume. It never touches the video's `loop`, so
  // clips keep looping. It shows while the pointer moves over the clip (or the clip is paused) and
  // fades after a moment, so it doesn't sit on the title permanently.
  const SC_ICON = {
    play: '<svg viewBox="0 0 24 24"><path fill="currentColor" d="M8 5v14l11-7z"/></svg>',
    pause: '<svg viewBox="0 0 24 24"><path fill="currentColor" d="M6 5h4v14H6zm8 0h4v14h-4z"/></svg>',
    vol: '<svg viewBox="0 0 24 24"><path fill="currentColor" d="M3 9v6h4l5 5V4L7 9H3zm13.5 3A4.5 4.5 0 0 0 14 8v8a4.5 4.5 0 0 0 2.5-4zM14 3.23v2.06a7 7 0 0 1 0 13.42v2.06A9 9 0 0 0 14 3.23z"/></svg>',
    mute: '<svg viewBox="0 0 24 24"><path fill="currentColor" d="M3 9v6h4l5 5V4L7 9H3zm13.59 3L19 9.59 20.41 11 18 13.41 20.41 15.83 19 17.24 16.59 14.83 14.17 17.24 12.76 15.83 15.17 13.41 12.76 11l1.41-1.41L16.59 12z"/></svg>',
  };
  const sc = { bar: null, v: null, els: null, drag: false, vol: null, hideT: 0, over: false };
  const SC_EVENTS = ['timeupdate', 'durationchange', 'loadedmetadata', 'play', 'pause', 'volumechange', 'seeked', 'emptied'];

  function scRender() {
    const v = sc.v;
    if (!sc.els || !v) return;
    const { play, time, seek, mute, vol } = sc.els;
    const icon = v.paused ? SC_ICON.play : SC_ICON.pause;
    if (play.dataset.i !== String(v.paused)) { play.dataset.i = String(v.paused); play.innerHTML = icon; play.setAttribute('aria-label', v.paused ? 'Play' : 'Pause'); }
    const dur = isFinite(v.duration) ? v.duration : 0;
    const t = `${mmss(v.currentTime * 1000)} / ${mmss(dur * 1000)}`;
    if (time.textContent !== t) time.textContent = t;
    if (!sc.drag) seek.value = dur ? String(Math.round((v.currentTime / dur) * 1000)) : '0';
    const muted = v.muted || v.volume === 0;
    if (mute.dataset.i !== String(muted)) { mute.dataset.i = String(muted); mute.innerHTML = muted ? SC_ICON.mute : SC_ICON.vol; mute.setAttribute('aria-label', muted ? 'Unmute' : 'Mute'); }
    if (document.activeElement !== vol) vol.value = String(v.muted ? 0 : v.volume);
    if (v.paused) scShow(false);
  }

  function scBind(v) {
    if (sc.v === v) return;
    if (sc.v) SC_EVENTS.forEach((n) => sc.v.removeEventListener(n, scRender));
    sc.v = v;
    if (!v) return;
    SC_EVENTS.forEach((n) => v.addEventListener(n, scRender));
    if (sc.vol != null && Math.abs(v.volume - sc.vol) > 0.001) { try { v.volume = sc.vol; } catch (_) { /* ignore */ } }
    scRender();
  }

  // The bar's own "Mute" goes through the site's sound button when there is one, so the site's
  // sound setting (which it applies to every clip) stays in step.
  function scToggleMute() {
    const v = sc.v;
    if (!v) return;
    const was = v.muted;
    const site = document.querySelector('.shorts-sound');
    if (site) {
      site.click();
      setTimeout(() => { if (sc.v === v && v.muted === was) { v.muted = !was; } }, 120);
    } else v.muted = !was;
  }

  function scShow(autoHide = true) {
    if (!sc.bar || sc.bar.classList.contains('cdl-hidden')) return;
    sc.bar.classList.add('cdl-sc-on');
    clearTimeout(sc.hideT);
    if (autoHide) sc.hideT = setTimeout(() => {
      if (sc.over || sc.drag || (sc.v && sc.v.paused)) return;
      sc.bar.classList.remove('cdl-sc-on');
    }, 2500);
  }

  function placeShortsCtl() {
    if (!sc.bar) return;
    const slide = currentSlide();
    const v = slide && slide.querySelector('video');
    scBind(v || null);
    const r = v && v.getBoundingClientRect();
    if (!r || r.width < 80 || r.height < 80 || r.bottom < 0 || r.top > innerHeight) { sc.bar.classList.add('cdl-hidden'); return; }
    sc.bar.classList.remove('cdl-hidden');
    const l = `${Math.round(r.left + 8)}px`, w = `${Math.round(r.width - 16)}px`;
    const t = `${Math.round(Math.min(r.bottom, innerHeight) - 38 - 8)}px`;
    if (sc.bar.style.left !== l) sc.bar.style.left = l;
    if (sc.bar.style.width !== w) sc.bar.style.width = w;
    if (sc.bar.style.top !== t) sc.bar.style.top = t;
  }

  function buildShortsCtl() {
    if (sc.bar && sc.bar.isConnected) return;
    const bar = document.createElement('div');
    bar.className = 'cdl-sc cdl-hidden';
    bar.dataset.cdlUi = '';
    bar.innerHTML = '<button type="button" class="cdl-sc-play"></button><span class="cdl-sc-time">0:00 / 0:00</span>' +
      '<input type="range" class="cdl-sc-seek" min="0" max="1000" step="1" value="0" aria-label="Seek">' +
      '<button type="button" class="cdl-sc-mute"></button>' +
      '<input type="range" class="cdl-sc-vol" min="0" max="1" step="0.05" value="1" aria-label="Volume">';
    const els = {
      play: bar.querySelector('.cdl-sc-play'), time: bar.querySelector('.cdl-sc-time'),
      seek: bar.querySelector('.cdl-sc-seek'), mute: bar.querySelector('.cdl-sc-mute'), vol: bar.querySelector('.cdl-sc-vol'),
    };
    Object.assign(sc, { bar, els });

    els.play.addEventListener('click', () => {
      const v = sc.v;
      if (!v) return;
      const slide = v.closest('.shorts-slide');
      // same as the site's own tap: play/pause plus its is-paused marker
      if (v.paused) { v.play().catch(() => {}); if (slide) slide.classList.remove('is-paused'); }
      else { v.pause(); if (slide) slide.classList.add('is-paused'); }
      scShow();
    });
    const seekTo = () => {
      const v = sc.v;
      if (v && isFinite(v.duration) && v.duration > 0) v.currentTime = (+els.seek.value / 1000) * v.duration;
    };
    els.seek.addEventListener('pointerdown', () => { sc.drag = true; });
    els.seek.addEventListener('input', () => { sc.drag = true; seekTo(); scRender(); });
    els.seek.addEventListener('change', () => { seekTo(); sc.drag = false; scRender(); });
    els.seek.addEventListener('pointerup', () => { sc.drag = false; });
    els.mute.addEventListener('click', () => { scToggleMute(); scShow(); });
    els.vol.addEventListener('input', () => {
      const v = sc.v;
      if (!v) return;
      const x = +els.vol.value;
      sc.vol = x;
      v.volume = x;
      if (x > 0 && v.muted) scToggleMute();
      scShow();
    });
    bar.addEventListener('pointerenter', () => { sc.over = true; scShow(false); });
    bar.addEventListener('pointerleave', () => { sc.over = false; scShow(); });
    // the bar sits outside the feed; pass the wheel on so scrolling over it still changes clip
    bar.addEventListener('wheel', (e) => {
      const feed = document.getElementById('shorts-feed') || document.querySelector('.shorts-feed');
      if (feed) { e.preventDefault(); feed.scrollBy({ top: e.deltaY }); }
    }, { passive: false });

    // show while the pointer moves over the clip on screen
    const near = (e) => {
      const v = sc.v;
      if (!v) return;
      const r = v.getBoundingClientRect();
      if (e.clientX >= r.left && e.clientX <= r.right && e.clientY >= r.top && e.clientY <= r.bottom) scShow();
    };
    document.addEventListener('pointermove', near, { passive: true });
    document.addEventListener('touchstart', (e) => { if (e.touches[0]) near(e.touches[0]); }, { passive: true });

    document.body.appendChild(bar);
    let placing = false;
    const place = () => { if (!placing) { placing = true; requestAnimationFrame(() => { placing = false; placeShortsCtl(); }); } };
    document.addEventListener('scroll', place, { capture: true, passive: true });   // the feed scrolls, not the window
    window.addEventListener('resize', place);
    setInterval(() => { if (!document.hidden) placeShortsCtl(); }, 500);
    placeShortsCtl();
  }

  function renderShorts() {
    placeShortsCtl();
    if (shortsFloat.setText) {
      shortsFloat.setText(floatLabel());
      shortsFloat.btn.classList.toggle('cdl-dim', running);
    }
    for (const b of document.querySelectorAll('.cdl-shorts-dl')) {
      const key = b.dataset.cdlKey;
      const span = b.querySelector('span');
      const t = shortLabel(key);
      if (span && span.textContent !== t) span.textContent = t;
      b.classList.toggle('cdl-dim', running && !(shorts.q && shorts.q.key === key));
    }
  }

  function decorateShorts() {
    for (const slide of document.querySelectorAll('.shorts-slide[data-video-id]')) {
      const rail = slide.querySelector('.shorts-actions');
      if (!rail || rail.querySelector('.cdl-shorts-dl')) continue;
      const e = shortEntry(slide);
      if (!e) continue;
      const btn = document.createElement('button');
      btn.type = 'button';
      btn.className = 'shorts-action cdl-shorts-dl';
      btn.dataset.cdlUi = '';
      btn.dataset.cdlKey = e.key;
      btn.setAttribute('aria-label', 'Download video');
      btn.innerHTML = '<i class="fa fa-download"></i><span></span>';
      btn.querySelector('span').textContent = shortLabel(e.key);
      const report = rail.querySelector('.shorts-report');
      if (report) rail.insertBefore(btn, report); else rail.appendChild(btn);
    }
    renderShorts();
  }

  async function startShort(slide) {
    if (running) return;
    const e = shortEntry(slide);
    if (!e) return;
    const q = { n: 1, key: e.key, url: e.url, title: e.title, thumb: e.thumb };
    shorts.q = q;
    shorts.rest.delete(q.key);
    const { ok } = await runQueue([q], { heading: 'Downloading video', batchMode: false, onUpdate: renderShorts });
    shorts.q = null;
    shorts.rest.set(q.key, ok ? 'Saved ✓' : q.state === 'failed' ? 'Retry' : 'Download');
    renderShorts();
    if (ok) setTimeout(() => { if (shorts.rest.get(q.key) === 'Saved ✓') { shorts.rest.delete(q.key); renderShorts(); } }, 4000);
  }

  if (IS_SHORTS) {
    window.addEventListener('click', (e) => {
      const b = e.target instanceof Element && e.target.closest('.cdl-shorts-dl');
      if (!b) return;
      e.preventDefault();
      e.stopImmediatePropagation();
      if (!running) startShort(b.closest('.shorts-slide'));
    }, true);
  }

  // ---------- batch selection ----------
  const sel = { mode: false, order: [], items: new Map() };
  const batch = { wrap: null, main: null, cancel: null };

  function tileInfo(th) {
    const a = [...th.querySelectorAll('a[href]')].find((x) => isVideoHref(x.href));
    if (!a) return null;
    const img = th.querySelector('img');
    const tl = th.querySelector('.caption a[title], h3 a[title], h3 a');
    return {
      key: idFromUrl(a.href),
      url: pageUrlOf(a.href),
      title: cleanTitle((tl && (tl.getAttribute('title') || tl.textContent)) || (img && img.alt) || ''),
      thumb: (img && (img.currentSrc || img.src)) || '',
    };
  }

  function makeCheck() {
    const c = document.createElement('div');
    c.className = 'cdl-check';
    c.innerHTML = '<span class="cdl-box"></span><span class="cdl-num"></span>';
    return c;
  }

  function markEl(el, key) {
    el.classList.add('cdl-item');
    el.dataset.cdlKey = key;
    if (!el.querySelector(':scope > .cdl-check')) el.appendChild(makeCheck());
  }

  function decorate() {
    document.querySelectorAll('.thumbnail').forEach((th) => {
      if (th.classList.contains('cdl-item') || th.closest('[data-cdl-ui]') || th.matches('.promo-card, [data-adv] *')) return;
      const info = tileInfo(th);
      if (info && info.key) markEl(th, info.key);
    });
    const cur = currentEntry();
    if (cur) {
      cur.el.classList.add('cdl-player');
      if (cur.el.dataset.cdlKey !== cur.key) markEl(cur.el, cur.key);   // shorts can change video in place
    }
  }

  function refreshMarks() {
    document.querySelectorAll('.cdl-item').forEach((el) => {
      const i = sel.order.indexOf(el.dataset.cdlKey);
      el.classList.toggle('cdl-on', i >= 0);
      const num = el.querySelector(':scope > .cdl-check .cdl-num');
      const text = i >= 0 ? String(i + 1) : '';
      if (num && num.textContent !== text) num.textContent = text;
    });
  }

  function updateBatchLabel() {
    if (!batch.main) return;
    const n = sel.order.length;
    batch.cancel.btn.classList.toggle('cdl-hidden', !(sel.mode && !running));
    batch.main.btn.classList.toggle('cdl-dim', (sel.mode && !n) || running);
    batch.main.btn.title = sel.mode && !n ? 'Click videos to select them' : '';
    if (running) return batch.main.setText('Downloading…');
    if (sel.mode) return batch.main.setText(n === 1 ? 'Start Download (1)' : n ? `Start Downloads (${n})` : 'Start Downloads');
    batch.main.setText('Batch Download');
  }

  function setSelectMode(on) {
    sel.mode = on;
    if (!on) { sel.order = []; sel.items.clear(); }
    document.documentElement.classList.toggle('cdl-select', on);
    if (on) decorate();
    refreshMarks();
    updateBatchLabel();
  }

  // What a click inside selection mode points at: the on-screen player, a video tile, or a bare video link.
  function selectableFrom(target) {
    const cur = currentEntry();
    if (cur && cur.el.contains(target)) return cur;
    const th = target.closest('.thumbnail');
    if (th && !th.matches('.promo-card')) {
      const info = tileInfo(th);
      if (info && info.key) { markEl(th, info.key); return { el: th, ...info }; }
    }
    const a = target.closest('a[href]');
    if (a && isVideoHref(a.href)) {
      const key = idFromUrl(a.href);
      a.classList.add('cdl-linkitem');
      markEl(a, key);
      return { el: a, key, url: pageUrlOf(a.href), title: cleanTitle(a.getAttribute('title') || a.textContent), thumb: '' };
    }
    return null;
  }

  function toggle(entry) {
    if (sel.items.has(entry.key)) {
      sel.items.delete(entry.key);
      sel.order = sel.order.filter((k) => k !== entry.key);
    } else {
      sel.items.set(entry.key, { key: entry.key, url: entry.url, title: entry.title || `Video ${entry.key}`, thumb: entry.thumb });
      sel.order.push(entry.key);
    }
    refreshMarks();
    updateBatchLabel();
  }

  async function askLeave(target) {
    const n = sel.order.length;
    const c = await confirmDialog({
      title: 'That isn’t a video',
      text: `Batch selection is on, so clicks pick videos.${n ? ` Cancelling clears your ${n} selected video${n > 1 ? 's' : ''}.` : ''} Continue selecting, or cancel batch download?`,
      primary: 'Cancel batch download', secondary: 'Continue selecting', danger: true,
    });
    if (c !== 'primary') return;
    setSelectMode(false);
    // Let the original click go through now that selection is off (links, buttons, menus).
    const actionable = target.isConnected && target.closest('a[href], button, [role="button"], input, label, select, summary');
    if (actionable) setTimeout(() => actionable.click(), 0);
  }

  // Capture phase on window: runs before the page's own click handlers.
  window.addEventListener('click', (e) => {
    if (!sel.mode || running || e.button !== 0 || !(e.target instanceof Element)) return;
    if (e.target.closest('[data-cdl-ui]')) return;     // our own buttons and dialogs
    e.preventDefault();
    e.stopImmediatePropagation();
    if (dialogOpen) return;
    const entry = selectableFrom(e.target);
    if (entry) toggle(entry);
    else askLeave(e.target);
  }, true);

  document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape' && sel.mode && !running && !dialogOpen) setSelectMode(false);
  });

  async function runBatch() {
    const queue = sel.order.map((key, i) => {
      const it = sel.items.get(key);
      return { n: i + 1, key, url: it.url, title: it.title, thumb: it.thumb };
    });
    setSelectMode(false);
    const done = runQueue(queue, { heading: `Downloading ${queue.length} video${queue.length > 1 ? 's' : ''}`, batchMode: true });
    updateBatchLabel();
    await done;
    updateBatchLabel();
    refreshResumeLabel();
  }

  // Floating, top-right, just below the site's fixed header bar.
  let navRO = null;
  // Right edge of the header's right-aligned menu (<ul class="navbar-right">). Sign Up is its last
  // item, but the list stays anchored to the right when its items change (e.g. after logging in).
  // On narrow screens that list is hidden, so the header's content edge is used instead.
  function headerRightInset() {
    const vw = document.documentElement.clientWidth;
    const ul = document.querySelector('.navbar .navbar-right');
    if (ul && !ul.closest('[data-cdl-ui]')) {
      const r = ul.getBoundingClientRect();
      if (r.width > 0 && r.height > 0) {
        let pad = parseFloat(getComputedStyle(ul).paddingRight) || 0;
        const last = ul.lastElementChild;
        if (last) { const ls = getComputedStyle(last); pad += (parseFloat(ls.paddingRight) || 0) + (parseFloat(ls.marginRight) || 0); }
        return Math.max(0, Math.round(vw - r.right + pad));
      }
    }
    const box = document.querySelector('.navbar > .container-fluid, .navbar > .container');
    if (box) {
      const r = box.getBoundingClientRect();
      if (r.width > 0) return Math.max(0, Math.round(vw - r.right + (parseFloat(getComputedStyle(box).paddingRight) || 0)));
    }
    return 14;
  }

  function placeBatch() {
    if (!batch.wrap) return;
    const right = `${headerRightInset()}px`;
    if (batch.wrap.style.right !== right) batch.wrap.style.right = right;
    let top = 12;
    const nav = document.querySelector('.navbar-fixed-top, nav.navbar, header');
    if (nav && !nav.closest('[data-cdl-ui]')) {
      const r = nav.getBoundingClientRect();
      if (r.bottom > 0 && r.bottom < 260 && r.height > 0) top = Math.round(r.bottom + 10);
      if (!navRO && typeof ResizeObserver === 'function') { navRO = new ResizeObserver(() => placeBatch()); navRO.observe(nav); }
    }
    if (batch.wrap.style.top !== `${top}px`) batch.wrap.style.top = `${top}px`;
  }

  function buildBatchButtons() {
    if (batch.wrap && batch.wrap.isConnected) { placeBatch(); return; }
    const wrap = document.createElement('div');
    wrap.className = 'cdl-batch';
    wrap.dataset.cdlUi = '';
    const main = siteButton('batch', 'Batch Download');
    const cancel = siteButton('close', 'Cancel', 'btn btn-default');
    cancel.btn.classList.add('cdl-hidden');
    main.btn.addEventListener('click', (e) => {
      e.preventDefault();
      e.stopPropagation();
      if (running) return;
      if (!sel.mode) return setSelectMode(true);
      if (!sel.order.length) return;       // nothing picked yet; Cancel leaves selection
      runBatch();
    });
    cancel.btn.addEventListener('click', (e) => { e.preventDefault(); e.stopPropagation(); setSelectMode(false); });
    wrap.append(cancel.btn, main.btn);
    document.body.appendChild(wrap);
    Object.assign(batch, { wrap, main, cancel });
    placeBatch();
    updateBatchLabel();
  }

  // ---------- styles ----------
  const CSS = `
  .cdl-btn { display: inline-flex !important; align-items: center; gap: 7px; white-space: nowrap; }
  .cdl-ico { width: 16px; height: 16px; flex: none; display: block; }
  .cdl-btn.btn-gradient { box-shadow: 0 4px 14px rgba(0,0,0,.35); }
  .cdl-single-bar { display: flex; justify-content: flex-end; align-items: center; margin: 10px 0 0; }
  .cdl-batch { position: fixed; top: 12px; right: 14px; z-index: 2147482000; display: flex; gap: 8px; align-items: center; }
  .cdl-batch .btn-default { box-shadow: 0 4px 14px rgba(0,0,0,.35); }
  .cdl-dim { opacity: .65; }
  .cdl-btn.cdl-hidden { display: none !important; }
  .cdl-shorts-dl.cdl-dim { opacity: .45; pointer-events: none; }
  .cdl-shorts-float, .cdl-shorts-float:hover, .cdl-shorts-float:focus, .cdl-shorts-float:active {
    position: fixed; z-index: 2147482000; margin: 0 !important; transform: none !important; translate: none !important; top: auto; }

  .cdl-sc { position: fixed; z-index: 2147481000; display: flex; align-items: center; gap: 8px; box-sizing: border-box;
    height: 38px; padding: 0 10px; border-radius: 8px; background: rgba(0,0,0,.62); color: #fff;
    font: 600 12px/1 system-ui, sans-serif; opacity: 0; pointer-events: none; transition: opacity .18s; }
  .cdl-sc.cdl-sc-on { opacity: 1; pointer-events: auto; }
  .cdl-sc.cdl-hidden { display: none; }
  .cdl-sc button { flex: none; width: 28px; height: 28px; padding: 0; border: 0; border-radius: 6px; background: none; color: inherit;
    cursor: pointer; display: flex; align-items: center; justify-content: center; }
  .cdl-sc button:hover { background: rgba(255,255,255,.15); }
  .cdl-sc svg { width: 20px; height: 20px; display: block; }
  .cdl-sc-time { flex: none; font-variant-numeric: tabular-nums; white-space: nowrap; }
  .cdl-sc input[type="range"] { margin: 0; accent-color: #e91e63; cursor: pointer; height: 4px; }
  .cdl-sc-seek { flex: 1 1 auto; min-width: 40px; }
  .cdl-sc-vol { flex: 0 0 64px; width: 64px; }
  .cdl-shorts-dl span { font-variant-numeric: tabular-nums; }

  .cdl-item { position: relative; }
  html.cdl-select .cdl-item { cursor: pointer; }
  .cdl-check { position: absolute; top: 8px; left: 8px; z-index: 60; display: none; gap: 6px; align-items: center; pointer-events: none; }
  html.cdl-select .cdl-check { display: flex; }
  .cdl-linkitem > .cdl-check { position: static; display: none; margin-left: 6px; vertical-align: middle; }
  html.cdl-select .cdl-linkitem > .cdl-check { display: inline-flex; }
  .cdl-box { width: 22px; height: 22px; box-sizing: border-box; border: 2px solid #fff; border-radius: 5px; background: rgba(0,0,0,.45);
    box-shadow: 0 0 0 1px rgba(0,0,0,.55); display: flex; align-items: center; justify-content: center; transition: background .15s; }
  .cdl-on > .cdl-check .cdl-box { background: #22c55e; }
  .cdl-on > .cdl-check .cdl-box::after { content: ""; width: 5px; height: 10px; border: solid #fff; border-width: 0 2px 2px 0; transform: translateY(-1px) rotate(45deg); }
  .cdl-num { display: none; min-width: 22px; height: 22px; box-sizing: border-box; padding: 0 5px; background: #fff; color: #000;
    border: 2px solid #000; border-radius: 3px; font: 700 12px/18px system-ui, sans-serif; text-align: center; }
  .cdl-on > .cdl-check .cdl-num { display: block; }
  html.cdl-select .cdl-on:not(.cdl-linkitem) { outline: 3px solid #22c55e; outline-offset: 2px; border-radius: 6px; }
  html.cdl-select .cdl-player > .cdl-check { top: 12px; left: 12px; }

  .cdl-backdrop { position: fixed; inset: 0; z-index: 2147483000; background: rgba(0,0,0,.6); display: flex; align-items: center; justify-content: center; }
  .cdl-backdrop.cdl-over { z-index: 2147483100; }
  .cdl-modal { --bg: #1e1e1e; --fg: #f1f1f1; --muted: #b0b0b0; --line: #444; --glass: rgba(24,24,24,.72); --fill: 0%;
    width: min(1180px, 97vw); max-height: 88vh; display: flex; flex-direction: column; gap: 12px; box-sizing: border-box; padding: 20px;
    color: var(--fg); border-radius: 12px; box-shadow: 0 20px 60px rgba(0,0,0,.45);
    background: linear-gradient(90deg, #22c55e 0%, #16a34a var(--fill), transparent var(--fill)), var(--bg);
    font: 14px/1.45 system-ui, -apple-system, "Segoe UI", sans-serif; text-align: left; }
  .cdl-confirm { width: min(460px, 94vw); background: var(--bg); }
  .cdl-title { margin: 0; font-size: 18px; text-align: center; padding: 6px 12px; border-radius: 8px; background: var(--glass); align-self: center; color: var(--fg); }
  .cdl-confirm .cdl-title { background: none; }
  .cdl-text { margin: 0; }
  .cdl-warn { margin: 0; padding: 8px 12px; border-radius: 8px; background: var(--glass); border-left: 4px solid #f59e0b; }
  .cdl-tablewrap { overflow: auto; border: 1px solid var(--line); border-radius: 8px; background: var(--glass); }
  .cdl-table { width: 100%; border-collapse: collapse; color: var(--fg); }
  .cdl-table th, .cdl-table td { padding: 8px 10px; border-bottom: 1px solid var(--line); vertical-align: middle; text-align: center; }
  .cdl-table th { font-weight: 600; color: var(--muted); white-space: nowrap; }
  .cdl-table tr:last-child td { border-bottom: 0; }
  .cdl-table .c-chk { width: 26px; padding-right: 0; }
  .cdl-table input[type="checkbox"] { width: 17px; height: 17px; margin: 0; cursor: pointer; accent-color: #22c55e; vertical-align: middle; }
  .cdl-table input[type="checkbox"]:disabled { cursor: default; opacity: .55; }
  .cdl-table .c-n { font-weight: 700; width: 28px; }
  .cdl-table .c-name { text-align: left; max-width: 260px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
  .cdl-table .c-link, .cdl-table .c-res, .cdl-table .c-size { white-space: nowrap; }
  .cdl-table .c-status { text-align: left; min-width: 190px; max-width: 300px; }
  .cdl-st1 { font-weight: 600; white-space: nowrap; }
  .cdl-st2 { font-size: 12px; line-height: 1.35; color: var(--muted); margin-top: 2px; word-break: break-word; }
  .cdl-st2:empty { display: none; }
  tr.cdl-skip td:not(.c-chk) { opacity: .5; }
  .cdl-link { color: inherit !important; text-decoration: underline; font-weight: 600; }
  .c-status[data-state="done"] .cdl-st1 { color: #4ade80; }
  .c-status[data-state="failed"] .cdl-st1 { color: #f87171; }
  .c-status[data-state="cancelled"] .cdl-st1, .c-status[data-state="skipped"] .cdl-st1 { color: var(--muted); }
  .c-status[data-state="linking"] .cdl-st1 { color: #fbbf24; }
  .cdl-hover { display: inline-block; padding: 6px 12px; border: 1px dashed var(--muted); border-radius: 6px; color: var(--muted); font-size: 12px; cursor: default; }
  .cdl-preview { position: fixed; z-index: 2147483600; display: none; width: 320px; height: auto; border-radius: 8px; border: 2px solid #fff;
    box-shadow: 0 10px 30px rgba(0,0,0,.5); pointer-events: none; background: #000; }
  .c-prog { white-space: nowrap; }
  .cdl-progwrap { display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 3px; }
  .cdl-progwrap span { font-size: 12px; line-height: 1; }
  .cdl-bar { display: block; width: 110px; height: 6px; border-radius: 3px; background: var(--line); overflow: hidden; }
  .cdl-bar i { display: block; height: 100%; width: 0; background: #22c55e; transition: width .2s; }
  .cdl-bar.cdl-indet i { width: 40%; animation: cdl-slide 1.2s ease-in-out infinite; }
  @keyframes cdl-slide { 0% { transform: translateX(-100%); } 100% { transform: translateX(275%); } }
  .cdl-foot { display: flex; align-items: center; gap: 8px; justify-content: flex-end; }
  .cdl-cache { margin-right: auto; font-size: 13px; padding: 2px 8px; border-radius: 6px; background: var(--glass); }
  .cdl-cache:empty { display: none; }
  .cdl-btn2 { padding: 8px 16px; border-radius: 8px; border: 1px solid var(--line); background: var(--bg); color: var(--fg);
    font: 600 14px system-ui, sans-serif; cursor: pointer; }
  .cdl-btn2:hover:not(:disabled) { border-color: var(--fg); }
  .cdl-btn2:disabled { opacity: .5; cursor: default; }
  .cdl-main { background: var(--fg); color: var(--bg); border-color: var(--fg); }
  .cdl-danger { background: #dc2626; color: #fff; border-color: #dc2626; }
  `;

  // ---------- bootstrap ----------
  let scheduled = false;
  function tick() {
    scheduled = false;
    if (!document.body) return;
    if (IS_SHORTS) { buildShortsFloat(); buildShortsCtl(); decorateShorts(); return; }   // rail + arrow-side buttons + controls; no batch
    buildSingleButton();
    buildBatchButtons();
    if (sel.mode) { decorate(); refreshMarks(); }
  }
  const schedule = () => { if (!scheduled) { scheduled = true; requestAnimationFrame(tick); } };

  function start() {
    const style = document.createElement('style');
    style.textContent = CSS;
    document.head.appendChild(style);
    tick();
    new MutationObserver(schedule).observe(document.body, { childList: true, subtree: true });
    let placing = false;
    const place = () => { if (!placing) { placing = true; requestAnimationFrame(() => { placing = false; placeBatch(); placeShortsFloat(); }); } };
    window.addEventListener('scroll', place, { passive: true });
    window.addEventListener('resize', place);
    janitor().catch((e) => log('cleanup error', e));
    setInterval(() => { if (!running) janitor().catch(() => {}); }, 5 * 60 * 1000);
  }

  try {
    if (IS_SHORTS) {
      GM_registerMenuCommand('Download this video', () => startShort(document.querySelector('.shorts-slide.is-current')));
    } else {
      GM_registerMenuCommand('Batch download: select videos', () => { if (!running) setSelectMode(true); });
      if (IS_VIDEO_PAGE) GM_registerMenuCommand('Download this video', () => startSingle());
    }
    GM_registerMenuCommand('Delete unfinished downloads (resume data)', async () => {
      for (const it of await Store.list()) if (it.manifest?.state !== 'saved') await Store.remove(it.name);
      refreshResumeLabel();
    });
  } catch (_) { /* ignore */ }

  window.addEventListener('load', () => { setTimeout(schedule, 300); setTimeout(placeBatch, 1200); });
  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', start);
  else start();
})();