☰

Botbooru Mod

Botbooru QOL enhancements. Phone-friendly and customizable layout. All card information now shows below the card image (JAI/Chub style) with controls.

Terá de instalar uma extensão como Tampermonkey, Greasemonkey ou Violentmonkey para instalar este script.

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

Terá de instalar uma extensão como Tampermonkey ou Violentmonkey para instalar este script.

Terá de instalar uma extensão como Tampermonkey ou Userscripts para instalar este script.

Terá de instalar uma extensão como Tampermonkey para instalar este script.

Terá de instalar uma extensão de gestão de scripts de utilizador para instalar este script.

(Já tenho um gestor de scripts de utilizador, deixe-me instalá-lo!)

Terá de instalar uma extensão como Stylus para instalar este estilo.

Terá de instalar uma extensão como Stylus para instalar este estilo.

Terá de instalar uma extensão como Stylus para instalar este estilo.

Terá de instalar uma extensão de gestão de estilos de utilizador para instalar este estilo.

Terá de instalar uma extensão de gestão de estilos de utilizador para instalar este estilo.

Terá de instalar uma extensão de gestão de estilos de utilizador para instalar este estilo.

(Já tenho um gestor de estilos de utilizador, deixe-me instalá-lo!)

// ==UserScript==
// @name         Botbooru Mod
// @namespace    https://greasyfork.org/users/1646275
// @version      1.7.1
// @description  Botbooru QOL enhancements. Phone-friendly and customizable layout. All card information now shows below the card image (JAI/Chub style) with controls.
// @match        https://botbooru.com/*
// @match        https://www.botbooru.com/*
// @icon         https://botbooru.com/favicon.ico
// @run-at       document-start
// @noframes
// @grant        GM_registerMenuCommand
// @grant        GM_getValue
// @grant        GM_setValue
// @license      MIT
// ==/UserScript==

(function () {
  "use strict";

  var VERSION = "1.7.1";
  var NS = "bbx"; // BotBooru eXtension

  /* ───────────────────────── preferences ───────────────────────── */

  var PREFS_KEY = "botbooru_mod_prefs_v1";

  /* One settings key, read from the first launch. The blob this script filed under its old
     name is not imported and not read: the owner asked for no support for it at all. What
     mattered was never the old name but the values, and those lost their key for a different
     reason — see snapCap, which wrote a snapped value back over a stored one. */

  var DEFAULTS = {
    enabled: true,         // master switch: card info on the list
    showDesc: true,        // show the character description paragraph
    descLines: 3,          // its collapsed height: 2 | 3 | 4 | 6 | 8 | "full"
    showNotes: true,       // creator notes ("tldr") paragraph
    notesLines: 3,         // its collapsed height: 2 | 3 | 4 | 6 | 8 | "full"
    notesFirst: true,      // put creator notes above the description
    moreBehavior: "both",  // what "more ▾" expands: "notes" | "desc" | "both"
    nameAbove: true,       // move the character name above the artwork, as a title
    marqueeName: true,     // slide a name that does not fit in one line
    showTags: true,        // tag chips below the text
    tagCap: 4,             // how many chips to show (0 = all available)
    showStats: true,       // tokens / downloads / favourites / comments / views row
    hideOverlay: true,     // drop the site's hover overlay (the info is inline now)
    phoneColumns: "auto",  // phone grid: auto | 2 | 1 (list) | full (1 column, stacked)
    textSize: "m",         // s | m | l | xl
    openCards: false,      // start with every card's text fully expanded
    gearOpacity: 100,      // settings button opacity, 0..100 (slider, 10% steps)
    cardGap: 0,            // extra vertical space between cards, px (0 = the site's own)
    cardMaxWidth: 100,     // 1-column modes: the card's width as % of the column (100 = no cap)
    cardMaxHeight: 0,      // 1-column modes: the artwork's height in px (0 = its natural height)
    hiRes: false,          // 1-column modes: load the full-resolution picture, not the thumbnail
    killHoverZoom: false,  // turn off the site's zoom-on-hover of the card picture
    dlDuplicate: true,     // card page: repeat the download buttons right under the pictures
    dlCompact: false,      // card page: squeeze the download block into one short row

    /* 1.7.0. Whatever only rearranges what the page already has defaults ON, and so does
       letting the artwork keep the ratio the picture really has: a 3:4 box that crops a
       portrait is the site's guess, not the uploader's. The two that can surprise default
       OFF — a second search box, and loading full-resolution pictures. Reading a card's
       stored text is never automatic: one request for one card, on that card's tap. */
    artNative: true,       // 1-column modes: artwork keeps its own ratio (needs Artwork height = 0)
    detailBar: true,       // card page: one compact bar of facts above the duplicated buttons
    loginShortcut: true,   // header: a Log in button where the site has none for logged-out visitors
    showBlChip: true,      // header: BL: off / BL: on — the site's reveal-blocked peek, reachable on a phone
    headerCompact: true,   // header: shrink the site's own header buttons to a glyph or an on/off state
    dupPager: true,        // list: the site's paginator repeated above the cards
    dupSearch: false,      // list: the search box repeated above the cards (mirrors both ways: opt-in)
    swipeDrawer: true,     // phone: swipe right from the left screen edge opens the site's drawer
    onDemandData: true,    // a media button on each card: one request for that one card, on a tap
    cardUploader: true,    // list: an UPLOADER line under each card's picture, where the site names one

    /* The sheet's own shape: which tab was last open, and which folded groups were open.
       This is the mod's state, not the page's, and both have to survive a reopen: a sheet
       that forgets what you had unfolded is a sheet you re-open blind. */
    ui: { tab: "list", open: {} },
  };

  /* Every number-typed setting and the range it accepts. The slider that offers a value and
     the reader that uses it now read the same pair, so a control can no longer offer a value
     the reader would clamp away. */
  var PREF_RANGES = {
    gearOpacity: [0, 100],
    cardGap: [0, 150],
    cardMaxWidth: [30, 100],
    cardMaxHeight: [0, 600],
    tagCap: [0, 50],
  };
  var PREF_WORDS = {
    phoneColumns: ["auto", "2", "1", "full"],
    textSize: ["s", "m", "l", "xl"],
    moreBehavior: ["notes", "desc", "both"],
  };

  /* ───────────────────────── labels: every word the mod writes ─────────────────────────
     One place holds the wording the sheet, the bars and the buttons print; the code that
     builds them carries no sentence of its own. Wording that only reads well next to a
     number (intro/intros, lorebook/lorebooks) is kept as a pair so the count decides. */
  var LABELS = {
    panelTitle: "Botbooru Mod settings",
    close: "Close settings",
    reset: "Reset to defaults",
    version: function (v) { return "v" + v + " \u00B7 saved on this device"; },

    tabs: { list: "Card list", page: "Card page", ext: "Extension" },
    tabHint: {
      list: "Everything on the card list: the cards, their text, tags and stats.",
      page: "Everything on a card's own page: the repeated buttons and the bar of facts.",
      ext: "Everything the mod adds to the site's own chrome: header, drawer, settings button.",
    },

    /* the card list */
    enabled: "Card info on the list",
    layout: "Layout",
    phoneColumns: "Phone columns",
    columns: { auto: "Site default", "2": "2 columns", "1": "1 column, thumb beside text", full: "1 column, full width" },
    textSize: "Text size",
    sizes: { s: "Small", m: "Medium", l: "Large", xl: "Extra large" },
    cardGap: "Space between cards",
    gapSite: "site",
    secCardSize: "Card size & picture",
    cardWidth: "Card width",
    artHeight: "Artwork height",
    artHeightAuto: "auto",
    artNative: "Keep the picture's own ratio",
    hiRes: "Full-resolution pictures",
    hintCardSize: "Card width and artwork height apply in 1-column mode. Keeping the picture's own ratio and an artwork height cap cannot both be on: the ratio wins.",
    hintOneColumn: "Card width, artwork height, full-resolution pictures and the picture's own ratio all apply in the 1-column modes. Switch Phone columns to 1 column or full width to reach them.",
    hintPhoneOnly: "This is a phone control: below the site's 1280 px drawer breakpoint only.",

    textSection: "Text & notes",
    showDesc: "Description",
    showNotes: "Creator notes",
    notesFirst: "Notes above the description",
    openCards: "Cards start expanded",
    moreBehavior: "What the more button opens",
    moreTargets: { both: "Text and notes", desc: "Text only", notes: "Notes only" },
    hintText: "Collapsed text keeps its own line cap. The more button opens it whole on that card.",
    lineOff: "Off",
    lineFull: "Full text",
    lineCount: function (n) { return n + " lines"; },
    tagsOnCard: "Tags on a card",
    hintInfoOff: "Card info is off: the site's own card layout is left alone, and everything below is stored for when it is on.",
    uploadSection: "Settings button",

    tagsSection: "Tags, stats & media",
    tagsOff: "Off",
    tagsCount: function (n) { return n + " tags"; },
    tagsAll: "All tags",
    showStats: "Stats row (tokens, downloads, favourites\u2026)",
    onDemandData: "Media button on each card",
    hintOnDemand: "That button sends one request for that one card, and only after you tap it. It counts the media the card's stored text holds.",
    siteCopies: "Repeating the site's own controls",
    dupPager: "Paginator above the cards",
    dupSearch: "Search box above the cards",
    hintSiteCopies: "Both copy something the site already has, put where a thumb reaches it without scrolling back up. The site keeps its own copy where it is.",
    /* where a card's own name sits, and what a name too long for one line does there */
    cardUploader: "Uploader line under the picture",
    uploaderLabel: "Uploader:",
    hintUploader: "Drawn only from what the site itself states about a card: the listing answer the page already fetched, a profile's own answer, or the card payload a tap on that card's media button brings back. An uploader id with no name is asked about once and remembered; an id the site will not name produces no name, and a card nobody attributes gets no line.",

    nameSection: "Card name",
    nameAbove: "Name above the picture",
    marqueeName: "Slide a name too long for one line",
    hintName: "Off: the name stays where the site puts it, under the picture with the rest of the info. The sliding applies to a name placed above the picture.",

    hovering: "Hovering a card",
    hoverChoices: { site: "As the site does it", overlay: "No info overlay", zoom: "No zoom on the picture", none: "Neither" },

    /* a card's own page */
    dlDuplicate: "Repeat the download buttons under the pictures",
    detailBar: "Bar of facts above them",
    secCardPage: "Card page details",
    dlCompact: "Small labels on the repeated buttons",
    hintCardPage: "Two things on a card's own page always apply and have no switch: the main picture is shown at its own height (never capped, never cropped), and the uploader's name sits as a chip at the top of the card's info.",

    /* the mod's own chrome */
    headerSection: "Header",
    headerCompact: "Short header labels",
    hintHeaderCompact: "Every header button becomes one glyph, or its state (on / off) with nothing else around it. The site's own wording survives in the tooltip and in what a screen reader reads.",
    loginShortcut: "Log-in button as a lock icon",
    showBlChip: "Chip for blocked content",
    swipeDrawer: "Swipe from the left edge opens the menu",
    gearSection: "Settings button",
    gearOpacity: "Opacity",
    hintGear: "0% hides the button. Settings stay available in the userscript manager's own menu.",

    /* controls the mod puts on a card */
    more: "more \u25BE",
    less: "less \u25B4",
    media: "media \u25BE",
    mediaOpen: "media \u25B4",
    reading: "reading\u2026",
    barWithMedia: function (n) { return "with " + n + " media"; },
    notesTag: "Creator notes",
    chipTitle: function (name) { return "Search cards tagged " + name; },
    chipProfileTitle: function (name) { return name + "'s uploads"; },

    /* the media button's one line: I intro(s) \u00B7 M/L links \u00B7 G gallery */
    introOne: "intro",
    introMany: "intros",
    linksWord: "links",
    galleryWord: "gallery",
    mediaTitle: function (where) {
      return "counted in this card's own text" + (where ? " \u2014 media in: " + where : "") +
        " \u00B7 botbooru's viewer here hides inline styles, video, audio and iframes; JAI, chub and SillyTavern render them";
    },
    mediaFail: function (why) {
      return "the site would not give this card's text (" + why + ") \u2014 a login, an NSFW or an NSFL rule can hide it";
    },
    mediaNoId: "this card does not say which post it is",
    mediaAsk: "Ask the site for this one card's stored text and count what it holds. Nothing is fetched until you tap.",

    /* the bar of facts on a card's page */
    lorebookOne: "lorebook",
    lorebookMany: "lorebooks",
    tokensTotal: "tokens total",
    notesSubject: "Creator's Notes",
    notesMarkup: "has custom CSS/HTML",
    notesMedia: function (n) { return "with " + n + " media"; },
    barIntroTitle: "first message plus the alternate greetings the card stores",
    barIntroMediaTitle: "unique media links found inside those greetings",
    barLoreTitle: "lorebooks this card points at, and the tokens their entries add up to",
    barNotesTitle: "custom markup the creator wrote into the notes: inline styles, style blocks, img / video / audio tags, CSS backgrounds",
    barFieldLine: function (label, links, media) { return label + ": " + links + " links, " + media + " media"; },
    barCountedLine: "counted in the card's stored text, not in what this page renders",
  };

  /* The order the site itself uses for a card's tag categories, and the rank the mod applies
     when it builds the chip row, so the writer chip leads the row the way the site's own tag
     sections lead it. Auto keeps the last seat for the same reason the site gives it. */
  var CATEGORY_RANK = {
    writer: 0, artist: 1, character: 2, characters: 2, general: 3, copyright: 4,
    scenarios: 5, settings: 6, activities: 7, meta: 8, nsfl: 9, language: 10, auto: 11,
  };
  var UNKNOWN_CATEGORY_RANK = 3;

  /* Header compaction: the site's state switches keep their short code plus the state, its
     fixed buttons become one glyph. The site's wording is handed back the moment the switch
     is off, and keeps living in title / aria-label while it is on. */
  var HEADER_STATE = { "ai-toggle-btn": "AI", "nsfw-toggle-btn": "NSFW", "nsfl-quick-toggle-btn": "NSFL" };
  var HEADER_GLYPH = {
    "nav-upload-btn": "\u2B06",
    "nav-settings-label": "\uD83D\uDC64",
    "nav-staff-stats-btn": "\u2593",
    "nav-create-btn": "\u2726",
  };
  var HEADER_GLYPH_TITLE = {
    "nav-upload-btn": "Upload",
    "nav-settings-label": "My Account",
    "nav-staff-stats-btn": "Staff stats",
    "nav-create-btn": "Bot Studio",
  };


  /* 1.2.x stored one shared "lines" value; 1.3.0 splits it per paragraph. */
  /* 1.2.x stored one shared "lines" value; 1.3.0 splits it per paragraph. */
  function migrate(data) {
    if (Object.prototype.hasOwnProperty.call(data, "lines") &&
        !Object.prototype.hasOwnProperty.call(data, "descLines")) {
      data.descLines = data.lines;
    }
    return data;
  }

  /* A stored value is only trusted after it is read back as the type the shipped default is.
     Some managers JSON-serialise GM_setValue and hand back "true" for true, or 1 for a number;
     a string "true" is truthy while a string "false" is truthy too, and a boolean setting that
     arrives as a string never switches off. Numbers are clamped into the very range the slider
     offers, so a value an older build stored cannot sit outside what today's control can show. */
  /* The two line-count settings take one word beyond their numbers: "full" means the text is
     not clamped at all. Clamping it back to a number would quietly throw away a choice the
     reader can still make in the sheet. */
  var LINES_KEYS = { descLines: 1, notesLines: 1 };

  function normPref(key, value) {
    var dflt = DEFAULTS[key];
    if (LINES_KEYS[key] && value === "full") return "full";
    if (key === "ui") {
      var out = (value && typeof value === "object") ? value : {};
      var tabs = LABELS.tabs;
      var tab = typeof out.tab === "string" && tabs[out.tab] ? out.tab : DEFAULTS.ui.tab;
      var open = (out.open && typeof out.open === "object") ? out.open : {};
      var clean = {};
      Object.keys(open).forEach(function (k) { if (k) clean[k] = !!open[k]; });
      return { tab: tab, open: clean };
    }
    if (typeof dflt === "boolean") {
      if (typeof value === "boolean") return value;
      if (typeof value === "number") return value !== 0;
      if (typeof value === "string") {
        if (/^(true|1|on|yes)$/i.test(value)) return true;
        if (/^(false|0|off|no|)$/i.test(value)) return false;
      }
      return dflt;
    }
    if (typeof dflt === "number") {
      var n = parseInt(value, 10);
      if (isNaN(n)) return dflt;
      var range = PREF_RANGES[key];
      if (range) n = Math.max(range[0], Math.min(range[1], n));
      return n;
    }
    if (typeof dflt === "string") {
      var words = PREF_WORDS[key];
      if (words && words.indexOf(String(value)) !== -1) return String(value);
      if (!words && typeof value === "string" && value) return value;
      return dflt;
    }
    return value;
  }

  var prefs = (function makeStore() {
    var data = null;

    function readRaw(key) {
      var v = null;
      try {
        if (typeof GM_getValue === "function") v = GM_getValue(key, null);
      } catch (e) { /* fall through to localStorage */ }
      if (v === null || v === undefined) {
        try { v = JSON.parse(localStorage.getItem(key) || "null"); } catch (e) { v = null; }
      }
      if (typeof v === "string") { try { v = JSON.parse(v); } catch (e) { /* not JSON: keep the string */ } }
      return (v && typeof v === "object" && !Array.isArray(v)) ? v : null;
    }

    function load() {
      if (data) return data;
      data = migrate(readRaw(PREFS_KEY) || {});
      Object.keys(data).forEach(function (k) {
        if (Object.prototype.hasOwnProperty.call(DEFAULTS, k)) data[k] = normPref(k, data[k]);
      });
      return data;
    }

    function save() {
      try {
        if (typeof GM_setValue === "function") { GM_setValue(PREFS_KEY, data); return; }
      } catch (e) { /* fall through */ }
      try { localStorage.setItem(PREFS_KEY, JSON.stringify(data)); } catch (e) { /* private mode */ }
    }

    return {
      get: function (key) {
        load();
        return Object.prototype.hasOwnProperty.call(data, key) ? data[key] : DEFAULTS[key];
      },
      set: function (key, value) {
        load();
        data[key] = normPref(key, value);
        save();
        applyPref(key);
      },
      all: function () {
        load();
        var out = {};
        Object.keys(DEFAULTS).forEach(function (k) {
          out[k] = Object.prototype.hasOwnProperty.call(data, k) ? data[k] : DEFAULTS[k];
        });
        return out;
      },
    };
  })();

  function P(key) { return prefs.get(key); }

  /* The sheet's own state (open tab, open folded groups) lives in one pref object. */
  function uiTab() { var u = P("ui"); return (u && u.tab) || DEFAULTS.ui.tab; }
  function uiOpen(name) { var u = P("ui"); return !!(u && u.open && u.open[name]); }
  function uiSet(patch) {
    var u = P("ui");
    var next = { tab: (u && u.tab) || DEFAULTS.ui.tab, open: {} };
    Object.keys((u && u.open) || {}).forEach(function (k) { next.open[k] = !!u.open[k]; });
    if (patch) {
      if (patch.tab) next.tab = patch.tab;
      Object.keys(patch.open || {}).forEach(function (k) { next.open[k] = !!patch.open[k]; });
    }
    prefs.set("ui", next);
  }

  /* ───────────────── what a changed setting rebuilds ─────────────────
     applyClasses turns every stored setting into the html classes the stylesheet reads, and
     it runs on every write. What it cannot do is change what a card says, what the header
     holds, or what a card's own page shows — those need their own pass, and until now each
     control had to remember to run its own, which is exactly the kind of thing that gets
     missed. Writing a setting now routes through this table, so a control cannot forget.
     The rebuilds are coalesced: dragging a slider or flipping a switch rebuilds once, on the
     next tick, not once per event. */
  var CARD_PREFS = {
    showDesc: 1, descLines: 1, showNotes: 1, notesLines: 1, notesFirst: 1, moreBehavior: 1,
    nameAbove: 1, marqueeName: 1, showTags: 1, tagCap: 1, showStats: 1, openCards: 1, cardUploader: 1,
    onDemandData: 1, enabled: 1, phoneColumns: 1, textSize: 1, hideOverlay: 1,
  };
  var CHROME_PREFS = {
    headerCompact: 1, loginShortcut: 1, showBlChip: 1, dupPager: 1, dupSearch: 1,
    swipeDrawer: 1, enabled: 1,
  };
  var PAGE_PREFS = { dlDuplicate: 1, dlCompact: 1, detailBar: 1, enabled: 1 };
  var THUMB_PREFS = { hiRes: 1, phoneColumns: 1, cardMaxHeight: 1, artNative: 1 };

  var pendingApply = { cards: false, chrome: false, page: false };
  var applyTimer = 0;

  function flushApply() {
    applyTimer = 0;
    if (pendingApply.cards) { pendingApply.cards = false; try { refreshAll(); } catch (e) { /* a card pass is not worth losing the rest */ } }
    if (pendingApply.page) { pendingApply.page = false; try { detailPass(true); } catch (e) { /* or the card page's */ } }
    if (pendingApply.chrome) { pendingApply.chrome = false; try { chromePass(); } catch (e) { /* or the header's */ } }
  }

  function scheduleApply(kind) {
    pendingApply[kind] = true;
    if (applyTimer) clearTimeout(applyTimer);
    applyTimer = setTimeout(flushApply, 30);
  }

  function applyPref(key) {
    applyClasses();
    if (THUMB_PREFS[key]) queueThumbs();
    if (CARD_PREFS[key]) scheduleApply("cards");
    if (PAGE_PREFS[key]) scheduleApply("page");
    if (CHROME_PREFS[key]) scheduleApply("chrome");
  }


  /* ───────────────────────── which window ───────────────────────── */

  /* A manager that honours @grant hands the script a sandboxed window: writes to it stay
     inside the sandbox, and so — on some managers — do reads of anything the page put on its
     own window. Measured on a real install, 2026-11-14: the duplicated download buttons worked
     (the DOM is shared either way), while the facts bar never appeared at all and the BL chip
     sat at "BL: off" through a toggle the site had really flipped, because both read
     window.currentPostDetail / window._revealBlocked from the wrong window.
     The page's own globals — the card the site loaded, the site's own controls — live on the
     real window, which is what unsafeWindow is. Where a manager does not offer it, or offers a
     restricted one (Tampermonkey's MV3 mode), this falls back to the sandbox window and every
     feature behaves exactly as it did before. */
  function pageWin() {
    try {
      return typeof unsafeWindow !== "undefined" && unsafeWindow ? unsafeWindow : window;
    } catch (e) { return window; }
  }

  /* ───────────────────────── stylesheet ───────────────────────── */

  var CSS = [
    /* font size knob: three named steps, phone/desktop share the same scale */
    "html.bbx-s { --bbx-fs: 10px; --bbx-fs-sm: 9px; }",
    "html.bbx-m { --bbx-fs: 11px; --bbx-fs-sm: 9.5px; }",
    "html.bbx-l { --bbx-fs: 12.5px; --bbx-fs-sm: 11px; }",
    "html.bbx-xl { --bbx-fs: 13.75px; --bbx-fs-sm: 12.1px; }",   /* 1.1 × large */
    "html { --bbx-fg: #374151; --bbx-fg-dim: #6b7280; --bbx-line: rgba(0,0,0,.10); --bbx-btn-bg: rgba(0,0,0,.05); }",
    "html.dark { --bbx-fg: #d1d5db; --bbx-fg-dim: #9ca3af; --bbx-line: rgba(255,255,255,.14); --bbx-btn-bg: rgba(255,255,255,.08); }",

    /* our own UI — settings button and panel — keeps one theme of its own in both
       site themes: dark black, graphite grey, white */
    "html { --bbx-ui-bg: #101114; --bbx-ui-bg-2: #1b1e23; --bbx-ui-fg: #f6f7f9;",
    "  --bbx-ui-dim: #98a1ad; --bbx-ui-line: #2b2f36; --bbx-ui-edge: #343943; --bbx-gear-op: 1; }",

    /* the inline info block that replaces the hover overlay */
    "." + NS + "-info {",
    "  border-top: 1px solid var(--bbx-line);",
    "  padding: 5px 8px 7px;",
    "  display: flex; flex-direction: column; gap: 5px;",
    "  font-size: var(--bbx-fs);",
    "  line-height: 1.33;",
    "  color: var(--bbx-fg);",
    "}",
    "." + NS + "-text { margin: 0; overflow-wrap: break-word; word-break: break-word; white-space: pre-wrap; }",
    "." + NS + "-text code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: .95em; }",
    "." + NS + "-clamp {",
    "  display: -webkit-box; -webkit-box-orient: vertical; overflow: hidden;",
    "}",
    "." + NS + "-clamp-2 { -webkit-line-clamp: 2; line-clamp: 2; }",
    "." + NS + "-clamp-3 { -webkit-line-clamp: 3; line-clamp: 3; }",
    "." + NS + "-clamp-4 { -webkit-line-clamp: 4; line-clamp: 4; }",
    "." + NS + "-clamp-6 { -webkit-line-clamp: 6; line-clamp: 6; }",
    "." + NS + "-clamp-8 { -webkit-line-clamp: 8; line-clamp: 8; }",
    "." + NS + "-notes { color: var(--bbx-fg-dim); }",
    /* with the description switched off, creator notes are the card's text, so they
       read in the same colour the description would have used */
    "." + NS + "-notes." + NS + "-bright { color: var(--bbx-fg); }",
    "." + NS + "-bright > ." + NS + "-notes-label { color: var(--bbx-fg); opacity: .75; }",
    /* the uploader line under a listing card's picture: the label in the notes label's own
       look, the name in the card's own uploader chip */
    "." + NS + "-up-row { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }",
    "." + NS + "-up-row ." + NS + "-notes-label { margin-bottom: 0; }",

    "." + NS + "-notes-label {",
    "  display: block; font-size: var(--bbx-fs-sm); letter-spacing: .04em;",
    "  text-transform: uppercase; opacity: .8; margin-bottom: 2px;",
    "}",
    "." + NS + "-more {",
    "  align-self: stretch; text-align: center; cursor: pointer; user-select: none;",
    "  font-size: var(--bbx-fs-sm); font-weight: 700; color: var(--bbx-fg-dim);",
    "  background: var(--bbx-btn-bg); border-radius: 6px;",
    "  padding: 3px 8px; min-height: 21px;   /* comfortable phone tap target */",
    "}",
    "." + NS + "-more:active { opacity: .6; }",

    /* character name moved above the artwork as a card title. The site's own name
       line stays in the DOM, hidden, so its badges/controls are untouched. */
    "." + NS + "-title {",
    "  display: flex; align-items: center; gap: 6px;",
    "  padding: 6px 8px 5px;",
    "  font-size: var(--bbx-fs); font-weight: 700; line-height: 1.3;",
    "  color: var(--bbx-fg);",
    "}",
    "." + NS + "-title-text {",
    "  flex: 1 1 auto; min-width: 0; white-space: nowrap;",
    "  overflow: hidden; text-overflow: ellipsis;",
    "}",
    /* sliding name: only for a title that measured wider than its box (see measureTitle) */
    /* the same slide for the name left where the site keeps it: the text is wrapped in
       a span we can move inside the site's own overflow-hidden row. One line, exactly the
       way the site's own row draws it — measured on the live site a `pre` span and a
       `nowrap` span of the same name are the same width, but `pre` gives a name that
       carries a newline a second line of its own for the row to clip */
    "." + NS + "-marquee-inner { display: inline-block; white-space: nowrap; }",
    "." + NS + "-name-slide { text-overflow: clip; }",
    "." + NS + "-name-slide > " + "." + NS + "-marquee-inner {",
    "  animation: bbx-slide var(--bbx-marquee-dur, 9s) ease-in-out 1.2s infinite alternate;",
    "}",
    /* the title slides the same way: the clip box stays put and the text inside it
       moves. Animating the clip itself just pushes the visible letters away — the
       1.3.0 bug: the name slid out of the card and nothing new came in. */
    "." + NS + "-title.bbx-marquee-on > ." + NS + "-title-text { text-overflow: clip; }",
    "." + NS + "-title.bbx-marquee-on > ." + NS + "-title-text > ." + NS + "-marquee-inner {",
    "  animation: bbx-slide var(--bbx-marquee-dur, 9s) ease-in-out 1.2s infinite alternate;",
    "}",
    "@keyframes bbx-slide {",
    "  from { transform: translateX(0); }",
    "  to { transform: translateX(var(--bbx-marquee-dx, 0px)); }",
    "}",
    "@media (prefers-reduced-motion: reduce) {",
    "  ." + NS + "-title.bbx-marquee-on > ." + NS + "-title-text { text-overflow: ellipsis; }",
    "  ." + NS + "-title.bbx-marquee-on > ." + NS + "-title-text > ." + NS + "-marquee-inner { animation: none; }",
    "  ." + NS + "-name-slide > ." + NS + "-marquee-inner { animation: none; }",
    "  ." + NS + "-name-slide { text-overflow: ellipsis; }",
    "}",
    "." + NS + "-hidden-name { display: none !important; }",
    "." + NS + "-hidden-foot { display: none !important; }",

    /* tag chips: same hues the site uses on the hover overlay, re-tuned for a card background */
    "." + NS + "-tags { display: flex; flex-wrap: wrap; gap: 3px; }",
    "." + NS + "-tag {",
    "  display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;",
    "  padding: 1px 5px; border-radius: 5px; border: 1px solid;",
    "  font-size: var(--bbx-fs-sm); line-height: 1.3; cursor: pointer;",
    "}",
    "." + NS + "-tag[data-cat=writer]     { color:#9a3412; background:rgba(234,88,12,.13);  border-color:rgba(234,88,12,.40); }",
    "." + NS + "-tag[data-cat=artist]     { color:#991b1b; background:rgba(239,68,68,.13);  border-color:rgba(239,68,68,.40); }",
    "." + NS + "-tag[data-cat=character]  { color:#166534; background:rgba(34,197,94,.13);  border-color:rgba(34,197,94,.40); font-weight:700; }",
    "." + NS + "-tag[data-cat=scenarios]  { color:#047857; background:rgba(16,185,129,.13); border-color:rgba(16,185,129,.40); }",
    "." + NS + "-tag[data-cat=settings]   { color:#92400e; background:rgba(245,158,11,.13); border-color:rgba(245,158,11,.40); }",
    "." + NS + "-tag[data-cat=activities] { color:#3f6212; background:rgba(132,204,22,.15); border-color:rgba(132,204,22,.40); }",
    "." + NS + "-tag[data-cat=copyright]  { color:#9d174d; background:rgba(236,72,153,.13); border-color:rgba(236,72,153,.40); }",
    "." + NS + "-tag[data-cat=meta]       { color:#6b21a8; background:rgba(168,85,247,.13); border-color:rgba(168,85,247,.40); }",
    "." + NS + "-tag[data-cat=nsfl]       { color:#44403c; background:rgba(120,113,108,.16);border-color:rgba(120,113,108,.42); }",
    "." + NS + "-tag[data-cat=language]   { color:#0f766e; background:rgba(20,184,166,.13); border-color:rgba(20,184,166,.40); }",
    "." + NS + "-tag[data-cat=auto]       { color:#475569; background:rgba(100,116,139,.14);border-color:rgba(100,116,139,.35); }",
    "." + NS + "-tag[data-cat=general]    { color:#1e40af; background:rgba(59,130,246,.13); border-color:rgba(59,130,246,.40); }",
    ".dark ." + NS + "-tag[data-cat=writer]     { color:#fdba74; }",
    ".dark ." + NS + "-tag[data-cat=artist]     { color:#fca5a5; }",
    ".dark ." + NS + "-tag[data-cat=character]  { color:#86efac; }",
    ".dark ." + NS + "-tag[data-cat=scenarios]  { color:#6ee7b7; }",
    ".dark ." + NS + "-tag[data-cat=settings]   { color:#fcd34d; }",
    ".dark ." + NS + "-tag[data-cat=activities] { color:#d9f99d; }",
    ".dark ." + NS + "-tag[data-cat=copyright]  { color:#f9a8d4; }",
    ".dark ." + NS + "-tag[data-cat=meta]       { color:#d8b4fe; }",
    ".dark ." + NS + "-tag[data-cat=nsfl]       { color:#d6d3d1; }",
    ".dark ." + NS + "-tag[data-cat=language]   { color:#5eead4; }",
    ".dark ." + NS + "-tag[data-cat=auto]       { color:#cbd5e1; }",
    ".dark ." + NS + "-tag[data-cat=general]    { color:#93c5fd; }",
    "." + NS + "-tags-more { color: var(--bbx-fg-dim); font-size: var(--bbx-fs-sm); padding: 2px 4px; }",

    /* stats row */
    "." + NS + "-stats {",
    "  display: flex; flex-wrap: wrap; gap: 8px;",
    "  color: var(--bbx-fg-dim); font-size: var(--bbx-fs-sm);",
    "  font-variant-numeric: tabular-nums;",
    "}",
    "." + NS + "-stat { display: inline-flex; align-items: center; gap: 3px; white-space: nowrap; }",
    "." + NS + "-stat svg { width: 12px; height: 12px; flex: none; }",

    /* the hover overlay is redundant once the info is inline */
    "html.bbx-hide-overlay .gallery-card-hover-stack { display: none !important; }",
    "html.bbx-hide-overlay a[data-post-id] img { transition: none !important; }",

    /* sticky :hover after a tap is a phone-browser thing; undo the card jump/zoom.
       keyed off our own coarse-pointer class rather than @media (hover: none),
       which phone browsers and emulators report inconsistently */
    "html.bbx-touch a[data-post-id],",
    "html.bbx-touch a[data-post-id]:hover,",
    "html.bbx-touch a[data-post-id]:active,",
    "html.bbx-touch a[data-post-id] img,",
    "html.bbx-touch a[data-post-id]:hover img { transform: none !important; }",

    /* the site's own zoom-on-hover of the picture (group-hover:scale-105 on the img),
       switched off on its own terms: not tied to touch, not tied to the overlay, not tied
       to which grid the card happens to sit in */
    "html." + NS + "-no-zoom ." + NS + "-card img,",
    "html." + NS + "-no-zoom ." + NS + "-card:hover img {",
    "  transform: none !important; transition: none !important;",
    "}",

    /* extra vertical space between cards: row-gap only, so the column widths and the
       site's own column gutter are left alone in every layout */
    "html." + NS + "-gapped ." + NS + "-grid { row-gap: var(--bbx-card-gap, 0px) !important; }",

    /* Phone-only grid override (the site hard-codes 2 columns below 640px). The same card
       markup is drawn on more screens than the gallery: a creator's profile builds its own
       grids for uploads, pinned work and favourites, and there each card sits inside a
       wrapper div of its own (that is where its pin button lives). So nothing below is keyed
       on the id "gallery" — it is keyed on what the script marks: .bbx-grid for any grid
       holding cards, .bbx-card for the card itself, .bbx-item for the grid item (the card on
       the gallery, the site's wrapper on a profile page). */
    "@media (max-width: 640px) {",
    "  html.bbx-cols-2 ." + NS + "-grid { grid-template-columns: repeat(2, minmax(0,1fr)) !important; }",
    /* one column, the card unchanged: picture, then its text below, at full width */
    "  html.bbx-cols-full ." + NS + "-grid { grid-template-columns: minmax(0,1fr) !important; }",
    "  html.bbx-cols-1 ." + NS + "-grid { grid-template-columns: minmax(0,1fr) !important; }",
    /* a 1-column phone list reads like chub: thumbnail left, text right */
    "  html.bbx-cols-1 ." + NS + "-grid ." + NS + "-card { display: grid; grid-template-columns: 40% minmax(0,1fr); grid-template-rows: auto auto auto; align-items: start; }",
    /* not yet decorated: fall back to the card's own shape (artwork first, footer second) */
    "  html.bbx-cols-1 ." + NS + "-grid ." + NS + "-card:not([data-" + NS + "-done]) > div:first-child { grid-column: 1; grid-row: 1 / span 2; align-self: stretch; }",
    "  html.bbx-cols-1 ." + NS + "-grid ." + NS + "-card:not([data-" + NS + "-done]) > div:nth-child(2) { grid-column: 2; }",
    /* decorated: place by our own classes, with or without a title above the art */
    "  html.bbx-cols-1 ." + NS + "-grid ." + NS + "-card > ." + NS + "-art { grid-column: 1; grid-row: 1 / span 3; align-self: stretch; }",
    "  html.bbx-cols-1 ." + NS + "-grid ." + NS + "-card > ." + NS + "-title { grid-column: 2; grid-row: 1; padding-left: 0; }",
    "  html.bbx-cols-1 ." + NS + "-grid ." + NS + "-card > ." + NS + "-info { grid-column: 2; grid-row: 2; border-top: 0; padding-top: 2px; }",
    "  html.bbx-cols-1 ." + NS + "-grid ." + NS + "-card > ." + NS + "-foot { grid-column: 2; grid-row: 3; }",
    /* fill the whole left column with the artwork, like chub's cards: no dead space under the image */
    "  html.bbx-cols-1 ." + NS + "-grid ." + NS + "-card [class*=\"aspect-\"] { aspect-ratio: auto; min-height: 100%; height: 100%; }",
    "  html.bbx-cols-1 ." + NS + "-grid ." + NS + "-card [class*=\"aspect-\"] img { height: 100%; max-height: none; object-fit: cover; }",
    /* the two card-size knobs, live only in the 1-column modes: a narrower card is
       centred in its column, a capped artwork height fixes the card's height too. The cap
       goes on the grid item so it holds whether the site's wrapper or the card is the item. */
    "  html." + NS + "-capped ." + NS + "-grid > ." + NS + "-item {",
    "    max-width: var(--bbx-card-max-w, 100%); justify-self: center;",
    "  }",
    "  html." + NS + "-artcap ." + NS + "-grid ." + NS + "-card > ." + NS + "-art {",
    "    aspect-ratio: auto !important; height: var(--bbx-art-h) !important;",
    "    min-height: 0 !important; max-height: none !important;",
    "  }",
    "  html." + NS + "-artcap ." + NS + "-grid ." + NS + "-card > ." + NS + "-art img {",
    "    height: 100% !important; max-height: none !important;",
    "  }",
    "}",

    /* settings button + panel — our own dark black / graphite / white theme */
    "." + NS + "-gear {",
    "  position: fixed; right: 10px; bottom: calc(10px + env(safe-area-inset-bottom, 0px)); z-index: 2147483000;",
    "  width: 34px; height: 34px; border-radius: 10px; cursor: pointer;",
    "  display: flex; align-items: center; justify-content: center;",
    "  background: linear-gradient(180deg, #1c1e23, #0a0b0d);",
    "  color: #ffffff; border: 1px solid var(--bbx-ui-edge);",
    "  box-shadow: 0 2px 10px rgba(0,0,0,.45);",
    "  font-size: 16px; line-height: 1;",
    "  opacity: var(--bbx-gear-op, 1);",
    "}",
    "." + NS + "-gear:hover { border-color: #5b636f; }",
    "." + NS + "-gear:active { transform: scale(.94); }",
    /* the panel outgrew a phone screen, so it is a sheet now: it scrolls inside its
       own height, the heading stays pinned while it scrolls, and the height is measured
       against dvh plus the safe-area insets so the heading is never under the notch */
    "." + NS + "-panel {",
    "  position: fixed; right: 10px; bottom: calc(10px + env(safe-area-inset-bottom, 0px));",
    "  z-index: 2147483001;",
    "  width: 288px; max-width: calc(100vw - 20px);",
    "  max-height: calc(100vh - 62px - env(safe-area-inset-top, 0px) - env(safe-area-inset-bottom, 0px));",
    "  max-height: calc(100dvh - 62px - env(safe-area-inset-top, 0px) - env(safe-area-inset-bottom, 0px));",
    "  overflow-y: auto; overscroll-behavior: contain; -webkit-overflow-scrolling: touch;",
    "  scrollbar-width: thin; scrollbar-color: #3a4048 transparent;",
    "  border-radius: 12px;",
    "  background: var(--bbx-ui-bg); color: var(--bbx-ui-fg);",
    "  border: 1px solid var(--bbx-ui-line);",
    "  box-shadow: 0 10px 30px rgba(0,0,0,.5);",
    "  font-size: 12.5px; line-height: 1.45; font-family: inherit;",
    "}",
    "." + NS + "-panel::-webkit-scrollbar { width: 8px; }",
    "." + NS + "-panel::-webkit-scrollbar-thumb { background: #343943; border-radius: 4px; }",
    "." + NS + "-panel-head {",
    "  position: sticky; top: 0; z-index: 2;",
    "  display: flex; align-items: center; justify-content: space-between; gap: 8px;",
    "  padding: 10px 10px 8px 14px;",
    "  background: var(--bbx-ui-bg); border-bottom: 1px solid var(--bbx-ui-line);",
    "}",
    "." + NS + "-panel h4 { margin: 0; font-size: 13.5px; font-weight: 700; letter-spacing: .01em; }",
    "." + NS + "-panel-body { padding: 0 14px 14px; }",
    "." + NS + "-panel-close {",
    "  flex: 0 0 auto; width: 30px; height: 30px; min-height: 30px; border-radius: 8px; cursor: pointer;",
    "  border: 1px solid var(--bbx-ui-edge); background: var(--bbx-ui-bg-2); color: var(--bbx-ui-fg);",
    "  font-size: 15px; line-height: 1; font-family: inherit;",
    "}",
    "." + NS + "-panel-close:active { background: #23262c; }",
    /* group headings keep a long panel scannable */
    "." + NS + "-sec {",
    "  margin: 13px 0 4px; padding-top: 9px; border-top: 1px solid var(--bbx-ui-line);",
    "  font-size: 10px; font-weight: 700; letter-spacing: .13em; text-transform: uppercase;",
    "  color: var(--bbx-ui-dim);",
    "}",
    "." + NS + "-sec:first-of-type { margin-top: 10px; }",
    /* rows are 34px tall: a phone thumb, not a mouse cursor */
    "." + NS + "-row { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin: 3px 0; min-height: 34px; padding: 5px 6px; border-radius: 8px; }",
    "." + NS + "-row-check { cursor: pointer; }",
    "." + NS + "-row-check:active { background: var(--bbx-ui-bg-2); }",
    "." + NS + "-row > span { min-width: 0; }",
    "." + NS + "-row select {",
    "  font-size: 12.5px; padding: 6px 6px; min-height: 34px; border-radius: 7px; max-width: 58%;",
    "  background: var(--bbx-ui-bg-2); color: var(--bbx-ui-fg); border: 1px solid var(--bbx-ui-edge);",
    "}",
    "." + NS + "-row input[type=checkbox] { width: 20px; height: 20px; accent-color: #cbd5e1; margin: 0; flex: 0 0 auto; }",
    /* sliders: 26px tall track area, and the current value printed beside it */
    "." + NS + "-row input[type=range] {",
    "  flex: 1 1 auto; min-width: 92px; max-width: 62%; height: 26px; margin: 0;",
    "  accent-color: #cbd5e1; background: transparent; cursor: pointer;",
    "}",
    "." + NS + "-val {",
    "  flex: 0 0 auto; min-width: 46px; text-align: right;",
    "  font-size: 11px; color: var(--bbx-ui-dim); font-variant-numeric: tabular-nums;",
    "}",
    "." + NS + "-hint { margin: 2px 0 0; font-size: 10.5px; color: var(--bbx-ui-dim); }",
    "." + NS + "-ver { margin-top: 12px; font-size: 10.5px; color: var(--bbx-ui-dim); }",
    "." + NS + "-reset {",
    "  display: block; width: 100%; margin-top: 14px; padding: 9px 10px; min-height: 38px;",
    "  border-radius: 9px; border: 1px solid var(--bbx-ui-edge); background: var(--bbx-ui-bg-2);",
    "  color: var(--bbx-ui-fg); font-size: 12.5px; font-family: inherit; cursor: pointer;",
    "}",
    "." + NS + "-reset:active { background: #23262c; }",

    /* the card page's download block: 348px of full-width buttons stacked one per
       line, about a third of a phone screen. Compacted it is one row of short buttons
       — every control is still there, still the site's own, only the labels are short
       and the hint lines are dropped. */
    "html." + NS + "-dl-compact ." + NS + "-dl-block {",
    "  display: flex; flex-wrap: wrap; align-items: center; gap: 5px;",
    "  padding: 6px 7px !important;",
    "}",
    "html." + NS + "-dl-compact ." + NS + "-dl-block > * { margin: 0 !important; }",
    /* the group wrappers (favourite row, tag radio row, import row) stop being boxes
       so their buttons join the same row; the lorebook boxes stay blocks */
    "html." + NS + "-dl-compact ." + NS + "-dl-block > div:not([id$=\"lorebooks-box\"]) { display: contents; }",
    /* the lorebook boxes keep whatever display the site itself chose: they are hidden
       when the card has no lorebooks, and forcing them visible added ~90px of empty
       headings back on a card that has none */
    "html." + NS + "-dl-compact ." + NS + "-dl-block > div[id$=\"lorebooks-box\"] { flex: 1 1 100%; }",
    /* hint lines sit either directly in the block or inside a wrapper that just became
       transparent, so both depths are dropped — except the site's own status line (it
       carries an id) and the headings of a lorebook box that really has lorebooks */
    "html." + NS + "-dl-compact ." + NS + "-dl-block > p:not([id]),",
    "html." + NS + "-dl-compact ." + NS + "-dl-block > div:not([id$=\"lorebooks-box\"]) > p:not([id]) { display: none !important; }",
    "html." + NS + "-dl-compact ." + NS + "-dl-block button {",
    "  width: auto !important; flex: 1 1 auto; min-width: 0;",
    "  padding: 4px 7px !important; min-height: 30px;",
    "  text-align: center; font-size: 0 !important; line-height: 0 !important;",
    "}",
    /* the label comes from ::after so the spans the site updates (favourite count,
       the radio buttons' own text) stay in the DOM untouched */
    "html." + NS + "-dl-compact ." + NS + "-dl-block button::after {",
    "  font-size: 11.5px; line-height: 1.25; font-weight: 700;",
    "}",
    "html." + NS + "-dl-compact [id=favorite-btn]::after,",
    "html." + NS + "-dl-compact [data-" + NS + "-dup-of=favorite-btn]::after { content: 'Fav'; }",
    "html." + NS + "-dl-compact [id=download-png-btn]::after,",
    "html." + NS + "-dl-compact [data-" + NS + "-dup-of=download-png-btn]::after { content: 'PNG'; }",
    "html." + NS + "-dl-compact [id=download-png-still-btn]::after,",
    "html." + NS + "-dl-compact [data-" + NS + "-dup-of=download-png-still-btn]::after { content: 'PNG still'; }",
    "html." + NS + "-dl-compact [id=download-json-btn]::after,",
    "html." + NS + "-dl-compact [data-" + NS + "-dup-of=download-json-btn]::after { content: 'JSON'; }",
    "html." + NS + "-dl-compact [id=download-tag-opt-original]::after,",
    "html." + NS + "-dl-compact [data-" + NS + "-dup-of=download-tag-opt-original]::after { content: 'orig'; }",
    "html." + NS + "-dl-compact [id=download-tag-opt-botbooru]::after,",
    "html." + NS + "-dl-compact [data-" + NS + "-dup-of=download-tag-opt-botbooru]::after { content: 'site'; }",
    "html." + NS + "-dl-compact [id=import-st-btn]::after,",
    "html." + NS + "-dl-compact [data-" + NS + "-dup-of=import-st-btn]::after { content: 'URL'; }",
    /* the copy under the pictures: same card look, no id of its own (see buildDup) */
    "." + NS + "-dl-dup { margin: 0 0 8px; }",

    /* 1.5.0. An artwork that keeps its own ratio, for the one-column modes. It is the
       opposite of the Artwork height cap and the two are mutually exclusive in
       applyClasses. Nothing changes until a picture reports its natural size
       (data-bbx-natural), so a scrolling list never reflows under a finger. */
    "html." + NS + "-art-native ." + NS + "-card ." + NS + "-art[" + "data-" + NS + "-natural] {",
    "  aspect-ratio: auto !important; min-height: 0 !important; height: auto !important; max-height: none; }",
    "html." + NS + "-art-native ." + NS + "-card ." + NS + "-art[" + "data-" + NS + "-natural] img {",
    "  position: static; width: 100%; height: auto; object-fit: contain; }",

    /* One compact bar of facts on a card's own page, above the duplicated buttons: one line of
       facts, not a panel with a control. The per-field breakdown an expander used to open is cut
       out of the layout, and what it said rides on the bar's own title instead. */
    "." + NS + "-dbar { display: flex; flex-wrap: wrap; gap: 4px 12px; align-items: baseline;",
    "  margin: 0 0 8px; padding: 7px 9px; border: 1px solid rgba(148,163,184,.38); border-radius: 8px;",
    "  background: rgba(148,163,184,.14); font-size: 12px; line-height: 1.5; color: #374151; }",
    "html.dark ." + NS + "-dbar { color: #e5e7eb; background: rgba(148,163,184,.10); border-color: rgba(148,163,184,.28); }",
    "." + NS + "-dbar-item { white-space: nowrap; }",
    "." + NS + "-dbar-item b { font-weight: 700; }",

    /* a list card's media button: a full-width strip under the card's stats row, in the shape
       of the card's own "more ▾", plus the one line its single request produced */
    "." + NS + "-read {",
    "  align-self: stretch; text-align: center; cursor: pointer; user-select: none;",
    "  font-size: var(--bbx-fs-sm); font-weight: 700; color: var(--bbx-fg-dim);",
    "  background: var(--bbx-btn-bg); border: 1px solid rgba(148,163,184,.3); border-radius: 6px;",
    "  padding: 4px 8px; min-height: 28px;   /* a comfortable phone tap target */",
    "}",
    "." + NS + "-read:active { opacity: .6; }",
    "." + NS + "-read-busy { opacity: .55; }",
    "." + NS + "-read-open { color: var(--bbx-fg); font-weight: 800; }",
    "." + NS + "-read-out {",
    "  margin: 4px 0 0; font-size: var(--bbx-fs-sm); line-height: 1.45; color: var(--bbx-fg-dim);",
    "  overflow-wrap: break-word;",
    "}",

    /* the settings that are rarely touched are not in the sheet until you ask for them */
    "." + NS + "-expander {",
    "  align-self: stretch; text-align: left; cursor: pointer; user-select: none;",
    "  border: 1px dashed rgba(148,163,184,.55); border-radius: 6px; background: transparent;",
    "  color: inherit; font-size: var(--bbx-fs-sm); font-weight: 700; padding: 5px 8px; min-height: 28px;",
    "}",
    "." + NS + "-extra { display: flex; flex-direction: column; gap: 6px; padding: 6px 0 2px; }",

    /* duplicated controls keep the site's own classes; they only need their own spacing and
       a hairline, so a copy reads as a copy and not as the control it was cloned from */
    "." + NS + "-pager-dup { margin: 0 0 10px; padding: 6px 8px; border: 1px solid rgba(148,163,184,.3); border-radius: 8px; }",
    "." + NS + "-search-dup { margin: 0 0 10px; padding: 6px 8px; border: 1px solid rgba(148,163,184,.3); border-radius: 8px; }",
    "." + NS + "-chip { white-space: nowrap; display: inline-flex; align-items: center; gap: 4px; }",
    "." + NS + "-chip svg { width: 15px; height: 15px; display: block; flex: 0 0 auto; }",
    /* one row, whatever the header holds: the mod's own chips step out before any of the
       site's buttons are ever clipped (see keepOneRow) */
    /* the header squeezed by its own spacing, before anything is taken away */
    "." + NS + "-tight { gap: 3px; }",
    "." + NS + "-tight > * { padding-left: 5px; padding-right: 5px; font-size: 10.5px; }",
    "." + NS + "-one-row { flex-wrap: nowrap; overflow: hidden; }",
    "." + NS + "-one-row > * { flex: 0 0 auto; }",
    /* 1.7.0. A folded group is a folded group: the sheet's folded blocks are flex containers,
       and an element whose own rule says display:flex does not obey the hidden attribute at
       all — the hidden write landed, the box kept rendering, and every "fold" button in the
       sheet only ever expanded. The attribute is now backed by a rule that beats the display
       rule instead of competing with it. */
    "." + NS + "-extra[hidden],",
    "." + NS + "-read-out[hidden],",
    "." + NS + "-panel-body [hidden] { display: none !important; }",

    /* the sheet is three tabs now: the title row and the tab row stick together while the
       settings under them scroll, so the way between groups is always in reach */
    "." + NS + "-panel-top {",
    "  position: sticky; top: 0; z-index: 2;",
    "  background: var(--bbx-ui-bg); border-bottom: 1px solid var(--bbx-ui-line);",
    "}",
    "." + NS + "-tabs { display: flex; gap: 4px; padding: 0 10px 10px 14px; }",
    "." + NS + "-tab {",
    "  flex: 1 1 0; min-width: 0; min-height: 34px; padding: 6px 4px; border-radius: 8px; cursor: pointer;",
    "  border: 1px solid var(--bbx-ui-edge); background: var(--bbx-ui-bg-2); color: var(--bbx-ui-dim);",
    "  font-size: 12px; font-weight: 700; line-height: 1.2; font-family: inherit;",
    "}",
    "." + NS + "-tab:active { background: #23262c; }",
    "." + NS + "-tab[aria-selected=true] { background: #2b313a; color: var(--bbx-ui-fg); border-color: #5b636f; }",
    "." + NS + "-tab-hint { margin: 10px 0 0; font-size: 10.5px; color: var(--bbx-ui-dim); }",

    /* a group you have to open is a row of its own: full width, the same hairline a group
       heading has, and the same shape in every tab — a ▸ that is as wide as the label it
       hides reads as a control, a pill the width of its word does not */
    "." + NS + "-expander { display: block; width: 100%; text-align: left; }",
    "." + NS + "-expander[aria-expanded=true] { border-style: solid; border-color: rgba(148,163,184,.4); }",

    /* the uploader's chip: the site's writer-orange text over the copyright tag's magenta
       frame (rgb(244 114 182) is the site's pink-400 border tone). It is a link, so it is
       middle-clickable like every other chip. */
    "." + NS + "-uploader {",
    "  display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;",
    "  padding: 2px 7px; border-radius: 6px; border: 1px solid; cursor: pointer;",
    "  font-size: 11.5px; line-height: 1.35; font-weight: 700;",
    "  color: #9a3412; background: rgba(244,114,182,.14); border-color: rgba(244,114,182,.9);",
    "}",
    ".dark " + "." + NS + "-uploader { color: #fdba74; background: rgba(244,114,182,.12); border-color: rgba(244,114,182,.75); }",
    "." + NS + "-dbar " + "." + NS + "-uploader, ." + NS + "-uploader-row { margin: 0; }",

    /* 1.7.0: a card's own page shows the picture at its own height. The site frames the main
       image in a box capped at 85vh and clamps its ratio to 0.5–2, so a tall portrait is
       cropped with no switch to ask for the whole thing. The frame is marked (bbx-page-art-frame)
       and the cap is dropped: no max-height, the site's own aspect lock released, and the
       image contained rather than covered. Videos are left framed — a cap is what keeps a
       video page usable. */
    "." + NS + "-page-art-frame {",
    "  max-height: none !important; aspect-ratio: auto !important; overflow: visible !important;",
    "}",
    "." + NS + "-page-art-frame > img {",
    "  max-height: none !important; height: auto !important; object-fit: contain !important;",
    "}",

    /* the bar of facts reads as a sentence, not as a row of pills: the facts are separated by a
       middot the way the reader would dictate them, and each one carries what it means on its
       tooltip */
    "." + NS + "-dbar-text { display: block; font-size: var(--bbx-fs); font-weight: 700; color: var(--bbx-fg); line-height: 1.5; }",
    "." + NS + "-dbar-fact { display: inline; }",

    /* the header squeezed by the mod's own compaction: tighter gaps and padding, no label */
    "." + NS + "-cluster-compact { gap: 3px !important; }",
    "." + NS + "-cluster-compact > * { padding-left: 6px; padding-right: 6px; }",

  ].join("\n");

  /* ─────────── shared: what a card actually carries ───────────
     A card is stored whole: description, personality, scenario, first message, example
     dialogue, creator notes, the prompt fields, the greeting array. Media lives inside that
     text — links, <img>/<video>/<audio> tags, inline style attributes, CSS backgrounds —
     and botbooru's own renderer strips most of it here (other services render it). Every
     number below therefore counts what the CARD'S TEXT contains; it is never a claim about
     what this page is showing. */

  var CARD_TEXT_FIELDS = [
    ["creator_notes", "notes"],
    ["description", "description"],
    ["personality", "personality"],
    ["scenario", "scenario"],
    ["first_mes", "first message"],
    ["alternate_greetings", "greetings"],
    ["mes_example", "example dialogue"],
    ["system_prompt", "system prompt"],
    ["post_history_instructions", "history instructions"],
    ["depth_prompt", "depth prompt"],
    ["uploader_notes", "uploader notes"],
  ];

  /* Measured from the live shell: the class string the header buttons themselves carry. A
     control the mod adds uses it, so it belongs to the header instead of looking glued on. */
  var SITE_BTN = "px-1.5 py-1.5 rounded-md border border-gray-300 dark:border-gray-700 " +
    "text-xs font-semibold text-gray-800 dark:text-gray-200 bg-gray-100 dark:bg-botdark " +
    "hover:bg-gray-200 dark:hover:bg-gray-800 transition-all duration-200 ease-in-out active:scale-95";

  var IMG_RE = /\.(png|jpe?g|gif|webp|avif|apng|bmp|svg)(\?|#|$)/i;
  var VID_RE = /\.(mp4|webm|mov|mkv|avi|ogv)(\?|#|$)/i;
  var AUD_RE = /\.(mp3|ogg|oga|wav|m4a|flac|aac)(\?|#|$)/i;
  var VID_HOST_RE = /(youtube\.com|youtu\.be|vimeo\.com|streamable\.com|dailymotion|bitchute|odysee\.com|media\.tenor)/i;
  var URL_RE = /https?:\/\/[^\s<>"')]+/g;

  function textOf(post, key) {
    var v = post ? post[key] : null;
    if (v && typeof v === "object" && typeof v.content === "string") v = v.content;
    if (Array.isArray(v)) return v.map(function (x) { return x == null ? "" : String(x); }).join("\n\n");
    return v == null ? "" : String(v);
  }

  function mediaKind(u) {
    if (IMG_RE.test(u)) return "image";
    if (VID_RE.test(u) || VID_HOST_RE.test(u)) return "video";
    if (AUD_RE.test(u)) return "audio";
    return "link";
  }

  function linkCore(u) { return u.split("#")[0].split("?")[0]; }

  /* mediaOf(post): how many media elements the card holds and WHERE they are.
     fields  — per text field: links, media, image, video, audio (occurrences)
     kinds   — the same summed over every field
     markup  — tags and CSS the text itself carries (the viewer here may hide them)
     unique  — distinct link targets, query and fragment ignored */
  /* mediaOf(post): how many media elements the card holds and WHERE they are.
     fields  — per text field: links, media, image, video, audio (occurrences), plus the same
               links counted once each (uniqueLinks / uniqueMedia) and the markup the field carries
     kinds   — the same summed over every field
     markup  — tags and CSS the text itself carries (the viewer here may hide them)
     unique  — distinct link targets, query and fragment ignored
     uniqueLinks / uniqueMedia — the same over the whole card, and this is what the bars say:
               unique media over unique links, source links excluded from both
     greetIntros / greetMedia  — the greetings as a group: how many there are, how much media they
               hold between them (a link repeated in two greetings is one link)
     notesMedia / notesMarkup  — the creator's own notes, counted on their own
     sauce   — the card's provenance links, held aside rather than counted as the creator's media */
  function mediaOf(post) {
    var out = {
      fields: {}, kinds: { image: 0, video: 0, audio: 0, link: 0 },
      markup: { img: 0, embed: 0, audioTag: 0, styleBlock: 0, inlineStyle: 0, cssBackground: 0 },
      links: 0, media: 0, fieldsWithMedia: 0, unique: {}, uniqueCount: 0,
      sauce: {}, uniqueLinks: 0, uniqueMedia: 0,
      greetMedia: 0, notesMedia: 0, notesMarkup: 0, notesMarkupKinds: {},
    };
    if (!post) return out;

    var sauceCores = out.sauce;
    ["sauce", "imported_sauce", "image_link"].forEach(function (k) {
      var v = post[k];
      if (typeof v === "string" && v.trim()) sauceCores[linkCore(v.trim())] = 1;
      else if (Array.isArray(v)) v.forEach(function (one) { if (typeof one === "string" && one.trim()) sauceCores[linkCore(one.trim())] = 1; });
    });

    var allLinks = {};
    var greetLinks = {};
    var notesLinks = {};

    /* One field's links, counted twice over: how many times each kind appears (a link posted
       three times is three occurrences) and which targets appear at all (a link posted three
       times is one target). Both answers are wanted, by different lines of the UI. */
    /* Counts occurrences: a link posted three times is three occurrences and one target.
       intoTotals=false harvests for one pool only (the greetings) without inflating what the
       whole-card occurrence counts say — those are a fact about the card's named text fields. */
    function harvest(text, intoTotals) {
      var found = text.match(URL_RE) || [];
      var c = { links: 0, media: 0, image: 0, video: 0, audio: 0, uniqueLinks: 0, uniqueMedia: 0 };
      var map = {};
      found.forEach(function (u) {
        u = u.replace(/[.,;:]+$/, "");
        var k = mediaKind(u);
        c.links++;
        map[linkCore(u)] = k;
        if (intoTotals === false) return;
        out.kinds[k]++;
        if (k !== "link") { c.media++; out.media++; }
        out.unique[linkCore(u)] = k;
      });
      c.map = map;
      return c;
    }
    function merge(target, map) {
      Object.keys(map).forEach(function (k) { target[k] = map[k]; });
    }

    function markupOf(text) {
      return {
        img: (text.match(/<img[\s>]/gi) || []).length,
        embed: (text.match(/<(video|iframe|embed)[\s>]/gi) || []).length,
        audioTag: (text.match(/<audio[\s>]/gi) || []).length,
        styleBlock: (text.match(/<style[\s>]/gi) || []).length,
        inlineStyle: (text.match(/[\s"']style\s*=/gi) || []).length,
        cssBackground: (text.match(/background(-image)?\s*:[^;}]{0,140}url\(/gi) || []).length,
      };
    }

    CARD_TEXT_FIELDS.forEach(function (entry) {
      var text = textOf(post, entry[0]);
      if (!text) return;
      var c = harvest(text, true);
      c.label = entry[1];
      out.links += c.links;
      if (c.media) out.fieldsWithMedia++;
      var mk = markupOf(text);
      out.markup.img += mk.img; out.markup.embed += mk.embed; out.markup.audioTag += mk.audioTag;
      out.markup.styleBlock += mk.styleBlock; out.markup.inlineStyle += mk.inlineStyle; out.markup.cssBackground += mk.cssBackground;
      /* merged into each pool this field belongs to: every named text field feeds the whole card,
         the first message feeds the greetings as well, the creator notes feed their own pool. A
         field that is not in a pool is never counted in it, whatever order the site lists them in. */
      merge(allLinks, c.map);
      if (entry[0] === "first_mes") merge(greetLinks, c.map);
      if (entry[0] === "creator_notes") {
        merge(notesLinks, c.map);
        out.notesMarkup = mk.img + mk.embed + mk.audioTag + mk.styleBlock + mk.inlineStyle + mk.cssBackground;
        out.notesMarkupKinds = mk;
      }
      var uniq = { links: 0, media: 0 };
      Object.keys(c.map).forEach(function (core) {
        if (sauceCores[core]) return;
        uniq.links++;
        if (c.map[core] !== "link") uniq.media++;
      });
      c.uniqueLinks = uniq.links;
      c.uniqueMedia = uniq.media;
      delete c.map;
      out.fields[entry[0]] = c;
    });

    /* The greetings are a group, and alternate_greetings is not one of the card's named text
       fields: it is a list. Counted here, on the same rules, so "how many intros this card has,
       and how much media they hold between them" is a fact about the greetings rather than a
       guess from whichever fields the site happens to name. */
    if (Array.isArray(post.alternate_greetings)) {
      post.alternate_greetings.forEach(function (g) {
        var text = g == null ? "" : String(g);
        if (!text.trim()) return;
        merge(greetLinks, harvest(text, false).map);
      });
    }

    var counts = { all: { media: 0, links: 0 }, greet: { media: 0 }, notes: { media: 0 } };
    Object.keys(allLinks).forEach(function (core) {
      if (sauceCores[core]) return;
      counts.all.links++;
      if (allLinks[core] !== "link") counts.all.media++;
    });
    Object.keys(greetLinks).forEach(function (core) {
      if (sauceCores[core]) return;
      if (greetLinks[core] !== "link") counts.greet.media++;
    });
    Object.keys(notesLinks).forEach(function (core) {
      if (sauceCores[core]) return;
      if (notesLinks[core] !== "link") counts.notes.media++;
    });

    out.uniqueCount = Object.keys(out.unique).length;
    out.uniqueLinks = counts.all.links;
    out.uniqueMedia = counts.all.media;
    out.greetMedia = counts.greet.media;
    out.notesMedia = counts.notes.media;
    return out;
  }

  function introWord(n) { return n === 1 ? LABELS.introOne : LABELS.introMany; }
  function lorebookWord(n) { return n === 1 ? LABELS.lorebookOne : LABELS.lorebookMany; }
  function bigNumber(n) {
    var s = String(Math.round(n));
    return s.replace(/\B(?=(\d{3})+(?!\d))/g, "\u00A0");   /* 12 400 tokens, grouped the way the site groups them */
  }

  /* How big a linked lorebook is, in tokens, from whatever the loaded card already carries.
     The site names the field token_estimate on a lorebook it renders; an older payload calls it
     something else, so the known names are tried in order and a lorebook whose size the page
     was never told stays uncounted rather than being invented. */
  function lorebookTokens(lb) {
    if (!lb || typeof lb !== "object") return 0;
    var names = ["token_estimate", "total_tokens", "token_count", "tokens", "est_tokens"];
    for (var i = 0; i < names.length; i++) {
      var v = lb[names[i]];
      if (typeof v === "number" && isFinite(v) && v > 0) return v;
      if (typeof v === "string") { var n = parseInt(v.replace(/[^0-9]/g, ""), 10); if (!isNaN(n) && n > 0) return n; }
    }
    return 0;
  }

  function lorebookStats(post) {
    var out = { count: 0, tokens: 0, measured: false };
    if (!post) return out;
    var seen = {};
    ["linked_lorebooks", "companion_lorebooks"].forEach(function (key) {
      var arr = post[key];
      if (!Array.isArray(arr)) return;
      arr.forEach(function (lb) {
        if (!lb) return;
        var id = (lb && (lb.id !== undefined && lb.id !== null)) ? String(lb.id) : "anon-" + out.count;
        if (seen[id]) return;
        seen[id] = 1;
        out.count++;
        var t = lorebookTokens(lb);
        if (t) { out.tokens += t; out.measured = true; }
      });
    });
    /* The card's own lorebook is only added when this page already knows how big it is: guessing
       a size from a presence flag is exactly the kind of number this bar is not allowed to make up. */
    if (!out.measured && post.lorebook_json && typeof post.lorebook_json === "object") {
      var own = lorebookTokens(post.lorebook_json);
      if (own) { out.tokens += own; out.measured = true; }
    }
    return out;
  }

  /* The bar on a card's own page: what the greetings are, what the card points at, and what the
     creator wrote into their own notes. Each statement is only made when the card supports it, in
     the shape the card supports — a parenthetical that would say zero is left unwritten.

     The notes sentence is built out of what was found, not out of one fixed wording: notes that
     carry markup say so, notes that also carry media say how much, and notes that carry media and
     no markup say that instead. */
  function notesSentence(m) {
    var markup = m.notesMarkup > 0;
    var media = m.notesMedia > 0;
    if (!markup && !media) return null;
    if (markup && media) return LABELS.notesSubject + " " + LABELS.notesMarkup + " " + LABELS.notesMedia(m.notesMedia);
    if (markup) return LABELS.notesSubject + " " + LABELS.notesMarkup;
    return LABELS.notesSubject + " " + LABELS.notesMedia(m.notesMedia);
  }


  function greetingCount(post) {
    if (!post) return 0;
    var n = textOf(post, "first_mes").trim() ? 1 : 0;
    var alts = post.alternate_greetings;
    if (Array.isArray(alts)) alts.forEach(function (g) { if (g && String(g).trim()) n++; });
    return n;
  }

  function miniGalleryCount(post) {
    var mg = post && post.mini_gallery;
    if (!mg) return 0;
    if (Array.isArray(mg.images)) return mg.images.length;
    if (typeof mg.approved_count === "number") return mg.approved_count;
    return 0;
  }

  function sauceCount(post) {
    if (!post) return 0;
    var n = 0;
    /* origin names the service a card came from ("chub"): it is not a source link, so it is
       not counted as one. */
    ["sauce", "imported_sauce", "image_link"].forEach(function (k) {
      var v = post[k];
      if (typeof v === "string" && v.trim()) n++;
      else if (Array.isArray(v)) n += v.length;
    });
    return n;
  }

  /* ─────────── shared: a duplicate of a site control ───────────
     The site wires its controls by id and an id exists once per document, so every copy
     the mod makes is built the same way: clone, strip the copy's ids (remembering each as
     data-bbx-dup-of), forward the copy's events to the original captured at build time, and
     mirror the original's state back into the copy only where the two differ. The observer
     watches the ORIGINAL's subtree and never the copy — a copy that feeds its own observer
     is the loop that froze a test harness once. Key events are built in the copy's realm. */

  function keyEventFor(node, init) {
    var view = node.ownerDocument && node.ownerDocument.defaultView;
    var Ctor = (view && view.KeyboardEvent) || (typeof KeyboardEvent === "function" ? KeyboardEvent : null);
    if (!Ctor) return null;
    try { return new Ctor("keydown", init); } catch (e) { return null; }
  }

  function makeDup(src, opts) {
    if (!src || !src.cloneNode) return null;
    var originals = {};
    [].slice.call(src.querySelectorAll("[id]")).forEach(function (n) { originals[n.id] = n; });
    var copy = src.cloneNode(true);
    if (copy.id) copy.removeAttribute("id");
    copy.setAttribute("data-" + NS + "-dup", "1");
    if (opts && opts.cls) copy.classList.add(opts.cls);
    [].slice.call(copy.querySelectorAll("[id]")).forEach(function (n) {
      n.setAttribute("data-" + NS + "-dup-of", n.id);
      n.removeAttribute("id");
    });
    if (copy.querySelectorAll) stripInline(copy);
    if (opts && opts.skip) opts.skip.forEach(function (id) {
      var n = copy.querySelector("[" + "data-" + NS + "-dup-of=\"" + id + "\"]");
      if (n && n.parentNode) n.parentNode.removeChild(n);
    });
    wireDup(copy, originals);
    return { copy: copy, originals: originals };
  }

  /* The site's buttons carry their handlers inline — Cloudflare rewrites them into onclick
     attributes — and a clone brings them along. Left in, one tap would answer twice: once from
     the copy's own attribute, once through the forwarding below. So a copy never keeps an
     inline handler: it answers only by clicking the original it was captured from. */
  function stripInline(root) {
    var all = [];
    if (root.querySelectorAll) all = [].slice.call(root.querySelectorAll("*"));
    all.push(root);
    all.forEach(function (n) {
      if (!n.attributes) return;
      [].slice.call(n.attributes).forEach(function (a) {
        if (/^on/i.test(a.name)) n.removeAttribute(a.name);
      });
    });
  }

  function wireOne(copy, src) {
    if (copy.tagName === "INPUT" || copy.tagName === "TEXTAREA" || copy.tagName === "SELECT") {
      var push = function () { if (src.value !== copy.value) src.value = copy.value; };
      copy.addEventListener("input", function () {
        push();
        /* The site builds its list of suggestions from this very event. Without it the copy is
           a text box with no autocomplete — the one thing the original had that a clone lost. */
        try { src.dispatchEvent(new Event("input", { bubbles: true })); } catch (e) { /* older engines */ }
        if (copy.getAttribute("data-" + NS + "-dup-of") === "search") placeSearchPanels();
      });
      copy.addEventListener("change", push);
      copy.addEventListener("focus", function () { placeSearchPanels(); });
      copy.addEventListener("click", function () { placeSearchPanels(); });
      copy.addEventListener("keydown", function (e) {
        /* The site wires its own box for Enter and for the arrow keys of its suggestion list.
           Only those keys are forwarded, and only after the text typed here has been handed to
           the original, so the site reads what the viewer actually wrote.

           Nothing else is prevented: a copy that preventDefaults every keydown blocks the very
           keystrokes that make a text box a text box, and a copy of a search box you cannot
           type into is the complaint this fixes. The site's handlers do their own preventing on
           the event this forwards, which is where preventing belongs. */
        var ac = null;
        try { ac = pageWin()._searchAutocomplete || null; } catch (err) { ac = null; }
        var isArrows = e.key === "ArrowDown" || e.key === "ArrowUp" || e.key === "Escape";
        var forwardsEnter = e.key === "Enter";
        var forwardsArrows = isArrows && !!(ac && typeof ac.isOpen === "function" && ac.isOpen());
        if (!forwardsEnter && !forwardsArrows) return;
        push();
        var ev = keyEventFor(src, { key: e.key, code: e.code, keyCode: e.keyCode, bubbles: true, cancelable: true });
        if (!ev) return;
        e.preventDefault();
        src.dispatchEvent(ev);
      });
      return;
    }
    copy.addEventListener("click", function (e) {
      e.preventDefault();
      e.stopPropagation();
      src.click();
      /* a copy of a control the site anchors somewhere on the page has to put what that control
         opens where the copy is, not where the original lives */
      if (copy.getAttribute("data-" + NS + "-dup-of") === "advanced-search-toggle") setTimeout(placeSearchPanels, 0);
    });
  }


  function wireDup(copy, originals) {
    [].slice.call(copy.querySelectorAll("[" + "data-" + NS + "-dup-of]")).forEach(function (n) {
      var src = originals[n.getAttribute("data-" + NS + "-dup-of")];
      if (!src) return;
      wireOne(n, src);
    });
  }

  /* One control, duplicated on its own (the search box: an input and a toggle, not a whole
     drawer's worth of markup). */
  function dupOne(src, cls) {
    if (!src || !src.cloneNode) return null;
    var id = src.getAttribute && src.getAttribute("id");
    var copy = src.cloneNode(true);
    if (copy.id) copy.removeAttribute("id");
    copy.setAttribute("data-" + NS + "-dup", "1");
    if (id) copy.setAttribute("data-" + NS + "-dup-of", id);
    if (cls) copy.classList.add(cls);
    stripInline(copy);
    /* nested ids go too: the site's controls are one per page, and a second
       #advanced-search-caret inside a copy is a page the site itself cannot address */
    [].slice.call(copy.querySelectorAll("[" + "id" + "]")).forEach(function (n) {
      n.setAttribute("data-" + NS + "-dup-of", n.id);
      n.removeAttribute("id");
    });
    if (id) wireOne(copy, src);
    return copy;
  }

  function mirrorDup(src, copy, opts) {
    if (!src || !copy || !copy.parentNode) return 0;
    var textIds = (opts && opts.textIds) || [];
    var classes = !!(opts && opts.classes);
    var wrote = 0;
    [].slice.call(src.querySelectorAll("[id]")).forEach(function (n) {
      var c = copy.querySelector("[" + "data-" + NS + "-dup-of=\"" + n.id + "\"]");
      if (!c) return;
      if (typeof n.disabled === "boolean" && n.disabled !== c.disabled) { c.disabled = n.disabled; wrote++; }
      if (n.hasAttribute("aria-checked") && c.getAttribute("aria-checked") !== n.getAttribute("aria-checked")) {
        c.setAttribute("aria-checked", n.getAttribute("aria-checked")); wrote++;
      }
      if (classes && n.className !== c.className) { c.className = n.className; wrote++; }
      if (textIds.indexOf(n.id) !== -1 && c.textContent !== n.textContent) { c.textContent = n.textContent; wrote++; }
      if (n.tagName === "INPUT" && c.tagName === "INPUT") {
        if (typeof n.max === "string" && c.max !== n.max) { c.max = n.max; wrote++; }
        if (typeof n.value === "string" && c.value !== n.value) { c.value = n.value; wrote++; }
      }
    });
    return wrote;
  }

  var dupTimers = {};
  function watchDup(id, src, copy, opts) {
    if (!window.MutationObserver) return null;
    var mo = new MutationObserver(function () {
      if (dupTimers[id]) return;                 /* one mirror pass per batch of changes */
      dupTimers[id] = setTimeout(function () {
        dupTimers[id] = null;
        mirrorDup(src, copy, opts);
      }, 16);
    });
    try {
      mo.observe(src, {
        childList: true, subtree: true, characterData: true,
        attributes: true, attributeFilter: ["disabled", "aria-checked", "class", "max", "value"]
      });
    } catch (e) { /* an engine without an observer: the copy simply stays as cloned */ }
    return mo;
  }

  /* ───────────────────────── tiny helpers ───────────────────────── */

  function el(tag, cls, text) {
    var n = document.createElement(tag);
    if (cls) n.className = cls;
    if (text != null) n.textContent = text;
    return n;
  }

  function svgIcon(pathD, filled) {
    var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
    svg.setAttribute("viewBox", "0 0 24 24");
    svg.setAttribute("aria-hidden", "true");
    svg.setAttribute("fill", filled ? "currentColor" : "none");
    if (!filled) svg.setAttribute("stroke", "currentColor");
    svg.setAttribute("stroke-width", "2");
    svg.setAttribute("stroke-linecap", "round");
    svg.setAttribute("stroke-linejoin", "round");
    var p = document.createElementNS("http://www.w3.org/2000/svg", "path");
    p.setAttribute("d", pathD);
    svg.appendChild(p);
    if (!filled) {
      var c = document.createElementNS("http://www.w3.org/2000/svg", "circle");
      c.setAttribute("cx", "12"); c.setAttribute("cy", "12"); c.setAttribute("r", "3");
      svg.appendChild(c);
    }
    return svg;
  }

  var ICONS = {
    tokens: { d: "M4 9h16M4 15h16M10 3 8 21M16 3l-2 18", filled: false, noCircle: true },
    downloads: { d: "M12 3v12m0 0 4-4m-4 4-4-4M4 21h16", filled: false, noCircle: true },
    favorites: { d: "M12 21s-7-4.35-9.5-8.5C.5 8.5 3 5 6.5 5c2 0 3.5 1 5.5 3 2-2 3.5-3 5.5-3C21 5 23.5 8.5 21.5 12.5 19 16.65 12 21 12 21z", filled: true },
    comments: { d: "M21 15a2 2 0 0 1-2 2H8l-5 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z", filled: false, noCircle: true },
    views: { d: "M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12z", filled: false },
    lock: { d: "M8 10V7a4 4 0 0 1 8 0v3M4 10h16a1 1 0 0 1 1 1v8a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1v-8a1 1 0 0 1 1-1z", filled: false, noCircle: true },
  };

  function icon(name) {
    var spec = ICONS[name];
    var node = svgIcon(spec.d, !!spec.filled);
    if (spec.noCircle) {
      var circle = node.querySelector("circle");
      if (circle) node.removeChild(circle);
    }
    return node;
  }

  /* Site chip class → category key (see _galleryHoverTagChipClasses in the site's ui.js). */
  var CHIP_CAT = [
    ["border-red-400/35", "artist"],
    ["border-orange-400/35", "writer"],
    ["border-green-400/35", "character"],
    ["border-emerald-400/35", "scenarios"],
    ["border-pink-400/35", "copyright"],
    ["border-purple-400/35", "meta"],
    ["border-slate-300/45", "auto"],
    ["border-amber-400/35", "settings"],
    ["border-lime-400/35", "activities"],
    ["border-stone-400/35", "nsfl"],
    ["border-teal-400/35", "language"],
    ["border-blue-400/35", "general"],
  ];

  function chipCategory(span) {
    var cls = span.className || "";
    for (var i = 0; i < CHIP_CAT.length; i++) {
      if (cls.indexOf(CHIP_CAT[i][0]) !== -1) return CHIP_CAT[i][1];
    }
    return "general";
  }

  function tagHref(name, cat) {
    try {
      var w = pageWin();
      if (typeof w._searchTParamForTag === "function") {
        return "/search?t=" + encodeURIComponent(w._searchTParamForTag(name, cat));
      }
    } catch (e) { /* site helper not loaded yet */ }
    return "/search?t=" + encodeURIComponent(name);
  }

  /* ───────────────────────── build one card's info block ───────────────────────── */

  var CLAMP_CLASSES = { 2: 1, 3: 1, 4: 1, 6: 1, 8: 1 };
  var CAP_STEPS = [2, 3, 4, 6, 8];

  /* Snap a requested number of lines to the ladder the stylesheet actually defines. A stored
     5 produced "bbx-clamp-5", which matches no rule at all — the text rendered whole while the
     setting promised three lines. */
  function nearestCap(n, fallback) {
    var fb = parseInt(fallback, 10);
    var best = CLAMP_CLASSES[fb] ? fb : 3;
    n = parseInt(n, 10);
    if (isNaN(n)) return best;
    for (var i = 0; i < CAP_STEPS.length; i++) {
      if (Math.abs(CAP_STEPS[i] - n) < Math.abs(best - n)) best = CAP_STEPS[i];
    }
    return best;
  }

  /* "2" | 3 | "full" … → a clamp class, or "" for "show it all".
     The chosen number is honoured everywhere, including the small cards on profile
     grids: the site trims its own peeks (line-clamp-2 there), but a setting that
     quietly rendered fewer lines than it promised was worse than a slightly
     generous card. */
  function clampClass(lines, fallback) {
    var n = lines === "full" ? "full" : parseInt(lines, 10);
    if (n === "full") return "";
    if (!CLAMP_CLASSES[n]) n = nearestCap(n, fallback);
    return NS + "-clamp " + NS + "-clamp-" + n;
  }

  function textBlock(source, cls, label) {
    var p = el("p", NS + "-text " + cls);
    // The site already escaped + sanitised this fragment (inline markdown only),
    // so cloning the parsed nodes keeps the bold/italic/code without new markup.
    var inner = source.querySelector("p") || source;
    var kids = inner.childNodes;
    for (var i = 0; i < kids.length; i++) p.appendChild(kids[i].cloneNode(true));
    if (label) {
      var wrap = el("div", NS + "-notes-wrap");
      wrap.appendChild(el("span", NS + "-notes-label", label));
      wrap.appendChild(p);
      return { wrap: wrap, p: p };
    }
    return { wrap: p, p: p };
  }

  /* ─── the order of a card's chips, and who wrote the card ───
     A chip's category is already knowable: the site colours a chip by its category, and
     CHIP_CAT above is the map from that colour back to the category name. Knowing it is what
     lets the writer chip LEAD the row — the way the site's own tag sections lead with Writer —
     instead of landing wherever the card's raw tag list happened to put it. Everything else
     keeps the order the card listed it in; Auto keeps the last seat, for the site's own reason
     (it is bookkeeping, not a tag someone chose). */
  function catRank(cat) {
    var c = String(cat || "").toLowerCase();
    return Object.prototype.hasOwnProperty.call(CATEGORY_RANK, c) ? CATEGORY_RANK[c] : UNKNOWN_CATEGORY_RANK;
  }

  function rankChips(list) {
    return list.map(function (item, i) { return { item: item, i: i, rank: catRank(item.cat) }; })
      .sort(function (a, b) { return a.rank - b.rank || a.i - b.i; })
      .map(function (x) { return x.item; });
  }

  /* The uploader, where the page states it without being asked.
     On a card's own page the site names the uploader and links their profile (#post-uploader,
     a real href). On a profile page the site puts the owner's name in the tab title it manages.
     In the card list the payload carries an uploader id and no name — and a name built out of an
     id is not a username, so nothing is claimed there. */
  function uploaderFromCardPage() {
    var n = document.getElementById("post-uploader");
    if (!n) return null;
    var name = String(n.textContent || "").trim();
    var href = n.getAttribute("href") || "";
    if (!name || !href || href === "#") return null;
    return { name: name, href: href };
  }

  function profileOwner() {
    var m = /^\/profile\/(\d+)/.exec(String(window.location.pathname || ""));
    if (!m) return null;
    var id = m[1];
    var title = /^Botbooru\s+-\s+(.+)$/.exec(String(document.title || "").trim());
    var name = title ? title[1].trim() : "";
    /* the site reuses the tab title for its own views; a title that reads like a view name is not
       somebody's username */
    if (!name || /^(Loading|Profile|Character|Search|Log ?in|Settings|Upload|Staff|Lorebook|Bot Studio|Forum|Wiki)/i.test(name)) name = "";
    var cached = uploaderName(id);   /* the profile's own payload, when the page already answered */
    if (cached) name = cached;
    return { name: name, href: "/profile/" + id, id: id, named: !!name };
  }

  /* ─────────── who uploaded a card, learned from answers the page already gets ───────────
     The list hands a card an uploader id and no name, and a name built out of an id is not a
     username — so the mod builds none. It remembers uploaders from three honest sources: the card
     payload the mod already fetches when a reader taps that card's media button (it states
     uploader_id and uploader_name); the answers the site asks for anyway on a listing page (its
     own /posts/ response, and a profile's /api/users/<id> response, which lists that user's own
     uploads) read by watching the page's fetch rather than sending a second copy of it; and one
     small request per uploader id that has no name yet. Names are deduped, cached across visits,
     and capped per batch, so a page of thirty cards does not cost thirty requests. A card whose
     uploader was never stated by any of those shows no uploader line at all: no certainty, no
     block. */

  var UPLOADER_CACHE_KEY = "botbooru_mod_uploaders_v1";
  var UPLOADER_LOOKUP_CAP = 8;    /* names to ask for per batch of cards */
  var UPLOADER_CACHE_MAX = 400;   /* usernames to keep; the oldest go first */

  var uploaderNames = {};         /* uploader id -> username (persisted) */
  var uploaderIds = {};           /* post id -> uploader id (this visit) */
  var uploaderAsked = {};         /* uploader id -> already asked about */
  var uploaderQueue = [];
  var uploaderWaiting = {};       /* post id -> that card's info block, waiting for a name */
  var uploaderCacheRead = false;
  var uploaderDraining = false;

  function uploaderCacheLoad() {
    if (uploaderCacheRead) return;
    uploaderCacheRead = true;
    var raw = null;
    try {
      if (typeof GM_getValue === "function") raw = GM_getValue(UPLOADER_CACHE_KEY, null);
    } catch (e) { /* fall through to localStorage */ }
    if (raw === null || raw === undefined) {
      try { raw = JSON.parse(localStorage.getItem(UPLOADER_CACHE_KEY) || "null"); } catch (e) { raw = null; }
    }
    if (typeof raw === "string") { try { raw = JSON.parse(raw); } catch (e) { raw = null; } }
    if (raw && typeof raw === "object" && !Array.isArray(raw)) {
      Object.keys(raw).forEach(function (k) {
        var v = raw[k];
        if (typeof v === "string" && v.trim()) uploaderNames[String(k)] = v.trim();
      });
    }
  }

  function uploaderCacheSave() {
    uploaderCacheLoad();
    var keys = Object.keys(uploaderNames);
    if (keys.length > UPLOADER_CACHE_MAX) {
      keys.slice(0, keys.length - UPLOADER_CACHE_MAX).forEach(function (k) { delete uploaderNames[k]; });
    }
    try {
      if (typeof GM_setValue === "function") { GM_setValue(UPLOADER_CACHE_KEY, uploaderNames); return; }
    } catch (e) { /* fall through */ }
    try { localStorage.setItem(UPLOADER_CACHE_KEY, JSON.stringify(uploaderNames)); } catch (e) { /* private mode */ }
  }

  function uploaderName(id) {
    if (id === null || id === undefined || id === "") return "";
    uploaderCacheLoad();
    return uploaderNames[String(id)] || "";
  }

  /* The card's uploader line: the label in the same look as the notes label, the name in the
     card's own uploader chip. */
  function uploaderLine(name, upId) {
    var row = el("div", NS + "-up-row");
    row.setAttribute("data-" + NS + "-up", "1");
    row.appendChild(el("span", NS + "-notes-label", LABELS.uploaderLabel));
    var href = "/profile/" + encodeURIComponent(upId);
    row.appendChild(uploaderChip(name, href, LABELS.chipProfileTitle(name)));
    return row;
  }

  /* Cards rendered before their uploader's name arrived get the line the moment it is known. */
  function fillWaitingUploader(postId) {
    postId = String(postId || "");
    var upId = uploaderIds[postId] || "";
    var name = uploaderName(upId);
    var info = uploaderWaiting[postId];
    if (!info) return;
    if (name && document.contains(info) && !info.querySelector("[" + "data-" + NS + "-up" + "]")) {
      info.insertBefore(uploaderLine(name, upId), info.firstChild);
    }
    delete uploaderWaiting[postId];
  }

  function rememberCardUploader(postId, upId, name) {
    postId = String(postId === null || postId === undefined ? "" : postId);
    upId = String(upId === null || upId === undefined ? "" : upId);
    if (!postId || !upId) return;
    uploaderCacheLoad();
    uploaderIds[postId] = upId;
    name = typeof name === "string" ? name.trim() : "";
    if (name && !uploaderNames[upId]) { uploaderNames[upId] = name; uploaderCacheSave(); }
    if (!uploaderNames[upId] && uploaderAsked[upId] !== true) uploaderQueue.push(upId);
    fillWaitingUploader(postId);
  }

  /* One request per uploader id that has no name yet, serially, capped per batch. The site states
     a username for an id at /api/users/<id>; asked once, remembered, never asked again. */
  function drainUploaderLookups() {
    if (uploaderDraining) return;
    uploaderDraining = true;
    var asked = 0;
    function next() {
      var id = "";
      while (uploaderQueue.length) {
        var candidate = uploaderQueue.shift();
        if (!uploaderAsked[candidate] && !uploaderNames[candidate]) { id = candidate; break; }
      }
      if (!id || asked >= UPLOADER_LOOKUP_CAP) { uploaderDraining = false; return; }
      uploaderAsked[id] = true;
      asked++;
      fetch("/api/users/" + encodeURIComponent(id), {
        headers: { accept: "application/json" },
        credentials: "same-origin",
      })
        .then(function (r) { return r && r.ok ? r.json() : null; })
        .then(function (j) {
          var name = j && typeof j.username === "string" ? j.username.trim() : "";
          if (!name) return;
          uploaderNames[id] = name;
          uploaderCacheSave();
          Object.keys(uploaderIds).forEach(function (pid) {
            if (uploaderIds[pid] === id) fillWaitingUploader(pid);
          });
        })
        .catch(function () { /* the site would not say who this is: the line stays absent */ })
        .then(next);
    }
    next();
  }

  /* A profile's payload lists that user's own uploads and states the user by name; a listing
     response states each card's uploader id. A profile's favourites list cards other people
     uploaded, so it is read for nothing: attributing those to the profile owner would be a guess. */
  function readUploaderPayload(body) {
    var j = null;
    try { j = JSON.parse(body); } catch (e) { return; }
    if (!j || typeof j !== "object") return;
    var ownerId = null, ownerName = "";
    if (j.id !== null && j.id !== undefined && typeof j.username === "string" && j.username.trim()) {
      ownerId = String(j.id);
      ownerName = j.username.trim();
      uploaderCacheLoad();
      if (!uploaderNames[ownerId]) { uploaderNames[ownerId] = ownerName; uploaderCacheSave(); }
    }
    function each(list, attributedTo) {
      if (!Array.isArray(list)) return;
      list.forEach(function (p) {
        if (!p || typeof p !== "object" || p.id === null || p.id === undefined) return;
        var upId = p.uploader_id !== null && p.uploader_id !== undefined ? p.uploader_id : attributedTo;
        var name = typeof p.uploader_name === "string" ? p.uploader_name : (attributedTo === ownerId ? ownerName : "");
        rememberCardUploader(p.id, upId, name);
      });
    }
    each(j.posts, null);
    each(j.cards, null);
    each(j.items, null);
    each(j.uploads, ownerId);
    each(j.pinned_uploads, ownerId);
    if (j.card && j.card.id !== undefined) each([j.card], null);
  }

  function uploaderPayloadUrl(url) {
    var path = String(url || "").replace(/^https?:\/\/[^/]+/i, "");
    return /^\/posts\/?\?/.test(path) || /^\/api\/users\/\d+$/.test(path);
  }

  /* Watch the page's own requests. Only the real page window can be watched: where a manager
     offers no honest way in, nothing is installed and those listing pages simply show no uploader
     line — the rule the owner set for anything the page does not state. */
  function pageWorld() {
    try { if (typeof unsafeWindow !== "undefined" && unsafeWindow) return unsafeWindow; } catch (e) { /* no unsafeWindow here */ }
    try { if (window.wrappedJSObject) return window.wrappedJSObject; } catch (e) { /* no wrappedJSObject here */ }
    return null;
  }

  function installUploaderCapture() {
    var w = pageWorld();
    if (!w || typeof w.fetch !== "function") return false;
    if (w.fetch[NS + "_capture"]) return true;
    var original = w.fetch;
    function wrapped(input, init) {
      var out;
      try { out = original.call(w, input, init); } catch (e) { return original.call(w, input, init); }
      var url = "";
      try { url = typeof input === "string" ? input : (input && input.url) || ""; } catch (e) { url = ""; }
      if (url && uploaderPayloadUrl(url)) {
        try {
          Promise.resolve(out).then(function (res) {
            if (!res || !res.ok || typeof res.clone !== "function") return null;
            return res.clone().text().then(function (body) { readUploaderPayload(body); });
          }).catch(function () { /* not text, not ours to read */ });
        } catch (e) { /* never break the page's own request */ }
      }
      return out;
    }
    try {
      wrapped[NS + "_capture"] = true;
      w.fetch = wrapped;
      return true;
    } catch (e) { return false; }
  }

  function followLink(a, href) {
    a.addEventListener("click", function (e) {
      if (e.ctrlKey || e.metaKey || e.shiftKey || e.button !== 0) return;   /* the browser keeps its own middle-click */
      var w = pageWin();
      var pm = /^\/profile\/(\d+)$/.exec(href);
      if (pm && typeof w.loadProfile === "function") {
        e.preventDefault();
        try { w.loadProfile(parseInt(pm[1], 10)); } catch (err) { window.location.assign(href); }
        return false;
      }
      var sm = /^\/search\?/.exec(href);
      if (sm) {
        e.preventDefault();
        if (typeof w._openGallerySearch === "function") {
          try { w._openGallerySearch(decodeURIComponent(href.replace(/^\/search\?t=/, ""))); } catch (err) { window.location.assign(href); }
        } else {
          window.location.assign(href);
        }
        return false;
      }
    });
  }

  function uploaderChip(name, href, titleText) {
    var a = el("a", NS + "-uploader", name);
    a.href = href;
    a.rel = "nofollow";
    a.title = titleText;
    followLink(a, href);
    return a;
  }

  /* The chip row a card gets: the card's own chips, ordered writer-first, capped AFTER the
     ordering. A cap applied to the raw list is a cap that can cut the one chip the row was asked
     to lead with — which is how a card's author disappeared from a profile's card list.
     On a profile page the row leads with the author tag the site itself put on that card: matched
     by name against the profile's own user, kept in the classes the site gave it (so its colour is
     the site's, unchanged), moved to the front, and never cut by the cap. Nothing is ever added to
     a card. A card that carries no such tag gets no author chip, and a page whose owner the site
     never named leads with whatever the card itself says. */
  function buildTagRow(post) {
    var host = post.querySelector(".gallery-card-tags-inner > div");
    var spans = host && host.querySelectorAll ? host.querySelectorAll("span") : [];
    var owner = profileOwner();
    var ownerLower = owner && owner.named ? String(owner.name).toLowerCase() : "";
    var list = [];
    for (var i = 0; i < spans.length; i++) {
      var name = (spans[i].textContent || "").trim();
      if (!name || /^\+\d+\s+more$/.test(name)) continue;
      var cat = chipCategory(spans[i]);
      var isAuthor = !!ownerLower && name.toLowerCase() === ownerLower;
      list.push({
        name: name, cat: cat, href: tagHref(name, cat), title: LABELS.chipTitle(name),
        native: isAuthor ? String(spans[i].className || "") : null,
      });
    }
    if (!list.length) return null;

    list = rankChips(list);

    /* the author chip leads the row whatever category the site filed it under */
    var authorAt = -1;
    for (var k = 0; k < list.length; k++) { if (list[k].native !== null) { authorAt = k; break; } }
    if (authorAt > 0) list.unshift(list.splice(authorAt, 1)[0]);
    var cap = parseInt(P("tagCap"), 10);
    if (isNaN(cap)) cap = DEFAULTS.tagCap;
    var showAll = !cap || cap <= 0 || cap >= list.length;
    var shown = showAll ? list : list.slice(0, cap);

    var box = el("div", NS + "-tags");
    shown.forEach(function (c) {
      /* A real link, like the site's own tag chips: an <a> has an address, so middle-click,
         Ctrl-click and "copy link address" reach the tag instead of the card. An <a> inside an
         <a> is invalid only to an HTML parser — these nodes are created and appended, never
         parsed, and the site does the same thing. */
      var chip = el("a", NS + "-tag", c.name);
      if (c.native !== null) {
        /* the site's own classes ride along: whatever colour the site gave this tag stays its
           colour, and no category rule of ours is applied to it */
        if (c.native) chip.className = NS + "-tag " + c.native;
      } else {
        chip.setAttribute("data-cat", c.cat);
      }
      chip.setAttribute("href", c.href);
      chip.setAttribute("title", c.title);
      followLink(chip, c.href);
      box.appendChild(chip);
    });
    var rest = list.length - shown.length;
    if (rest > 0) box.appendChild(el("span", NS + "-tags-more", "+" + rest));
    return box;
  }

  function buildInfo(tile, post) {
    var info = el("div", NS + "-info");
    info.setAttribute("data-" + NS + "-info", "1");

    /* The uploader line: under the picture, above the card's own info, first in the block. Only
       what the page stated about this card is drawn. A name that has not arrived yet leaves the
       card remembered as waiting, and the line appears when it does; an uploader nobody stated
       leaves no line at all. */
    if (P("cardUploader")) {
      var upPostId = String(tile.getAttribute("data-post-id") || "");
      var upId = uploaderIds[upPostId] || "";
      var upName = upId ? uploaderName(upId) : "";
      if (upName) info.appendChild(uploaderLine(upName, upId));
      else if (upId) uploaderWaiting[upPostId] = info;
    }

    var descSrc = post.querySelector(".chov-layer-description .gallery-card-description-inner") ||
                  post.querySelector(".chov-layer-description");
    var notesSrc = post.querySelector(".chov-layer-notes .gallery-card-notes-inner") ||
                   post.querySelector(".chov-layer-notes");

    var descCls = clampClass(P("descLines"), DEFAULTS.descLines);
    var notesCls = clampClass(P("notesLines"), DEFAULTS.notesLines);

    /* the two paragraphs are independent: each has its own switch, its own collapsed
       height, and they can be swapped in either order */
    var descBlock = P("showDesc") && descSrc ? textBlock(descSrc, descCls, null) : null;
    var notesBlock = P("showNotes") && notesSrc ? textBlock(notesSrc, NS + "-notes " + notesCls, LABELS.notesTag) : null;

    /* With the description switched off, the notes are the only text the card has, and
       they were still wearing the dim colour that only made sense next to the
       description. The one thing on the card should look like the thing on the card. */
    if (notesBlock && !descBlock) {
      notesBlock.wrap.classList.add(NS + "-bright");
      notesBlock.p.classList.add(NS + "-bright");
    }

    var clampedDesc = [];
    var clampedNotes = [];

    function addBlock(b, kind, cls) {
      if (!b) return;
      info.appendChild(b.wrap);
      var clamped = cls === "" ? null : b.p;
      if (clamped) (kind === "notes" ? clampedNotes : clampedDesc).push(clamped);
    }

    if (P("notesFirst")) {
      addBlock(notesBlock, "notes", notesCls);
      addBlock(descBlock, "desc", descCls);
    } else {
      addBlock(descBlock, "desc", descCls);
      addBlock(notesBlock, "notes", notesCls);
    }

    /* Show more / less — added only when a paragraph the button can expand really overflows. */
    var toggle = null;
    if (clampedDesc.length || clampedNotes.length) {
      toggle = el("span", NS + "-more");
      toggle.setAttribute("role", "button");
      toggle.setAttribute("tabindex", "0");
      toggle.textContent = LABELS.more;
      toggle.setAttribute("data-" + NS + "-more", "1");
      info.appendChild(toggle);
    }

    if (P("showTags")) {
      var tagRow = buildTagRow(post);
      if (tagRow) info.appendChild(tagRow);
    }

    if (P("showStats")) {
      var statHost = post.querySelector(".gallery-card-stats-header");
      if (statHost) {
        var row = el("div", NS + "-stats");
        statHost.querySelectorAll("span[title]").forEach(function (s) {
          var title = s.getAttribute("title") || "";
          var value = (s.textContent || "").trim();
          if (!value) return;
          var kind = /token/i.test(title) ? "tokens"
            : /download/i.test(title) ? "downloads"
            : /favor/i.test(title) ? "favorites"
            : /comment/i.test(title) ? "comments"
            : /view/i.test(title) ? "views" : null;
          if (!kind) return;
          var cell = el("span", NS + "-stat");
          cell.setAttribute("title", title);
          cell.appendChild(icon(kind));
          cell.appendChild(el("span", null, value));
          row.appendChild(cell);
        });
        if (row.childNodes.length) info.appendChild(row);
      }
    }

    return {
      info: info,
      toggle: toggle,
      clamped: clampedDesc.concat(clampedNotes),
      clampedDesc: clampedDesc,
      clampedNotes: clampedNotes,
    };
  }

  /* What the "more ▾" strip expands. A target that is switched off or not clamped
     falls back to the other paragraph, so the strip never becomes a dead control. */
  function moreTargets(built) {
    var behavior = P("moreBehavior");
    if (behavior === "desc") return built.clampedDesc.length ? built.clampedDesc : built.clampedNotes;
    if (behavior === "both") return built.clamped;
    return built.clampedNotes.length ? built.clampedNotes : built.clampedDesc;
  }

  /* ───────────────────────── process a tile ───────────────────────── */

  /* The character name the site puts under the artwork: a <p> carrying its own
     "truncate" class, inside the card's footer row (ui.js renderCard). */
  function findNameEl(tile) {
    var kids = tile.children;
    for (var i = 0; i < kids.length; i++) {
      var child = kids[i];
      if (child.nodeType !== 1) continue;
      /* Only the blocks we created are skipped. The art and the name row carry our
         stamps as well, but they ARE the site's elements: skipping them by prefix made
         the name unfindable after the first settings change, which silently turned off
         the title and the slide on every later pass. */
      if (child.classList.contains(NS + "-info") || child.classList.contains(NS + "-title")) continue;
      var ps = child.querySelectorAll(":scope > p");
      for (var j = 0; j < ps.length; j++) {
        if ((ps[j].className || "").indexOf("truncate") !== -1) return ps[j];
      }
    }
    return null;
  }

  function buildTitle(nameEl, tile) {
    if (!nameEl) return null;
    unwrapMarquee(nameEl);
    var title = el("div", NS + "-title");
    var text = el("span", NS + "-title-text");
    /* the name goes into a span of its own even when it is not sliding: that span is
       what the slide moves later, and wrapping it here is the difference between a
       picture sliding out of a window and the text sliding inside the window */
    var inner = el("span", NS + "-marquee-inner");
    var kids = nameEl.childNodes;
    for (var i = 0; i < kids.length; i++) inner.appendChild(kids[i].cloneNode(true));
    text.appendChild(inner);
    title.appendChild(text);
    nameEl.classList.add(NS + "-hidden-name");

    /* With the name moved up, the footer row is left holding the card's badges and the
       hide / download controls. Those are worth keeping — they are how you hide a post or
       grab the file — but not worth a whole row of card height on a phone, so they move
       into the title row beside the name and the emptied row is hidden. The name itself
       stays in the DOM, hidden, so the site's own markup is never deleted. */
    var row = nameEl.parentNode;
    if (row && row !== tile) {
      var rowKids = [].slice.call(row.children);
      for (var k = 0; k < rowKids.length; k++) {
        var c = rowKids[k];
        if (c === nameEl || (c.className || "").indexOf(NS + "-hidden") !== -1) continue;
        title.appendChild(c); // same document: appendChild re-parents the node
      }
      var rest = "";
      [].slice.call(row.childNodes).forEach(function (n) {
        if (n.nodeType === 3) rest += n.nodeValue || "";
      });
      if (!rest.trim()) row.classList.add(NS + "-hidden-foot");
    }

    tile.insertBefore(title, tile.firstChild);
    return title;
  }

  /* Take the text back out of the slide wrapper: without this, re-running the pass
     would nest wrapper inside wrapper. */
  function unwrapMarquee(scope) {
    [].slice.call(scope.querySelectorAll("." + NS + "-marquee-inner")).forEach(function (sp) {
      var parent = sp.parentNode;
      if (!parent) return;
      while (sp.firstChild) parent.insertBefore(sp.firstChild, sp);
      parent.removeChild(sp);
      parent.classList.remove(NS + "-name-slide");
    });
  }

  /* How much a name has to overflow before sliding it is worth the motion. The site already
     ellipsizes anything wider than its row, and a name cut by a few pixels still reads as a
     whole name — sliding that looks like the card is broken. So the cut has to be real:
     about a tenth of the row, and never less than a dozen pixels (measured on a phone: the
     name row inside a 2-column card is 112px wide, and the names that used to slide at 5px,
     7px and 11px over are the ones the user saw moving for no reason). A name genuinely too
     long for its box — 40, 60, 90px over — still slides. */
  function slideAmount(over, boxWidth) {
    if (over <= 0) return 0;
    var floor = Math.max(12, Math.round(boxWidth * 0.1));
    return over > floor ? over + 6 : 0;
  }

  /* Sliding name, only where it is needed: a title measured wider than its box,
     once the card is laid out (a rAF later), like the "more ▾" overflow check. */
  function measureTitle(title) {
    if (!title || !P("marqueeName")) return;
    var clip = title.querySelector("." + NS + "-title-text");
    var inner = clip && clip.querySelector("." + NS + "-marquee-inner");
    if (!clip || !inner) return;
    /* the box says how much room there is, the span inside it says how much text there
       is (a nowrap span reports its own full width even inside a clipped box) */
    var dx = slideAmount(inner.scrollWidth - clip.clientWidth, clip.clientWidth);
    if (!dx) { title.classList.remove("bbx-marquee-on"); return; }   // it fits: the box clips it
    inner.style.setProperty("--bbx-marquee-dx", "-" + dx + "px");
    inner.style.setProperty("--bbx-marquee-dur", Math.max(4, Math.round(dx / 22)) + "s");
    title.classList.add("bbx-marquee-on");
  }

  /* The same treatment for the name the site keeps below the art: wrap its text in a
     span, measure the wrap against the site's own row, slide only if it does not fit. */
  function marqueeInline(nameEl) {
    if (!nameEl || !P("marqueeName")) return;
    var text = nameEl.querySelector("." + NS + "-marquee-inner");
    if (!text) {
      text = el("span", NS + "-marquee-inner");
      while (nameEl.firstChild) text.appendChild(nameEl.firstChild);
      nameEl.appendChild(text);
    }
    var dx = slideAmount(text.scrollWidth - nameEl.clientWidth, nameEl.clientWidth);
    if (!dx) { unwrapMarquee(nameEl); return; }   // it fits: leave the site's row exactly as it was
    nameEl.classList.add(NS + "-name-slide");
    text.style.setProperty("--bbx-marquee-dx", "-" + dx + "px");
    text.style.setProperty("--bbx-marquee-dur", Math.max(4, Math.round(dx / 22)) + "s");
  }

  function stripClamp(p) {
    p.classList.remove(NS + "-clamp");
    [2, 3, 4, 6, 8].forEach(function (n) { p.classList.remove(NS + "-clamp-" + n); });
  }

  /* ───────────────────── the picture a card shows ─────────────────────
     The card's own thumbnail is /images/preview/640/<file>, and the same builder the
     site uses answers /images/preview/8192/<file> for the picture itself (measured on
     a live card: 55 KB for the thumbnail, 653 KB for the full picture, both webp). Only
     the tier in the URL changes and the filename is already sitting in the card, so
     there is nothing to look up and nothing to guess.
     The site's loader reads data-thumb-src when it decides to fetch an image, and it
     also re-reads that attribute when a load fails and is retried — but an image that
     already loaded is never re-read. So both the attribute and a src that is already
     set have to be rewritten together, or a card on screen keeps its thumbnail. */

  var THUMB_PREFIX = "/images/preview/";
  var HIRES_TIER = 8192;

  function previewParts(url) {
    var m = /^(.*?)(\/images\/preview\/)([^/]+)\/([^?]*)(\?.*)?$/.exec(url || "");
    if (!m || !m[4]) return null;
    return { head: m[1], file: m[4], query: m[5] || "" };
  }

  function previewAtTier(url, tier) {
    var parts = previewParts(url);
    if (!parts) return null;
    return parts.head + THUMB_PREFIX + tier + "/" + parts.file + parts.query;
  }

  /* A full-resolution switch is a one-column phone thing: on a wide screen the phone
     layout is not in effect at all, and asking for 8192-pixel pictures there would be
     pure download cost with nothing gained. */
  function hiResWanted() {
    if (!P("hiRes")) return false;
    var cols = String(P("phoneColumns"));
    return (cols === "1" || cols === "full") && window.innerWidth <= 640;
  }

  function applyThumbTo(img, hi) {
    if (!img || img.nodeType !== 1) return;
    var current = img.getAttribute("data-thumb-src") || img.getAttribute("src") || "";
    if (!current) return;                       // the site has not assigned this image yet
    var original = img.getAttribute("data-" + NS + "-thumb0");
    if (!original) {
      if (!previewParts(current)) return;       // not a tiered preview URL: leave it alone
      original = current;
      img.setAttribute("data-" + NS + "-thumb0", original);   // what the site asked for, kept for later
    }
    var want = hi ? previewAtTier(original, HIRES_TIER) : original;
    if (!want || want === current) return;
    img.setAttribute("data-thumb-src", want);
    if (img.getAttribute("src")) img.setAttribute("src", want);
  }

  var thumbsQueued = false;
  /* The native-ratio switch may only change a card once its picture is known to have a
     ratio of its own: swapping the box while an image is still arriving is how a list starts
     jumping under your finger. data-bbx-natural is therefore stamped from naturalWidth, on
     the way the site already loads the picture, and every rule for the switch is gated on
     that attribute. */
  function markNatural(img) {
    if (!img || img.tagName !== "IMG") return;
    var stamp = function () {
      if (!img.naturalWidth || !img.naturalHeight) return;
      var art = img.parentNode;
      while (art && art.nodeType === 1 && !(art.classList && art.classList.contains(NS + "-art"))) art = art.parentNode;
      if (!art) return;
      art.setAttribute("data-" + NS + "-natural", img.naturalWidth + "x" + img.naturalHeight);
    };
    if (img.complete && img.naturalWidth) { stamp(); return; }
    if (img.getAttribute("data-" + NS + "-natural-hook")) return;
    img.setAttribute("data-" + NS + "-natural-hook", "1");
    img.addEventListener("load", stamp);
  }

  function queueThumbs() {
    if (thumbsQueued) return;
    thumbsQueued = true;
    requestAnimationFrame(function () {
      thumbsQueued = false;
      applyThumbs();
    });
  }

  /* A profile page carries a whole hidden gallery in its markup (measured: 24 cards in a
     wrapper the site hides, next to the 50 the page actually shows). Loading the
     full-resolution tier for those would download megabytes nobody can see, so a card is
     only upgraded when nothing between it and the page root is hiding it. The site hides a
     block with its own utility class or the hidden attribute, which is what this looks for
     — a computed-style or offset-parent test would work in a browser but not in a headless
     document at all, and this check has to hold in both. */
  function offscreen(card) {
    for (var n = card; n && n.nodeType === 1; n = n.parentNode) {
      if (n.hidden) return true;
      if (n.classList && n.classList.contains("hidden")) return true;
      if (n.style && n.style.display === "none") return true;
      if (n === document.documentElement) return false;
    }
    return false;
  }

  function applyThumbs() {
    var hi = hiResWanted();
    var imgs = document.querySelectorAll("a[data-post-id] img");
    for (var i = 0; i < imgs.length; i++) {
      var card = imgs[i].closest ? imgs[i].closest("a[data-post-id]") : null;
      if (card && offscreen(card)) continue;
      applyThumbTo(imgs[i], hi);
      markNatural(imgs[i]);
    }
  }

  function processTile(tile) {
    if (!tile || tile.nodeType !== 1) return;
    if (tile.getAttribute("data-" + NS + "-done")) return;
    if (!tile.hasAttribute("data-post-id")) return;
    var overlay = tile.querySelector(".gallery-card-hover-stack");
    if (!overlay) return; // no preview data for this card

    tile.setAttribute("data-" + NS + "-done", "1");

    /* Name the site's own two rows so the phone CSS can place them by class instead
       of guessing from their position (a title above the art changes that order). */
    var art = tile.querySelector(":scope > [class*=\"aspect-\"]") || tile.querySelector(":scope > div");
    if (art) art.classList.add(NS + "-art");
    var tileImg = tile.querySelector("img");
    applyThumbTo(tileImg, hiResWanted());
    markNatural(tileImg);
    var nameEl = findNameEl(tile);
    if (nameEl && nameEl.parentNode && nameEl.parentNode !== tile) nameEl.parentNode.classList.add(NS + "-foot");
    var title = P("nameAbove") ? buildTitle(nameEl, tile) : null;

    var built = buildInfo(tile, tile);
    var hasInfo = built.info.childNodes.length > 0;
    if (hasInfo) tile.appendChild(built.info);
    if (hasInfo) ensureMediaButton(tile);
    /* "0" means: this card was tried and has nothing to show (the switches are all
       off). It is terminal, so a re-render of the same card cannot queue it forever,
       while a card that never got decorated at all — no preview overlay yet — stays
       un-stamped and is retried. */
    if (!hasInfo && !title) {
      if (nameEl) requestAnimationFrame(function () { marqueeInline(nameEl); });
      tile.setAttribute("data-" + NS + "-done", "0");
      return;
    }

    requestAnimationFrame(function () {
      if (title) measureTitle(title);
      else marqueeInline(nameEl);
      if (!built.toggle) return;
      var targets = moreTargets(built);
      /* Which paragraphs the strip really unlocks: the ones the setting points at, but
         only if they are genuinely cut. If the configured block happens to fit while
         the other one is cut, the button follows the text that is actually hidden
         instead of doing nothing when tapped. */
      var live = targets.filter(overflows);
      if (!live.length) live = built.clamped.filter(overflows);
      if (!live.length) {
        if (built.toggle.parentNode) built.toggle.parentNode.removeChild(built.toggle);
        built.toggle = null;
        built.clamped.forEach(stripClamp);
        built.clamped = [];
        built.targets = [];
        return;
      }
      built.targets = live;
      if (P("openCards")) setOpen(built, true);
    });

    if (hasInfo) wireInfo(tile, built);
  }

  function overflows(p) {
    return p.scrollHeight > p.clientHeight + 2;
  }

  function setOpen(built, open) {
    (built.targets || moreTargets(built)).forEach(function (p) {
      if (open) p.classList.remove(NS + "-clamp");
      else p.classList.add(NS + "-clamp");
    });
    if (built.toggle) {
      built.toggle.textContent = open ? LABELS.less : LABELS.more;
      built.toggle.setAttribute("aria-expanded", open ? "true" : "false");
    }
    built.open = open;
  }

  function wireInfo(tile, built) {
    var info = built.info;
    info.addEventListener("click", function (e) {
      /* A tag chip is a link of its own: the browser follows it, in this tab or in the
         new one the user asked for. We only stop the tap travelling on to the card, so
         a normal click lands on the tag search and Ctrl-click opens it in a new tab. */
      var tag = e.target.closest && e.target.closest("a." + NS + "-tag");
      if (tag) { e.stopPropagation(); return; }
      var more = e.target.closest && e.target.closest("[" + "data-" + NS + "-more]");
      if (more) {
        e.preventDefault(); e.stopPropagation();
        setOpen(built, !built.open);
        return;
      }
      // a tap anywhere else in the text area should still open the card
    });
    info.addEventListener("keydown", function (e) {
      if (e.key !== "Enter" && e.key !== " ") return;
      /* a chip is a link: the browser already activates it on Enter, and its href is the
         tag search — so a keyboard user gets the same place a click gets, modifiers and
         all. Only the "more ▾" strip still needs help here. */
      if (e.target.closest && e.target.closest("a." + NS + "-tag")) return;
      var more = e.target.closest && e.target.closest("[" + "data-" + NS + "-more]");
      if (more) { e.preventDefault(); e.stopPropagation(); setOpen(built, !built.open); }
    });
  }

  /* ─────────── the site header: three small additions ───────────
     Each one sits inside the header's own button cluster and wears the class string the
     header's buttons carry, so it reads as part of the header rather than as something glued
     on. None of them is a second login, a second blacklist or a second search: each reaches
     the site's own control and lets the site do the work. */

  var chromeState = { bl: null, login: null, tight: false, resizeWatch: false, signature: "", plan: -1, evalQueued: false, viewportWidth: 0 };

  var collapseOriginals = {};

  /* The header's button cluster is found from the two controls that are always in it — never
     from a class name, because renaming a utility class is what a site build does most often. */
  function headerCluster() {
    var a = document.getElementById("ai-toggle-btn");
    var b = document.getElementById("nav-upload-btn");
    if (!a || !b) return null;
    var n = a.parentNode;
    while (n && n.nodeType === 1) {
      if (n.contains && n.contains(b)) return n;
      n = n.parentNode;
    }
    return null;
  }

  /* The site offsets its mobile drawer from --site-top-header-h, a value it measures from the
     real header height at its own sync points (boot, and a handful of re-renders). The mod's
     compaction changes that height after every one of those points, so the drawer kept starting
     under a header that had already become shorter: an empty band between the two. Measured
     here, the same way the site measures it, whenever our pass touches the header. */
  function syncHeaderOffset() {
    var header = document.querySelector(".site-top-header");
    if (!header || !header.offsetHeight) return;
    var h = Math.max(0, Math.round(header.offsetHeight));
    if (!h) return;
    var want = h + "px";
    var have = "";
    try { have = document.documentElement.style.getPropertyValue("--site-top-header-h") || ""; } catch (e) { /* no inline style access */ }
    if (have === want) return;
    try { document.documentElement.style.setProperty("--site-top-header-h", want); } catch (e) { /* ignore */ }
  }

  function loggedIn() {
    try { return !!localStorage.getItem("token"); } catch (e) { return false; }
  }

  function chromeButton(kind, text, iconName) {
    var b = el("button", NS + "-chip " + SITE_BTN);
    b.type = "button";
    b.setAttribute("data-" + NS + "-chrome", kind);
    /* an icon is a word of its own here: a lock needs no label next to it, and the label is
       what pushes the header onto a second line */
    if (iconName) {
      b.appendChild(icon(iconName));
      b.setAttribute("aria-label", kind === "login" ? "Log in or register" : kind);
    }
    if (text) b.appendChild(document.createTextNode(text));
    return b;
  }

  function dropChrome(kind) {
    [].slice.call(document.querySelectorAll("[" + "data-" + NS + "-chrome=\"" + kind + "\"]")).forEach(function (n) {
      if (n.parentNode) n.parentNode.removeChild(n);
    });
    if (kind === "bl") chromeState.bl = null;
    if (kind === "login") chromeState.login = null;
  }

  /* The site's own account entry: in the drawer on a phone, in the nav on a wide screen.
     Clicking it is the site's own route into its own account screen. */
  function accountEntry() {
    return document.getElementById("mnav-account") || document.getElementById("nav-settings-btn") || null;
  }

  function openAccount() {
    var entry = accountEntry();
    if (entry) { entry.click(); return true; }
    if (typeof pageWin().switchView === "function") { pageWin().switchView("account-view", "/account"); return true; }
    return false;
  }

  /* "Reveal blocked" is the site's own switch (window._revealBlocked) and it only appears in
     the sub-nav row, which a phone never shows. This chip is how a phone reaches it. */
  function revealItem() {
    var hosts = ["nav-subnav-items", "nav-items", "sidebar-nav"];
    for (var h = 0; h < hosts.length; h++) {
      var host = document.getElementById(hosts[h]);
      if (!host) continue;
      var items = host.querySelectorAll("button, a");
      for (var i = 0; i < items.length; i++) {
        var t = (items[i].textContent || "").trim().toLowerCase();
        if (t === "reveal blocked" || t === "hide blocked") return items[i];
      }
    }
    return null;
  }

  function blLabel(btn) {
    var on = !!pageWin()._revealBlocked;
    /* "BL" is this chip's own name, so it keeps it; what the compact header drops is the state
       wording around it. */
    btn.textContent = P("headerCompact") ? ("BL " + (on ? "\u2713" : "\u2717")) : ("BL: " + (on ? "on" : "off"));
    btn.setAttribute("aria-pressed", on ? "true" : "false");
    btn.title = on
      ? "Showing cards your tag blacklist would hide. Tap to hide them again. (tag blacklist only — NSFW and NSFL rules still apply)"
      : "Hiding cards that match your tag blacklist. Tap to show them: this page only, not saved, and the list changes because revealed cards take the place of others.";
    return on;
  }

  function toggleReveal(btn) {
    var item = revealItem();
    if (item) {
      item.click();          /* the site flips its own flag and re-renders its own sub-nav */
      blLabel(btn);
      return;
    }
    var w = pageWin();
    w._revealBlocked = !w._revealBlocked;
    if (typeof w.loadGallery === "function") w.loadGallery();
    blLabel(btn);
  }

  /* A label the site already writes: keep its meaning, drop its length. The state word is read
     from the label the site actually rendered, so a wording change on the site cannot make
     this lie about it. */
  /* The state, on its own. The site writes "NSFW: On"; what the header shows after this is
     "On ✓" — no label, only the status, exactly as the owner asked for. The label the state
     belongs to is not lost, it moves to the button's title / aria-label, and the site's own
     wording is kept on the node so the state can always be re-read from it. */
  var STATE_ON = "On \u2713";   // ✓
  var STATE_OFF = "Off \u2717";  // ✗

  function stateShort(text) {
    var t = String(text || "").trim();
    if (t === STATE_ON || /\u2713$/.test(t)) return STATE_ON;   // already ours: stay put
    if (t === STATE_OFF || /\u2717$/.test(t)) return STATE_OFF;
    if (/\boff\b$/i.test(t) || /:\s*OFF$/i.test(t)) return STATE_OFF;
    if (/\bon\b$/i.test(t) || /:\s*ON$/i.test(t)) return STATE_ON;
    return null;   /* a wording this map does not know is not shortened at all */
  }

  /* Is this wording one of the ones collapseLabels writes — a state or a glyph — rather than
     something the site wrote? Glyph buttons are shortened to a fixed mark, and without this test
     the mark on the node would be taken for the site's own wording and handed back as it. */
  function ourShortText(text) {
    if (text === STATE_ON || text === STATE_OFF) return true;
    var ids = Object.keys(HEADER_GLYPH);
    for (var i = 0; i < ids.length; i++) { if (text === HEADER_GLYPH[ids[i]]) return true; }
    return false;
  }

  function collapseLabels() {
    var want = !!P("headerCompact");
    var cluster = headerCluster();
    if (cluster) cluster.classList.toggle(NS + "-cluster-compact", want);
    Object.keys(HEADER_STATE).concat(Object.keys(HEADER_GLYPH)).forEach(function (id) {
      var n = document.getElementById(id);
      if (!n) return;
      var live = String(n.textContent || "").trim();
      /* The site writes these labels itself. The first wording met on a node is the site's own,
         and so is every wording that is not one of the two states this function writes — which
         is what the state is read from, what the title keeps, and what is handed back verbatim
         the moment the switch is off. */
      if (collapseOriginals[id] === undefined ||
          (live && !ourShortText(live) && live !== collapseOriginals[id])) {
        collapseOriginals[id] = live || collapseOriginals[id] || "";
      }
      var own = collapseOriginals[id];
      if (!want) {
        if (own && n.textContent !== own) n.textContent = own;
        n.removeAttribute("data-" + NS + "-state");
        return;
      }
      var short = null;
      if (HEADER_STATE[id]) {
        short = stateShort(own || live);
        if (!short) return;                     /* nothing safe to say: leave the site's label */
        n.setAttribute("data-" + NS + "-state", short === STATE_ON ? "on" : "off");
      } else {
        short = HEADER_GLYPH[id] || null;       /* a fixed button becomes its glyph */
        if (!short) return;
      }
      if (n.textContent !== short) n.textContent = short;
      var full = HEADER_GLYPH_TITLE[id] || own;
      if (full) {
        n.setAttribute("title", full);
        n.setAttribute("aria-label", full);
      }
    });
    if (!want) collapseOriginals = {};
  }

  function headerChrome() {
    var cluster = headerCluster();
    if (!cluster) return;
    /* a header the site rebuilt wiped our buttons: forget the dead references */
    if (chromeState.bl && !cluster.contains(chromeState.bl)) chromeState.bl = null;
    if (chromeState.login && !cluster.contains(chromeState.login)) chromeState.login = null;

    var anchor = document.getElementById("nav-upload-btn") || document.getElementById("ai-toggle-btn");
    var insertAt = anchor && anchor.parentNode === cluster ? anchor.nextSibling : null;
    var live = P("enabled");

    var wantLogin = live && P("loginShortcut") && !loggedIn() && !chromeState.tight;
    if (wantLogin && !chromeState.login) {
      var lg = chromeButton("login", "", "lock");
      lg.title = "Log in or register — this opens the site's own account screen.";
      lg.addEventListener("click", function (e) {
        e.preventDefault();
        e.stopPropagation();
        openAccount();
      });
      cluster.insertBefore(lg, insertAt);
      chromeState.login = lg;
    } else if (!wantLogin && chromeState.login) {
      dropChrome("login");
    }

    var wantBl = live && P("showBlChip") && loggedIn() && !chromeState.tight;
    if (wantBl && !chromeState.bl) {
      var bl = chromeButton("bl", "BL: off");
      bl.addEventListener("click", function (e) {
        e.preventDefault();
        e.stopPropagation();
        toggleReveal(bl);
      });
      cluster.insertBefore(bl, insertAt);
      chromeState.bl = bl;
    } else if (!wantBl && chromeState.bl) {
      dropChrome("bl");
    }
    if (chromeState.bl) blLabel(chromeState.bl);
    collapseLabels();
    keepOneRow(cluster);
    syncHeaderOffset();
  }

  /* The header has to stay one row tall on a phone. If it does not fit, the mod's own chips
     step out first — the site's buttons are never clipped and never removed — and they come
     back when the header is wide enough again.

     The cluster the site gives us wraps (`flex-wrap`), and that is what hid this from the first
     version of the check: a wrapped row reports no horizontal overflow at all — `scrollWidth`
     stays exactly `clientWidth` while the header grows a second row. Measuring only the width
     therefore reported "it fits" on a header that had visibly spilled onto two rows, and the
     compaction never ran. So the row count is measured as well, from the vertical centres of
     the children that have a box. Where no layout engine can answer (a test stand-in reports
     zero-sized boxes for everything), nothing is measurable, the count comes back as 0, and the
     overflow test is the only signal there is — which is what the old code had. */
  function keepOneRow(cluster) {
    var HELPERS = [NS + "-tight", NS + "-one-row"];
    var stripHelpers = function () { HELPERS.forEach(function (c) { cluster.classList.remove(c); }); };
    var helperChildren = function (n) {
      return n.classList && (n.classList.contains(NS + "-chip") || n.hasAttribute("data-" + NS + "-chrome"));
    };
    var overflows = function () { return cluster.scrollWidth > cluster.clientWidth + 1; };
    /* `scrollWidth` is not enough on its own, in either direction. This cluster is
       `justify-end`, so a row that does not fit spills off the start edge, and a leftward
       spill in a left-to-right page is not part of the scrollable area at all: `scrollWidth`
       keeps answering "it fits" while `overflow: hidden` cuts a site button out of the
       header — measured live, the site's own AI button vanished and its neighbour came back as
       "wd 0". So the children are compared against the cluster's own box instead. */
    var spills = function () {
      if (!cluster.getBoundingClientRect) return false;
      var box = cluster.getBoundingClientRect(), n, r;
      for (n = cluster.firstElementChild; n; n = n.nextElementSibling) {
        if (!n.getBoundingClientRect) continue;
        r = n.getBoundingClientRect();
        if (!(r.width > 0) || !(r.height > 0)) continue;
        if (r.left < box.left - 1 || r.right > box.right + 1) return true;
      }
      return false;
    };
    var rows = function () {
      var bands = [], n, k, r, mid, seen;
      if (!cluster.firstElementChild) return 0;
      for (n = cluster.firstElementChild; n; n = n.nextElementSibling) {
        if (!n.getBoundingClientRect) continue;
        r = n.getBoundingClientRect();
        if (!r || !(r.width > 0) || !(r.height > 0)) continue;
        mid = r.top + r.height / 2; seen = false;
        for (k = 0; k < bands.length; k++) {
          if (Math.abs(bands[k] - mid) <= 8) { seen = true; break; }
        }
        if (!seen) bands.push(mid);
      }
      return bands.length;
    };
    var cramped = function () { return overflows() || spills(); };
    var fits = function () { if (cramped()) return false; return rows() <= 1; };

    /* the signature: the room the header has, and the site's own buttons in it. Our chips and
       our helper classes are deliberately left out — they are what this function decides about,
       and counting them in the measurement is how the decision fed itself. */
    /* The key that decides whether the room has to be measured again: the room's own width, the
       buttons of the site's that stand in it, and the switches that decide what the header is
       asked to hold. Deliberately left out: the measured width of each button and the wording it
       carries. A phone browser fires resize every time its address bar slides in or out — the
       height changes, the width does not — and re-deciding on a height-only change is what made
       the header flip between one row and two on every scroll, its labels flipping with it and
       the drawer offset lagging behind. Same room, same buttons, same switches: the decision
       stands until the room itself changes. */
    var signature = function () {
      /* The room the header has AND what the row asks of it, both measured with our own helper
         classes already taken off: scrollWidth is the demand the header would have without the
         squeeze, so it says the same thing whatever plan was last applied and cannot feed itself.
         What is deliberately left out: the width of each button and the wording it carries. A phone
         browser fires resize every time its address bar slides in or out — the height changes, the
         width and the demand do not — and re-deciding on a height-only change is what made the
         header flip between one row and two on every opposite scroll, its labels with it. */
      var parts = [Math.round(cluster.clientWidth || 0), Math.round(cluster.scrollWidth || 0)];
      var n;
      for (n = cluster.firstElementChild; n; n = n.nextElementSibling) {
        if (helperChildren(n)) continue;
        parts.push(n.id || String(n.className || "").slice(0, 24) || "boxless");
      }
      parts.push((P("headerCompact") ? "c" : "-") + (P("showBlChip") && loggedIn() ? "b" : "-") +
        (P("loginShortcut") && !loggedIn() ? "l" : "-") + (P("enabled") ? "" : "x"));
      return parts.join("|");
    };

    var applyPlan = function (plan) {
      if (plan <= 0) { cluster.classList.remove(NS + "-tight"); cluster.classList.remove(NS + "-one-row"); return; }
      cluster.classList.add(NS + "-tight");
      if (plan >= 2) cluster.classList.add(NS + "-one-row");
      if (plan >= 3 && chromeState.bl) dropChrome("bl");
      if (plan >= 4 && chromeState.login) dropChrome("login");
      chromeState.tight = plan >= 3;
    };

    stripHelpers();
    var stored = signature();
    if (stored === chromeState.signature && chromeState.plan >= 0) { applyPlan(chromeState.plan); return; }
    chromeState.signature = stored;

    /* A cluster whose children report no box at all (a test stand-in with no layout engine)
       reports 0 rows and no spill, which leaves the overflow test as the only signal — the
       same footing the earlier versions had. */
    if (fits()) { chromeState.plan = 0; applyPlan(0); return; }
    /* first squeeze the row's own spacing and label size: nothing leaves the header */
    cluster.classList.add(NS + "-tight");
    if (fits()) { chromeState.plan = 1; return; }
    /* still spilled: unwrap the row so it can be measured as one line, and see whether the
       squeeze was enough. `overflow: hidden` only ever goes on a row that fits. */
    cluster.classList.add(NS + "-one-row");
    if (!cramped()) { chromeState.plan = 2; return; }
    /* unwrapping made it worse, not better: something of ours has to leave, and `-one-row`
       comes back off before any of the site's buttons is cut */
    cluster.classList.remove(NS + "-one-row");
    if (chromeState.bl) {
      dropChrome("bl"); chromeState.tight = true;
      cluster.classList.add(NS + "-one-row");
      if (cramped()) { cluster.classList.remove(NS + "-one-row"); chromeState.plan = 4; return; }
      chromeState.plan = 3;
      return;
    }
    if (chromeState.login) {
      dropChrome("login"); chromeState.tight = true;
      cluster.classList.add(NS + "-one-row");
      if (cramped()) { cluster.classList.remove(NS + "-one-row"); chromeState.plan = 4; return; }
      chromeState.plan = 4;
      return;
    }
    /* nothing of ours is left and it still does not fit on one line: the site's own header
       stays exactly as the site lays it out. A wrapped header is ugly; a header with a clipped
       site button is a button that no longer works. */
    cluster.classList.remove(NS + "-tight");
    cluster.classList.remove(NS + "-one-row");
    chromeState.tight = false;
    chromeState.plan = 0;
    chromeState.signature = "";   /* nothing was measured: the next pass has to measure again */
  }

  /* ─────────── the list: the site's own controls, repeated ───────────
     The paginator sits under the cards and the search box lives in the drawer, so on a phone
     page two means scrolling to the bottom and a new search means opening a drawer. Both
     features here are clones of the site's control, not new controls: same markup, the same
     wiring, and a tap that forwards to the original. */

  var galleryState = { pager: null, pagerSrc: null, search: null, searchSrc: null, bar: null };
  var dupWatchers = {};

  function dropDupClass(cls) {
    [].slice.call(document.querySelectorAll("." + cls)).forEach(function (n) {
      if (n.parentNode) n.parentNode.removeChild(n);
    });
  }

  function pagerSource() {
    var wrap = document.getElementById("gallery-pagination-wrap");
    if (wrap) return wrap;
    var prev = document.getElementById("prev-page-btn");
    return prev && prev.parentNode ? prev.parentNode : null;
  }

  function buildDupPager(grid) {
    var src = pagerSource();
    if (!src) {
      /* no paginator on this screen (unlimited mode, or a random grid with a load-more
         button): a copy of a control that is not there would do nothing */
      dropDupClass(NS + "-pager-dup");
      galleryState.pager = null;
      galleryState.pagerSrc = null;
      return null;
    }
    if (galleryState.pager && galleryState.pager.parentNode && galleryState.pagerSrc === src) return galleryState.pager;
    var made = makeDup(src, { cls: NS + "-pager-dup" });
    if (!made) return null;
    if (galleryState.pager && galleryState.pager.parentNode) dropDupClass(NS + "-pager-dup");
    grid.parentNode.insertBefore(made.copy, grid);
    galleryState.pager = made.copy;
    galleryState.pagerSrc = src;
    mirrorDup(src, made.copy, { textIds: ["gallery-total-pages"] });
    if (dupWatchers.pager) { try { dupWatchers.pager.disconnect(); } catch (e) { /* already gone */ } }
    dupWatchers.pager = watchDup("pager", src, made.copy, { textIds: ["gallery-total-pages"] });
    return made.copy;
  }

  /* The search box is duplicated as its two controls — the input and the advanced toggle — not
     as the drawer around them.

     Both panels the site opens from that box — the tag suggestions and the advanced search
     panel — live INSIDE the drawer (#sidebar), and the drawer is a fixed element the site moves
     with a transform. A transformed ancestor is the containing block for a fixed descendant, so
     a panel left there is positioned inside a box that is off the screen: the copied box could
     be typed into, the site could build its list, and the list appeared 288 px to the left of
     the phone. The advanced toggle had the same problem in a plainer way — it opened a panel
     that was there and not on the page. So while a copied box is in use and the drawer is shut,
     both panels are lifted out of the drawer: the advanced panel into the copied box's own row
     (where it simply sits, no positioning to guess), the suggestions list onto the document, so
     its own fixed positioning means what it says. When the drawer opens, both go back exactly
     where they were. One suggestions list, one advanced panel, one set of wiring — the site's. */
  var searchMoved = {};
  var searchMirrorTimer = 0;
  var searchMirrorValue = null;
  var panelWatch = null;
  var placeLast = "";

  function panelVisible(node) {
    if (!node) return false;
    if (node.hidden) return false;
    if (node.hasAttribute && node.hasAttribute("hidden")) return false;
    return !/(^|\s)hidden(\s|$)/.test(String(node.className || ""));
  }

  function searchOriginal() { return document.getElementById("search"); }
  function searchCopy() {
    return document.querySelector("." + NS + "-search-dup [" + "data-" + NS + "-dup-of=\"search\"]");
  }
  function searchCopyWrap() { return document.querySelector("." + NS + "-search-dup"); }

  function liftPanel(node, host) {
    if (!node || !host) return;
    var moved = searchMoved[node.id];
    if (moved) {
      if (moved.node.parentNode === host) return;
      /* already lifted elsewhere: put it home first so the home slot is remembered once */
      restorePanel(node);
    }
    var parent = node.parentNode;
    if (!parent) return;
    searchMoved[node.id] = { node: node, home: parent, next: node.nextSibling };
    host.appendChild(node);
  }

  function restorePanel(node) {
    var moved = searchMoved[node && node.id];
    if (!moved || !moved.home) return;
    if (moved.node.parentNode === moved.home) { delete searchMoved[node.id]; return; }
    moved.home.insertBefore(moved.node, moved.next && moved.next.parentNode === moved.home ? moved.next : null);
    delete searchMoved[node.id];
  }

  function restoreSearchPanels() {
    restorePanel(document.getElementById("search-tag-suggestions"));
    restorePanel(document.getElementById("advanced-search-panel"));
  }

  /* Which box the panels belong under: the one the viewer is actually using. */
  function panelAnchor() {
    var src = searchOriginal();
    var copy = searchCopy();
    var active = document.activeElement;
    if (copy && active === copy) return copy;
    if (src && active === src && !drawerOpen()) return src;
    return copy || src || null;
  }

  function placeSearchPanels() {
    var drop = document.getElementById("search-tag-suggestions");
    var adv = document.getElementById("advanced-search-panel");
    var copy = searchCopy();
    var open = drawerOpen();

    /* the drawer is showing its own box: the site may lay its panels out inside it */
    if (!copy || open) { restoreSearchPanels(); return; }
    if (drop && panelVisible(drop)) liftPanel(drop, document.body);
    if (adv) liftPanel(adv, searchCopyWrap());

    if (!drop || !panelVisible(drop)) return;
    var box = panelAnchor();
    if (!box || !box.getBoundingClientRect) return;
    var r = box.getBoundingClientRect();
    if (!r.width) return;
    var left = Math.round(r.left), top = Math.round(r.bottom + 4), wide = Math.round(r.width);
    var sig = left + "," + top + "," + wide;
    if (sig === placeLast) return;   /* our own write must not restart this watch */
    placeLast = sig;
    drop.style.left = left + "px";
    drop.style.top = top + "px";
    drop.style.minWidth = wide + "px";
  }

  var placeObserverTargets = null;
  function watchSearchPanels() {
    if (!window.MutationObserver) return;
    var drop = document.getElementById("search-tag-suggestions");
    var adv = document.getElementById("advanced-search-panel");
    var nodes = [drop, adv].filter(Boolean);
    var key = nodes.map(function (n) { return n.id; }).join(",");
    if (panelWatch && placeObserverTargets === key) return;
    if (panelWatch) { try { panelWatch.disconnect(); } catch (e) { /* already gone */ } }
    placeObserverTargets = key;
    panelWatch = new MutationObserver(function () { placeSearchPanels(); });
    nodes.forEach(function (n) {
      try { panelWatch.observe(n, { attributes: true, attributeFilter: ["class", "style", "hidden"] }); } catch (e) { /* an engine without an observer */ }
    });
    nodes.forEach(function (n) {
      try { panelWatch.observe(n.parentNode || document.body, { childList: true }); } catch (e) { /* ditto */ }
    });
  }

  /* A box the site keeps in a drawer it can rebuild at any moment is a box whose value the site
     writes through the value property, which no observer sees: a tag pill, a saved search, an
     advanced-panel chip, a clear. So the two boxes are matched on a slow timer while a copy is
     live, in whichever direction the change came from — the last agreed value decides whose
     text is the new one. */
  function startSearchMirror() {
    if (searchMirrorTimer) return;
    searchMirrorTimer = setInterval(function () {
      var src = searchOriginal();
      var copy = searchCopy();
      if (!src || !copy) { clearInterval(searchMirrorTimer); searchMirrorTimer = 0; return; }
      if (searchMirrorValue === null) searchMirrorValue = src.value;
      if (src.value !== searchMirrorValue) {
        searchMirrorValue = src.value;
        if (copy.value !== src.value) copy.value = src.value;
      } else if (copy.value !== searchMirrorValue) {
        searchMirrorValue = copy.value;
        src.value = copy.value;
        try { src.dispatchEvent(new Event("input", { bubbles: true })); } catch (e) { /* older engines */ }
      }
      placeSearchPanels();
    }, 250);
  }

  function stopSearchMirror() {
    if (!searchMirrorTimer) return;
    clearInterval(searchMirrorTimer);
    searchMirrorTimer = 0;
    searchMirrorValue = null;
  }

  function buildDupSearch(grid) {
    var input = searchOriginal();
    var toggle = document.getElementById("advanced-search-toggle");
    if (!input) { dropDupClass(NS + "-search-dup"); restoreSearchPanels(); stopSearchMirror(); galleryState.search = null; return null; }
    if (galleryState.search && galleryState.search.parentNode && galleryState.searchSrc === input) {
      mirrorSearch(input, toggle, galleryState.search);
      placeSearchPanels();
      return galleryState.search;
    }
    var wrap = el("div", NS + "-search-dup");
    var ci = dupOne(input);
    if (!ci) { dropDupClass(NS + "-search-dup"); galleryState.search = null; return null; }
    /* a clone carries the value attribute, not the value the site has been typing into the
       original: without this the copy starts out disagreeing with the box it mirrors */
    ci.value = input.value;
    searchMirrorValue = input.value;
    wrap.appendChild(ci);
    if (toggle) {
      var ct = dupOne(toggle);
      if (ct) { ct.removeAttribute("title"); wrap.appendChild(ct); }
    }
    if (galleryState.search && galleryState.search.parentNode) dropDupClass(NS + "-search-dup");
    grid.parentNode.insertBefore(wrap, grid);
    galleryState.search = wrap;
    galleryState.searchSrc = input;
    mirrorSearch(input, toggle, wrap);
    wireAdvancedRetarget(document.getElementById("advanced-search-panel"));
    watchSearchPanels();
    startSearchMirror();
    placeSearchPanels();
    return wrap;
  }

  /* Keep the copy and the original reading the same: the text in the box, the advanced panel's
     state on the copied toggle (its caret rotates under the site's own hand). */
  function mirrorSearch(input, toggle, copy) {
    if (!copy) return;
    var ci = copy.querySelector("[" + "data-" + NS + "-dup-of=\"search\"]");
    if (ci && input && typeof input.value === "string" && ci.value !== input.value) {
      ci.value = input.value;
      searchMirrorValue = input.value;
    }
    var srcLabel = toggle ? (toggle.textContent || "").trim() : null;
    var ct = copy.querySelector("[" + "data-" + NS + "-dup-of=\"advanced-search-toggle\"]");
    if (ct && srcLabel !== null && ct.textContent.trim() !== srcLabel) ct.textContent = srcLabel;
    var srcCaret = document.getElementById("advanced-search-caret");
    var ctCaret = copy.querySelector("[" + "data-" + NS + "-dup-of=\"advanced-search-caret\"]");
    if (srcCaret && ctCaret) {
      var want = srcCaret.style && srcCaret.style.transform ? srcCaret.style.transform : "";
      if ((ctCaret.style.transform || "") !== want) ctCaret.style.transform = want;
    }
  }

  /* A chip inside the advanced panel writes into the site's own box and focuses it — that box
     is in the drawer, off the screen, so the caret the site just placed is somewhere the viewer
     cannot see. A tap in the lifted panel hands the caret back to the copied box, at the end of
     the text the site just inserted. */
  function wireAdvancedRetarget(panel) {
    if (!panel || panel.getAttribute("data-" + NS + "-retarget")) return;
    panel.setAttribute("data-" + NS + "-retarget", "1");
    panel.addEventListener("click", function () {
      setTimeout(function () {
        var ci = searchCopy();
        var src = searchOriginal();
        if (!ci || !src || drawerOpen()) return;
        if (document.activeElement !== src) return;
        ci.focus();
        var end = ci.value.length;
        try { ci.setSelectionRange(end, end); } catch (e) { /* a box without a selection API */ }
        src.value = ci.value;
        searchMirrorValue = ci.value;
      }, 0);
    });
  }


  /* ─────────── a card's own text, fetched one card at a time ───────────
     The list gives every card a name, tags and stats, but not its text — so the media a card
     holds is simply not on the list. Reading it costs one request for that one card, which is
     why it waits for a tap on that card's own media button. Nothing in this script ever asks
     the site for a group of cards, and a card already read is not asked a second time. */

  var dataCache = {};

  function sleep(ms) { return new Promise(function (res) { setTimeout(res, ms); }); }

  async function fetchCard(id) {
    var token = null;
    try { token = localStorage.getItem("token"); } catch (e) { /* a manager without storage */ }
    var headers = { accept: "application/json" };
    if (token) headers.authorization = "Bearer " + token;
    var r = await fetch("/post/" + encodeURIComponent(id), {
      headers: headers,
      credentials: "same-origin",
    });
    if (!r.ok) {
      var why = "";
      try { var j = await r.json(); if (j && j.detail) why = String(j.detail); } catch (e) { /* no body to read */ }
      var err = new Error("http " + r.status + (why ? " " + why : ""));
      err.status = r.status;
      err.detail = why;
      throw err;
    }
    var body = await r.json();
    return body;
  }

  function cachedCard(id) { return dataCache[String(id)] || null; }

  /* One card's stored text, read one card at a time.
     The list gives every card a name, tags and stats but not its text, so the media a card
     holds is simply not on the list. Reading it costs one request for that card — which is why
     it happens only when somebody taps that card's own media button. No control here ever asks
     the site for a group of cards. */

  /* The one line a card's media button answers with, and the count the bar uses:
     I intro(s) · M/L links · G gallery
     I — the greetings the card stores: the first message plus every alternate greeting.
     M — the unique media links in the card's own text (a link twice is one link; the card's
         source links are not the creator's media and are not counted here).
     L — every unique link in that text, media or not, source links aside again.
     G — the card's mini-gallery. Nothing is dropped for being one, or for being none: a card
     with no greetings and no gallery is a card with no greetings and no gallery, and that is
     the answer the reader needs. */
  function mediaSummary(post) {
    var m = mediaOf(post);
    var intros = greetingCount(post);
    var gallery = miniGalleryCount(post);
    var parts = [
      intros + " " + introWord(intros),
      m.uniqueMedia + "/" + m.uniqueLinks + " " + LABELS.linksWord,
      gallery + " " + LABELS.galleryWord,
    ];
    var where = [];
    Object.keys(m.fields).forEach(function (key) {
      var f = m.fields[key];
      if (f && f.media) where.push(f.label);
    });
    return { text: parts.join(" \u00B7 "), where: where.join(", "), media: m.media, title: LABELS.mediaTitle(where.join(", ")) };
  }

  /* The media button: a full-width strip under the card's stats row, the same shape as the
     card's own "more ▾". It reads this one card, then toggles the line it produced. */
  function ensureMediaButton(tile) {
    if (!P("onDemandData") || !P("enabled")) return null;
    var info = tile.querySelector(":scope > [" + "data-" + NS + "-info]");
    if (!info) return null;
    var btn = info.querySelector(":scope > [" + "data-" + NS + "-read-card]");
    if (btn) return btn;

    var stats = info.querySelector("." + NS + "-stats");
    var node = stats;
    while (node && node.parentNode !== info) node = node.parentNode;
    var after = node ? node.nextSibling : null;

    btn = el("button", NS + "-read " + NS + "-more");
    btn.type = "button";
    btn.setAttribute("data-" + NS + "-read-card", "1");
    btn.textContent = LABELS.media;
    btn.title = LABELS.mediaAsk;

    var out = el("p", NS + "-read-out");
    out.hidden = true;

    function closeSheet() {
      out.hidden = true;
      btn.textContent = LABELS.media;
      btn.classList.remove(NS + "-read-open");
    }
    function show(post) {
      var s = mediaSummary(post);
      out.textContent = s.text;
      out.title = s.title;
      out.hidden = false;
      btn.textContent = LABELS.mediaOpen;
      btn.classList.add(NS + "-read-open");
    }

    btn.addEventListener("click", async function (e) {
      e.preventDefault();
      e.stopPropagation();
      if (!out.hidden) { closeSheet(); return; }
      var id = tile.getAttribute("data-post-id");
      if (!id) { out.textContent = LABELS.mediaNoId; out.hidden = false; return; }
      var hit = cachedCard(id);
      if (hit) { show(hit); return; }
      btn.textContent = LABELS.reading;
      btn.classList.add(NS + "-read-busy");
      try {
        var post = await fetchCard(id);
        dataCache[String(id)] = post;
      /* the payload a tap already brought back states the uploader too: remembered for that card's
         own turn in the list, at no extra cost */
      rememberCardUploader(id, post.uploader_id, post.uploader_name);
        show(post);
      } catch (err) {
        btn.textContent = LABELS.media;
        out.textContent = LABELS.mediaFail(err);
        out.hidden = false;
      }
      btn.classList.remove(NS + "-read-busy");
    });

    info.insertBefore(btn, after);
    info.insertBefore(out, btn.nextSibling);
    return btn;
  }
  /* how a swipe is recognised: a band along the left edge a touch may start in, a distance the
     finger travels to the right inside the gesture, and how much downward travel is still a
     swipe rather than a scroll.

     1.6 asked for 18 px of start, 45 px of travel and 400 ms of duration, and the gesture was
     wired through pointer events. Two of those three were never reachable on a phone. A touch
     that starts inside 18 px of the screen edge is inside the browser's own back-swipe zone, and
     the browser takes it: the pointer stream ends in a pointercancel, the track is cleared, and
     nothing is asked for. A 400 ms deadline rejects the deliberate, unhurried swipe a person
     actually makes when they mean to open a menu. And pointer events are the ones a scrolling
     page hands to its own scroller first. So the gesture now listens to touches directly, fires
     the moment the travel is unmistakably rightward, holds the browser off that gesture with a
     preventable touchmove, and also answers at the end of the touch if the travel was enough but
     the finger stopped short of a move event. Nothing here opens a drawer the site cannot open:
     it calls the site's own openSidebar(), and falls back to the site's own menu button. */
  var SWIPE_EDGE = 41;        /* px along the left edge a touch may start in (1.7.1: 20% wider) */
  var SWIPE_EDGE_MIN = 31;
  var SWIPE_MIN = 56;         /* px of rightward travel that means "open the menu" */
  var SWIPE_RATIO = 1.25;     /* vertical travel allowed against the horizontal travel */
  var swipeTrack = null;
  var swipeInstalled = false;

  function drawerOpen() {
    var s = document.getElementById("sidebar");
    if (!s) return false;
    if (/-translate-x-full/.test(String(s.className || ""))) return false;
    if (s.style && s.style.transform && /translateX\(-/.test(s.style.transform)) return false;
    return true;
  }

  function wideScreen() {
    /* the drawer is the site's phone control: on a wide screen there is no drawer to open.
       Asked the other way round on purpose — bail only when the engine says the screen is
       definitely wide, so an engine that cannot answer does not switch the gesture off. */
    try {
      if (window.matchMedia && window.matchMedia("(min-width: 1280px)").matches === true) return true;
    } catch (e) { /* no matchMedia here: leave the gesture available */ }
    return false;
  }

  function swipeBand() {
    var w = window.innerWidth || 0;
    var band = SWIPE_EDGE_MIN;
    if (w > 0) band = Math.max(band, Math.min(SWIPE_EDGE * 2, Math.round(w * 0.084)));
    return band;
  }

  function onOurOwnUI(target) {
    if (!target || !target.closest) return false;
    /* a touch that starts on one of our own controls is a tap on that control, never a swipe:
       the sheet, its tabs and its sliders, a card's text block, a chip, a copy of a site control */
    var ours = "input, textarea, select, button, ." + NS + "-gear, ." + NS + "-read-out, ." + NS + "-tag," +
      " ." + NS + "-more, ." + NS + "-dbar, ." + NS + "-panel, ." + NS + "-chip, ." + NS + "-search-dup, ." + NS + "-pager-dup";
    if (target.closest(ours)) return true;
    return !!target.closest("[" + "data-" + NS + "-info], [" + "data-" + NS + "-chrome], [" + "data-" + NS + "-panel]");
  }

  function swipeBegin(x, y, target) {
    if (!P("swipeDrawer") || !P("enabled")) return false;
    if (wideScreen()) return false;
    if (drawerOpen()) return false;                    /* an open drawer is not opened again */
    if (x > swipeBand()) return false;                 /* not the edge: a normal touch on a card */
    if (onOurOwnUI(target)) return false;
    swipeTrack = { x: x, y: y, dx: 0, dy: 0, fired: false };
    return true;
  }

  function openDrawer() {
    var w = pageWin();
    if (typeof w.openSidebar === "function") { try { w.openSidebar(); return true; } catch (e) { /* fall through to the button */ } }
    var btn = document.getElementById("hamburger-btn");
    if (btn && typeof btn.click === "function") { btn.click(); return true; }
    if (typeof w._openSidebar === "function") { try { w._openSidebar(); return true; } catch (e) { /* nothing left to ask */ } }
    return false;
  }

  /* Returns true when this move IS the gesture — and has already opened the drawer — so the
     caller can hold the browser off it. A gesture that has not travelled far enough yet does
     not touch the event: a scroll is a scroll, and stealing it is worse than missing a swipe. */
  function swipeMove(x, y) {
    if (!swipeTrack || swipeTrack.fired) return false;
    swipeTrack.dx = x - swipeTrack.x;
    swipeTrack.dy = y - swipeTrack.y;
    if (swipeTrack.dx < SWIPE_MIN) return false;
    if (Math.abs(swipeTrack.dy) > SWIPE_RATIO * swipeTrack.dx) { swipeTrack = null; return false; }  /* down or up: a scroll, not a swipe */
    swipeTrack.fired = true;
    var t = swipeTrack;
    swipeTrack = null;
    openDrawer();
    return true;
  }

  /* The forgiving end of the gesture: a swipe whose travel was right and long enough but whose
     last move event never arrived (a flick that the browser already handed to its own scroller)
     still counts, once, at the end of the touch. */
  function swipeEnd() {
    var t = swipeTrack;
    swipeTrack = null;
    if (!t || t.fired) return false;
    if (t.dx < SWIPE_MIN) return false;
    if (Math.abs(t.dy) > SWIPE_RATIO * t.dx) return false;
    t.fired = true;
    openDrawer();
    return true;
  }

  function installSwipe() {
    if (swipeInstalled) return true;
    if (!P("swipeDrawer") || !P("enabled")) return false;
    var hasTouch = "ontouchstart" in window || (window.PointerEvent && (window.matchMedia ? window.matchMedia("(pointer: coarse)").matches : false));
    if (!hasTouch && !window.PointerEvent) return false;
    swipeInstalled = true;

    if (hasTouch) {
      var point = function (e) {
        var t = (e.touches && e.touches[0]) || (e.changedTouches && e.changedTouches[0]) || null;
        return t ? { x: t.clientX, y: t.clientY } : null;
      };
      document.addEventListener("touchstart", function (e) {
        var p = point(e);
        if (!p) return;
        swipeBegin(p.x, p.y, e.target);
      }, { passive: true, capture: true });
      /* not passive: this is the one gesture on the page the mod is allowed to keep from the
         browser, and a passive listener cannot keep it */
      document.addEventListener("touchmove", function (e) {
        var p = point(e);
        if (!p) return;
        if (swipeMove(p.x, p.y) && e.cancelable) { try { e.preventDefault(); } catch (err) { /* already uncancelable */ } }
      }, { passive: false, capture: true });
      document.addEventListener("touchend", function () { swipeEnd(); }, { passive: true, capture: true });
      document.addEventListener("touchcancel", function () { swipeTrack = null; }, { passive: true, capture: true });
    }

    if (window.PointerEvent) {
      /* pen / stylus. Touch is already covered above, and a touch also streams pointer events:
         ignoring pointerType touch/pen keeps one gesture from being counted twice. */
      var handledElsewhere = function (e) { return !e || e.pointerType === "mouse" || e.pointerType === "touch"; };
      document.addEventListener("pointerdown", function (e) {
        if (handledElsewhere(e)) return;
        swipeBegin(e.clientX, e.clientY, e.target);
      }, { passive: true });
      document.addEventListener("pointermove", function (e) {
        if (handledElsewhere(e)) return;
        swipeMove(e.clientX, e.clientY);
      }, { passive: true });
      document.addEventListener("pointerup", function (e) {
        if (handledElsewhere(e)) return;
        swipeEnd();
      }, { passive: true });
      document.addEventListener("pointercancel", function () { swipeTrack = null; }, { passive: true });
    }
    return true;
  }

  function swipeOff() {
    /* the switch was turned off: the listeners stay registered but the gesture refuses to start,
       and any half-tracked swipe is dropped. Removing live capture listeners mid-page is the kind
       of thing that has bitten this script before; refusing at the door is enough. */
    swipeTrack = null;
  }


  function galleryChrome() {
    var grid = document.getElementById("gallery");
    if (!grid || !grid.parentNode || !P("enabled")) {
      dropDupClass(NS + "-pager-dup");
      dropDupClass(NS + "-search-dup");
      galleryState.pager = null;
      galleryState.search = null;
      /* with the copies gone there is nothing left to mirror into, and a panel this mod lifted
         out of the drawer has to be put back where the site keeps it */
      stopSearchMirror();
      restoreSearchPanels();
      return;
    }
    /* the order above the grid: the repeated search, then the repeated paginator */
    if (P("dupSearch")) {
      buildDupSearch(grid);
    } else {
      dropDupClass(NS + "-search-dup");
      stopSearchMirror();
      restoreSearchPanels();
    }
    if (P("dupPager")) buildDupPager(grid); else dropDupClass(NS + "-pager-dup");
    installSwipe();
  }

  /* A seam for the tests and for anyone debugging from the console: these are the very
     functions the page runs, not a second copy of them. Written onto the page's own window,
     because a sandboxed manager's window is invisible to DevTools. */
  function exposeApi() {
    try {
      pageWin()[NS + "_api"] = {
        version: VERSION,
        mediaOf: mediaOf,
        greetingCount: greetingCount,
        miniGalleryCount: miniGalleryCount,
        sauceCount: sauceCount,
        cachedCard: cachedCard,
        fetchCard: fetchCard,
        mediaSummary: mediaSummary,
        lorebookStats: lorebookStats,
        notesSentence: notesSentence,
        buildDetailBar: buildDetailBar,
        buildTagRow: buildTagRow,
        rankChips: rankChips,
        catRank: catRank,
        chipCategory: chipCategory,
        profileOwner: profileOwner,
        uploaderFromCardPage: uploaderFromCardPage,
        uploaderChip: uploaderChip,
        markPageArt: markPageArt,
        markLayout: markLayout,
        holdsCards: holdsCards,
        uploaderRow: uploaderRow,
        uploaderName: uploaderName,
        rememberCardUploader: rememberCardUploader,
        uploaderLine: uploaderLine,
        uploaderIds: uploaderIds,
        uploaderNames: uploaderNames,
        drainUploaderLookups: drainUploaderLookups,
        installUploaderCapture: installUploaderCapture,
        uploaderPayloadUrl: uploaderPayloadUrl,
        readUploaderPayload: readUploaderPayload,
        stateShort: stateShort,
        prefs: function (key) { return key === undefined ? prefs.all() : prefs.get(key); },
        labels: LABELS,
        ui: { tab: uiTab, open: uiOpen, set: uiSet },
        panel: { open: openPanel, close: closePanel, isOpen: panelOpen },
        swipe: { begin: swipeBegin, move: swipeMove, end: swipeEnd, off: swipeOff, band: swipeBand, installed: function () { return swipeInstalled; } },
        search: { place: placeSearchPanels, copy: function () { return searchCopy; }, original: searchOriginal },
        headerChrome: headerChrome,
        galleryChrome: galleryChrome,
        chrome: chromeState,
        dup: { pager: function () { return galleryState.pager; }, search: function () { return galleryState.search; } },
      };

    } catch (e) { /* a frozen window: the features work without the seam */ }
  }

  /* ───────────────────────── the card's own page ─────────────────────────
     On a card's page the left column carries a block of full-width buttons — favourite,
     PNG, JSON, the tag-mode pair, the SillyTavern import — that measured 348px tall on a
     360px-wide phone: about a third of the screen before you even reach the tags. Two
     switches here: repeat those buttons directly under the pictures, where they are the
     first thing you want, and squeeze that block from a tall stack into one short row.
     Both change only where it sits and how it looks: every button stays the site's own. */

  var dupSync = null;

  function downloadBlock() {
    var node = document.getElementById("download-png-btn");
    node = node && node.parentNode;
    while (node && node !== document.body) {
      /* not the row one button sits in: the block that holds the whole group, recognised
         by what it contains rather than by its position, which is the thing the site's
         markup changes between builds */
      if (node.querySelector("#favorite-btn") && node.querySelector("#download-json-btn")) return node;
      node = node.parentNode;
    }
    return null;
  }

  function dupOf() {
    var all = document.querySelectorAll("." + NS + "-dl-dup");
    for (var i = 0; i < all.length; i++) if (all[i].parentNode) return all[i];
    return null;
  }

  function dropDup() {
    [].slice.call(document.querySelectorAll("." + NS + "-dl-dup")).forEach(function (n) {
      if (n.parentNode) n.parentNode.removeChild(n);
    });
    if (dupSync) {
      try { dupSync.disconnect(); } catch (e) { /* already gone */ }
      dupSync = null;
    }
  }

  /* The site wires these buttons by their ids — an addEventListener inside its own code,
     no inline onclick — and an id may exist only once in a document. So the copy hands
     its ids over (remembered as data-bbx-dup-of) and answers a tap by clicking the real
     button it was copied from. Forwarding through the element captured at build time,
     never through a fresh getElementById, keeps the site's lookups pointed at the
     original and makes it impossible for a copy to trigger a copy. */
  /* Where the repeated buttons belong: directly under the pictures. The site keeps its own
     block further down the column — on a 360×720 phone it measured 867px before the first
     thing you actually tap. Walking up from the artwork to the level that also holds the
     card's name gives the slot immediately after the artwork; if the artwork and the name
     live in different columns, the old slot is used instead. */
  function artHost() {
    var art = document.getElementById("post-image") || document.getElementById("post-video");
    if (!art) {
      var main = document.getElementById("main-content");
      art = main && main.querySelector("img");
    }
    var nameEl = document.getElementById("post-character-name");
    if (!art || !art.parentNode || !nameEl || !nameEl.parentNode) return null;
    var node = art;
    while (node.parentNode && node.parentNode !== nameEl.parentNode && node.parentNode !== document.body) {
      node = node.parentNode;
    }
    if (node.parentNode !== nameEl.parentNode) return null;
    return { host: node.parentNode, before: node.nextSibling, name: nameEl };
  }

  function buildDup(block) {
    dropDup();
    var nameEl = document.getElementById("post-character-name");
    var at = artHost();
    var host = at ? at.host : (nameEl && nameEl.parentNode);
    var before = at ? at.before : nameEl;
    if (!host) return;

    var made = makeDup(block, { cls: NS + "-dl-dup" });
    if (!made) return;
    var dup = made.copy;
    host.insertBefore(dup, before);

    /* The favourite count, the favourite button's colour and the chosen tag mode change
       under the site's own hands; mirror them so the two can never disagree. */
    dupSync = watchDup("dl", block, dup, { classes: true, textIds: ["fav-count", "fav-label"] });
  }

  /* One compact bar of facts above the duplicated buttons, on a card's own page: what the
     card holds and where it holds it. It reads the card the site has already loaded — the
     page's own window.currentPostDetail, reached through pageWin(), since a sandboxed
     manager hands the script a window that does not carry it — and asks the site for nothing.
     When that card is not in the page — still loading, or hidden by an NSFW/NSFL/login rule —
     the bar is not built at all, because a bar of guesses about somebody's card is worse than
     no bar. */

  function detailBarHost() {
    var dup = document.querySelector("." + NS + "-dl-dup");
    if (dup && dup.parentNode) return { host: dup.parentNode, before: dup };
    var at = artHost();
    if (at) return { host: at.host, before: at.before };
    var nameEl = document.getElementById("post-character-name");
    if (nameEl && nameEl.parentNode) return { host: nameEl.parentNode, before: nameEl };
    return null;
  }

  function dropDetailBar() {
    [].slice.call(document.querySelectorAll("[" + "data-" + NS + "-dbar]")).forEach(function (n) {
      if (n.parentNode) n.parentNode.removeChild(n);
    });
  }



  function buildDetailBar(post) {
    var m = mediaOf(post);
    var intros = greetingCount(post);
    var books = lorebookStats(post);
    var bar = el("div", NS + "-dbar");
    bar.setAttribute("data-" + NS + "-dbar", "1");

    var facts = [];
    if (intros > 0) {
      var introText = intros + " " + introWord(intros);
      var introTitle = LABELS.barIntroTitle;
      if (m.greetMedia > 0) {
        introText += " (" + LABELS.barWithMedia(m.greetMedia) + ")";
        introTitle += " \u00B7 " + LABELS.barIntroMediaTitle;
      }
      facts.push({ text: introText, title: introTitle });
    }
    if (books.count > 0) {
      var loreText = books.count + " " + lorebookWord(books.count);
      var loreTitle = LABELS.barLoreTitle;
      if (books.tokens > 0) {
        loreText += " (" + bigNumber(books.tokens) + " " + LABELS.tokensTotal + ")";
        loreTitle += " \u00B7 " + bigNumber(books.tokens) + " " + LABELS.tokensTotal;
      }
      facts.push({ text: loreText, title: loreTitle });
    }
    var notes = notesSentence(m);
    if (notes) facts.push({ text: notes, title: LABELS.barNotesTitle });

    if (facts.length) {
      var line = el("span", NS + "-dbar-text");
      facts.forEach(function (f, i) {
        if (i) line.appendChild(document.createTextNode(" \u00B7 "));
        var s = el("span", NS + "-dbar-fact", f.text);
        s.setAttribute("title", f.title);
        line.appendChild(s);
      });
      bar.appendChild(line);
    }

    var fields = [];
    Object.keys(m.fields).forEach(function (key) {
      var f = m.fields[key];
      if (!f || (!f.links && !f.media)) return;
      fields.push({ label: f.label, links: f.links, media: f.media });
    });
    /* Which field holds what, and what this viewer does not render, is still computed — it is a
       fact about the card. What is gone is the row in the layout: an expander bolted onto a bar
       whose whole job is one line. The breakdown now rides on the bar's own title, where a
       press-and-hold answers it with no control to find and no second state to remember. */
    var help = [];
    Object.keys(m.fields).forEach(function (key) {
      var fl = m.fields[key];
      if (!fl || (!fl.links && !fl.media)) return;
      help.push(LABELS.barFieldLine(fl.label, fl.links, fl.media));
    });
    if (help.length) {
      help.push(LABELS.barCountedLine);
      bar.setAttribute("title", help.join(" \u00B7 "));
    }
    return bar.childNodes.length ? bar : null;
  }

  function detailBar() {
    var post = pageWin().currentPostDetail;
    if (!P("detailBar") || !post || !post.id) { dropDetailBar(); return null; }
    var key = String(post.id) + ":" + String(post.content_updated_at || "");
    var live = document.querySelector("[" + "data-" + NS + "-dbar]");
    if (live && live.getAttribute("data-" + NS + "-bar-key") === key) return live;
    if (live) dropDetailBar();
    var at = detailBarHost();
    if (!at) return null;
    var bar = buildDetailBar(post);
    at.host.insertBefore(bar, at.before);
    return bar;
  }

  /* A card's own page frames its main picture: the site caps the frame and the image at 85vh and
     locks the frame's aspect ratio to 0.5–2, so a tall portrait is cropped and nothing on the
     page asks for the whole picture. The frame is marked and the stylesheet releases both — the
     caps and the site's own inline aspect lock, which is a write rather than a class and therefore
     needs the rules written !important.

     No setting: an artwork shown at a height someone else picked is not a preference the owner
     could want the other way. A video keeps its frame, because a cap there is what keeps a video
     page usable. */
  function markPageArt() {
    var img = document.getElementById("post-image");
    if (!img || !img.parentNode || img.parentNode.nodeType !== 1) return false;
    var frame = img.parentNode;
    if (!frame.classList.contains(NS + "-page-art-frame")) frame.classList.add(NS + "-page-art-frame");
    return true;
  }

  /* Who made this card, at the top of the card's info, from the one place the page already states
     it: the site's own #post-uploader names the uploader and links their profile. It is added as a
     chip in the card's tag look — the writer's orange over the copyright tag's magenta frame — so
     it reads as one of the card's own tags and sits where a reader looks for the maker. Nothing is
     fetched for it, and nothing is guessed: no #post-uploader, no chip. */
  function uploaderRow() {
    var live = document.querySelector("[" + "data-" + NS + "-uploader]");
    var up = uploaderFromCardPage();
    if (!up) { if (live && live.parentNode) live.parentNode.removeChild(live); return null; }
    var nameEl = document.getElementById("post-character-name");
    if (!nameEl || !nameEl.parentNode) { if (live && live.parentNode) live.parentNode.removeChild(live); return null; }
    if (live && live.parentNode === nameEl.parentNode && live.textContent === up.name) return live;
    if (live && live.parentNode) live.parentNode.removeChild(live);
    var row = el("div", NS + "-uploader-row");
    row.setAttribute("data-" + NS + "-uploader", "1");
    row.appendChild(uploaderChip(up.name, up.href, LABELS.chipProfileTitle(up.name)));
    nameEl.parentNode.insertBefore(row, nameEl.nextSibling);
    return row;
  }

  function dropUploaderRow() {
    [].slice.call(document.querySelectorAll("[" + "data-" + NS + "-uploader]")).forEach(function (n) {
      if (n.parentNode) n.parentNode.removeChild(n);
    });
  }

  function detailPass(force) {
    if (!P("enabled")) { dropDup(); dropDetailBar(); dropUploaderRow(); return; }
    markPageArt();
    uploaderRow();
    var block = downloadBlock();
    if (!block) { dropDup(); dropDetailBar(); dropUploaderRow(); return; }
    block.classList.add(NS + "-dl-block");
    var dup = dupOf();
    if (!P("dlDuplicate")) { if (dup) dropDup(); }
    else if (!dup || force) buildDup(block);
    detailBar();
  }

  /* ───────────────────────── scanning ───────────────────────── */

  var scanQueued = false;
  var pendingRoots = null;

  /* Mark the three things the layout CSS needs, once per card. The gallery is one grid; a
     creator's profile has its own grids, and there the card is not the grid item — a
     <div class="relative"> holding the card plus the site's pin button is. Walking up from
     the card finds the nearest grid and remembers the child we came through, which is exactly
     the grid item. A card that is not inside a grid of cards (a list somewhere, or a layout
     grid that merely happens to hold one) gets .bbx-card only, which is still enough for the
     hover-zoom switch. The site marks its own grids with the utility class "grid", so that
     is the first thing to look for; the computed display is the fallback for a grid styled
     some other way. */
  function isGrid(n) {
    if (n.classList.contains(NS + "-grid") || n.id === "gallery") return true;
    if (/(^|\s)grid(\s|$)/.test(n.className || "")) return true;
    var d = window.getComputedStyle ? window.getComputedStyle(n).display : "";
    return d === "grid" || d === "inline-grid";
  }

  /* Is this grid a grid OF CARDS, or a page layout that merely happens to hold one?
     A grid holding two or more cards is a card grid. So is a grid whose every child holds a
     card, however few cards it holds: a profile that shows one pinned upload, or one upload
     full stop, is still a card grid, and 1.6 refused to mark it — which is how a lone card on
     a profile came out wearing none of the owner's settings while the rest of the page wore
     them. A page-layout grid has children that hold no card at all, so it is still left alone
     rather than being treated as a one-item card grid. */
  function holdsCards(grid) {
    var holds = 0, everyChildHolds = true, kid;
    for (kid = grid.firstElementChild; kid; kid = kid.nextElementSibling) {
      if (!kid.classList) continue;
      /* the rows the mod put in this grid are not the site's items */
      if (kid.classList.contains(NS + "-title") || kid.hasAttribute("data-" + NS + "-info")) continue;
      var isCard = !!kid.matches && kid.matches("a[" + "data-post-id" + "]");
      var holder = isCard ? kid : (kid.querySelector ? kid.querySelector("a[" + "data-post-id" + "]") : null);
      if (holder) holds++; else everyChildHolds = false;
    }
    return holds >= 2 || everyChildHolds;
  }

  function markLayout(tile) {
    /* Once per card, stamped: this is a DOM walk, and re-walking on every mutation batch is how
       a long list starts costing time on every scroll. */
    if (tile.getAttribute("data-" + NS + "-layout")) return;
    tile.classList.add(NS + "-card");
    var grid = null;
    var item = tile;
    var n = tile.parentNode;
    /* The card IS the grid item in the gallery. On a creator's profile it is not: there the item
       is a <div class="relative"> holding the card plus the site's own pin button, so the card's
       immediate parent is display:block with no "grid" in its class list. Reading only the parent
       — which is what 1.7.0 did — found no grid at all on a profile, so .bbx-grid, .bbx-item and
       the card's own .bbx-card never landed, and every rule the layout section writes (columns,
       gaps, card width, artwork ratio) is keyed on exactly those classes: the whole section went
       silent on /profile/* while it kept working on /posts/. Walking up — at most five steps, so a
       page-layout grid far above cannot be mistaken for the card's own — finds the grid and
       remembers the child we came through, which is precisely the grid item. */
    for (var depth = 0; n && n.nodeType === 1 && n !== document.documentElement && depth < 5; n = n.parentNode, depth++) {
      if (!isGrid(n)) { item = n; continue; }
      /* a grid of cards, not a page layout that merely contains one card */
      if (!holdsCards(n)) break;
      grid = n;
      break;
    }
    if (grid) {
      grid.classList.add(NS + "-grid");
      item.classList.add(NS + "-item");
    }
    tile.setAttribute("data-" + NS + "-layout", "1");
  }

  function scan(root) {
    if (!P("enabled")) return;
    var scope = root && root.querySelectorAll ? root : document;
    var tiles = scope.querySelectorAll("a[data-post-id]");
    for (var i = 0; i < tiles.length; i++) { markLayout(tiles[i]); processTile(tiles[i]); }
    // a tile that is itself the mutation target
    if (root && root.matches && root.matches("a[data-post-id]")) { markLayout(root); processTile(root); }
    /* ids the page stated since the last pass, looked up in one capped batch */
    drainUploaderLookups();
  }

  /* Header and list chrome, refreshed on the same coalesced batch as the cards. Both are
     idempotent, so a batch that changes nothing re-does nothing, and a failure here must
     never take the card work down with it. */
  function chromePass() {
    headerChrome();
    galleryChrome();
    /* The left-edge gesture belongs to the page, not to one view of it: a card's own page and a
       creator's profile carry no #gallery, and 1.6 installed the gesture only where a gallery
       existed — so an owner reading a card had no swipe at all, and the only way back to the menu
       was to find a page that had one. */
    installSwipe();
  }

  function queueScan(root) {
    // Collect every root mutated in this frame: coalescing to just the first one
    // would skip the other tiles added in the same frame.
    if (root && root.nodeType === 1) {
      if (!pendingRoots) pendingRoots = [];
      if (pendingRoots.indexOf(root) === -1) pendingRoots.push(root);
    }
    if (scanQueued) return;
    scanQueued = true;
    requestAnimationFrame(function () {
      scanQueued = false;
      var roots = pendingRoots || [];
      pendingRoots = null;
      if (!roots.length) { scan(document); detailPass(); chromePass(); return; }
      for (var i = 0; i < roots.length; i++) scan(roots[i]);
      detailPass();
      chromePass();
    });
  }

  function startObserver() {
    var mo = new MutationObserver(function (records) {
      for (var i = 0; i < records.length; i++) {
        var r = records[i];
        if (r.type === "childList") {
          // A card the site (re)renders: either it has not been processed yet — its
          // preview overlay may only now be arriving — or it was processed and our
          // block went away with the card's own markup. Re-check that one card;
          // processTile skips anything already done, so this cannot double up.
          var host = r.target && r.target.closest ? r.target.closest("a[data-post-id]") : null;
          if (host) {
            var stamped = host.getAttribute("data-" + NS + "-done");
            if (!stamped) {
              queueScan(host);
            } else if (stamped === "1" && !host.querySelector(":scope > [" + "data-" + NS + "-info" + "]")) {
              // processed, but our block went away with the card's own markup
              host.removeAttribute("data-" + NS + "-done");
              queueScan(host);
            }
          }
          for (var j = 0; j < r.addedNodes.length; j++) {
            var n = r.addedNodes[j];
            if (n.nodeType !== 1) continue;
            if (n.hasAttribute && n.hasAttribute("data-" + NS + "-info")) continue; // our own block
            if (n.classList && n.classList.contains(NS + "-gear")) continue;
            if (n.hasAttribute && (n.hasAttribute("data-" + NS + "-chrome") || n.hasAttribute("data-" + NS + "-dbar") ||
                n.hasAttribute("data-" + NS + "-data") || n.hasAttribute("data-" + NS + "-up"))) continue;
            if (n.hasAttribute && n.hasAttribute("data-" + NS + "-read-card")) continue;
            if (n.classList && (n.classList.contains(NS + "-chip") || n.classList.contains(NS + "-read") ||
              n.classList.contains(NS + "-read-out") || n.classList.contains(NS + "-pager-dup") ||
              n.classList.contains(NS + "-search-dup") || n.classList.contains(NS + "-expander") ||
              n.classList.contains(NS + "-extra") || n.classList.contains(NS + "-panel") ||
              n.classList.contains(NS + "-panel-top") || n.classList.contains(NS + "-tabs") ||
              n.classList.contains(NS + "-tab") || n.classList.contains(NS + "-tags") ||
              n.classList.contains(NS + "-uploader") || n.classList.contains(NS + "-dbar-text") ||
              n.classList.contains(NS + "-dbar-fact") || n.classList.contains(NS + "-page-art-frame"))) continue;
            queueScan(n);
          }
        }
      }
    });
    mo.observe(document.documentElement, { childList: true, subtree: true });
  }

  /* ───────────────────────── html classes from prefs ───────────────────────── */

  /* A pref that is a number, clamped into the range the slider offers: a stored
     "0" from an older build and a 0 from today have to mean the same thing. */
  function numPref(key, fallback, min, max) {
    var n = parseInt(P(key), 10);
    if (isNaN(n)) n = parseInt(fallback, 10);
    if (isNaN(n)) n = min;
    return Math.max(min, Math.min(max, n));
  }

  function applyClasses() {
    var root = document.documentElement;
    if (!root) return;
    var cols = String(P("phoneColumns"));
    root.classList.toggle(NS + "-hide-overlay", !!P("hideOverlay") && !!P("enabled"));
    root.classList.remove(NS + "-cols-1", NS + "-cols-2", NS + "-cols-full");
    if (cols === "1") root.classList.add(NS + "-cols-1");
    else if (cols === "2") root.classList.add(NS + "-cols-2");
    else if (cols === "full") root.classList.add(NS + "-cols-full");
    root.classList.remove(NS + "-s", NS + "-m", NS + "-l", NS + "-xl");
    root.classList.add(NS + "-" + (P("textSize") || "m"));
    root.classList.toggle(NS + "-off", !P("enabled"));
    root.classList.toggle(NS + "-touch", isTouchy());
    root.classList.toggle(NS + "-no-zoom", !!P("killHoverZoom"));
    root.classList.toggle(NS + "-dl-compact", !!P("dlCompact"));

    /* the gear's opacity is a plain 0–1 step; 0 leaves an invisible but still
       tappable button, and the userscript manager's menu is the way back */
    var op = numPref("gearOpacity", DEFAULTS.gearOpacity, PREF_RANGES.gearOpacity[0], PREF_RANGES.gearOpacity[1]);
    root.style.setProperty("--bbx-gear-op", String(op / 100));

    /* Space between cards: row-gap only, 0 leaves the site's own spacing alone. It
       behaves in every layout — two columns, one column, full width — because a row
       gap never touches the column widths or the cards inside them. */
    var gap = numPref("cardGap", DEFAULTS.cardGap, PREF_RANGES.cardGap[0], PREF_RANGES.cardGap[1]);
    root.classList.toggle(NS + "-gapped", gap > 0);
    /* the variable only stays on the document while it is actually in use, so a page
       with no extra spacing does not advertise a spacing it is not applying */
    if (gap > 0) root.style.setProperty("--bbx-card-gap", gap + "px");
    else root.style.removeProperty("--bbx-card-gap");

    /* The two size knobs only mean something in the one-column layouts, where the card
       is exactly as wide and as tall as its column lets it be; in the two-column grid
       the site's own cell already decides that. A width below 100% shrinks the card and
       centres it in the column it was given; a height replaces the picture's natural
       3:4 with that many pixels. */
    var oneCol = cols === "1" || cols === "full";
    var maxW = numPref("cardMaxWidth", DEFAULTS.cardMaxWidth, PREF_RANGES.cardMaxWidth[0], PREF_RANGES.cardMaxWidth[1]);
    var capped = oneCol && maxW < 100;
    root.classList.toggle(NS + "-capped", capped);
    if (capped) root.style.setProperty("--bbx-card-max-w", maxW + "%");
    else root.style.removeProperty("--bbx-card-max-w");

    var maxH = numPref("cardMaxHeight", DEFAULTS.cardMaxHeight, PREF_RANGES.cardMaxHeight[0], PREF_RANGES.cardMaxHeight[1]);
    var artCapped = oneCol && maxH > 0;
    root.classList.toggle(NS + "-artcap", artCapped);
    if (artCapped) root.style.setProperty("--bbx-art-h", maxH + "px");
    else root.style.removeProperty("--bbx-art-h");

    /* Keep the picture's own ratio is the opposite of an artwork height, so a card can only
       ever have one of the two: with a height set, the height wins and this switch is simply
       not applied (the panel says so next to the slider). */
    root.classList.toggle(NS + "-art-native", oneCol && !artCapped && !!P("artNative"));

    queueThumbs();
  }

  function isTouchy() {
    try {
      if (window.matchMedia && window.matchMedia("(hover: none)").matches) return true;
      if (window.matchMedia && window.matchMedia("(pointer: coarse)").matches) return true;
    } catch (e) { /* older engines */ }
    return "ontouchstart" in window;
  }

  /* ───────────────────────── settings UI ───────────────────────── */

  function field(labelText, control) {
    var row = el("div", NS + "-row");
    var lab = el("span", null, labelText);
    row.appendChild(lab);
    row.appendChild(control);
    /* A 20px checkbox is a small target for a thumb, so the whole row is the target:
       tapping anywhere in the row flips the switch. The input's own click is left
       alone, otherwise one tap would toggle twice. */
    if (control && control.type === "checkbox") {
      row.classList.add(NS + "-row-check");
      row.setAttribute("role", "switch");
      row.setAttribute("aria-checked", control.checked ? "true" : "false");
      row.addEventListener("click", function (e) {
        if (e.target === control) return;
        control.checked = !control.checked;
        control.dispatchEvent(new Event("change", { bubbles: true }));
      });
      control.addEventListener("change", function () {
        row.setAttribute("aria-checked", control.checked ? "true" : "false");
      });
    }
    return row;
  }

  function checkbox(value, onChange) {
    var c = el("input");
    c.type = "checkbox";
    c.checked = !!value;
    c.addEventListener("change", function () { onChange(c.checked); });
    return c;
  }

  function select(options, value, onChange) {
    var s = el("select");
    options.forEach(function (o) {
      var op = el("option", null, o.label);
      op.value = o.value;
      if (String(o.value) === String(value)) op.selected = true;
      s.appendChild(op);
    });
    s.addEventListener("change", function () { onChange(s.value); });
    return s;
  }

  function section(titleText) { return el("div", NS + "-sec", titleText); }
  function hint(text) { return el("div", NS + "-hint", text); }

  /* A slider row: the label, the track, and the number it currently stands at. Dragging
     applies as you go, so the card layout changes while your finger is still on it. */
  function sliderRow(labelText, min, max, step, value, format, onChange) {
    var row = el("div", NS + "-row");
    var n = parseInt(value, 10);
    if (isNaN(n)) n = min;
    n = Math.max(min, Math.min(max, n));
    row.appendChild(el("span", null, labelText));
    var s = el("input");
    s.type = "range";
    s.min = String(min); s.max = String(max); s.step = String(step); s.value = String(n);
    s.setAttribute("aria-label", labelText);
    var out = el("span", NS + "-val", format(n));
    var read = function () {
      var v = parseInt(s.value, 10);
      if (isNaN(v)) v = min;
      out.textContent = format(v);
      onChange(v);
    };
    s.addEventListener("input", read);
    s.addEventListener("change", read);
    row.appendChild(s);
    row.appendChild(out);
    return row;
  }

  /* The panel is a sheet floating over the page, so tapping anywhere outside it — or
     pressing Escape — closes it. It cannot then be left sitting on top of the cards. */
  var awayWatch = null;

  function panelOpen() {
    return document.querySelector("[" + "data-" + NS + "-panel" + "]");
  }

  function startAwayWatch() {
    if (awayWatch) return;
    awayWatch = function (e) {
      var panel = panelOpen();
      if (!panel) { stopAwayWatch(); return; }
      if (e.type === "keydown") {
        if (e.key === "Escape") closePanel();
        return;
      }
      var t = e.target;
      if (!t || t.nodeType !== 1) return;
      if (t.closest("[" + "data-" + NS + "-panel" + "]") || t.closest("." + NS + "-gear")) return;
      closePanel();
    };
    /* capture phase: we want the tap before the page acts on it, and we want it even
       when something below stops propagation */
    document.addEventListener("pointerdown", awayWatch, true);
    document.addEventListener("mousedown", awayWatch, true);
    document.addEventListener("keydown", awayWatch, true);
  }

  function stopAwayWatch() {
    if (!awayWatch) return;
    document.removeEventListener("pointerdown", awayWatch, true);
    document.removeEventListener("mousedown", awayWatch, true);
    document.removeEventListener("keydown", awayWatch, true);
    awayWatch = null;
  }

  /* Two preferences, one control: a block of text is either off, capped to a number of lines,
     or whole. The cap offered is the ladder the stylesheet really defines (2, 3, 4, 6, 8) and a
     stored value that is not on it is snapped, so an older install repairs itself the first
     time the sheet is opened. */
  /* "full" is one of the values these two settings hold, not a broken number. Reading it as NaN
     and snapping the NaN into the middle of the ladder is how a stored "full" came back as 3. */
  function snapCap(v, fallback) {
    if (v === "full") return "full";
    return nearestCap(parseInt(v, 10), fallback);
  }

  function lineSelect(showKey, linesKey, fallback, onChange) {
    var options = [{ value: "off", label: LABELS.lineOff }];
    CAP_STEPS.forEach(function (n) { options.push({ value: String(n), label: LABELS.lineCount(n) }); });
    options.push({ value: "full", label: LABELS.lineFull });
    var on = P(showKey);
    var stored = P(linesKey);
    var snapped = String(snapCap(stored, fallback));
    /* Write back only a value the control cannot show at all. A stored "full", or a stored number
       already on the ladder, is the reader's own choice and is left exactly as it is: writing a
       snapped value back on every rebuild is what rewrote settings while you browsed, because the
       sheet is rebuilt on navigation. */
    if (on && snapped !== String(stored)) prefs.set(linesKey, snapped);
    return select(options, on ? snapped : "off", function (v) {
      if (v === "off") prefs.set(showKey, false);
      else { prefs.set(showKey, true); prefs.set(linesKey, v); }
      onChange();
    });
  }

  /* The settings that are rarely touched are not in the sheet at all until you ask for them. */

  /* A folded group that forgets itself is the complaint this answers: the sheet was rebuilt from
     scratch every time it opened, and every group you had opened was closed again. Their state is
     stored with the rest of the settings now, so the sheet reopens the way you left it — the same
     rule the open tab follows.

     Built when it opens, kept built afterwards: a group that is only filled in on the first tap
     cannot be shown already open. */
  function expander(body, name, label, build) {
    var btn = el("button", NS + "-expander", label);
    btn.type = "button";
    var box = el("div", NS + "-extra");
    var open = uiOpen(name);
    btn.setAttribute("aria-expanded", open ? "true" : "false");
    btn.textContent = label + (open ? " \u25B4" : " \u25BE");
    if (open) build(box);
    box.hidden = !open;
    btn.addEventListener("click", function (e) {
      e.preventDefault();
      e.stopPropagation();
      var now = box.hidden;
      if (now && !box.childElementCount) build(box);
      box.hidden = !now;
      btn.setAttribute("aria-expanded", now ? "true" : "false");
      btn.textContent = label + (now ? " \u25B4" : " \u25BE");
      var opened = {};
      opened[name] = now;
      uiSet({ open: opened });
    });
    body.appendChild(btn);
    body.appendChild(box);
  }

  /* Which layout the card list is in right now. Card width, artwork height and the picture's own
     ratio only ever apply to a card that spans a whole column, and those are the 1-column layouts:
     the sheet says so instead of offering a slider that cannot do anything in this mode. */
  function oneColumnMode() {
    var c = P("phoneColumns");
    return c === "1" || c === "full";
  }

  function hoverChoiceValue() {
    if (P("hideOverlay") && P("killHoverZoom")) return "none";
    if (P("hideOverlay")) return "overlay";
    if (P("killHoverZoom")) return "zoom";
    return "site";
  }

  function applyHoverChoice(v) {
    prefs.set("hideOverlay", v === "overlay" || v === "none");
    prefs.set("killHoverZoom", v === "zoom" || v === "none");
  }

  /* The sheet is three tabs: what changes the card list, what changes a card's own page, and what
     changes the mod itself. A switch that can only do something in one of them is not offered in
     the others — the complaint was a sheet where half the rows belonged to a mode you were not in. */
  function tabStrip(host, body, active) {
    var strip = el("div", NS + "-tabs");
    ["list", "page", "ext"].forEach(function (key) {
      var btn = el("button", NS + "-tab", LABELS.tabs[key]);
      btn.type = "button";
      btn.setAttribute("role", "tab");
      btn.setAttribute("aria-selected", key === active ? "true" : "false");
      btn.addEventListener("click", function (e) {
        e.preventDefault();
        e.stopPropagation();
        if (key === active) return;
        uiSet({ tab: key });
        openPanel();
      });
      strip.appendChild(btn);
    });
    host.appendChild(strip);
    body.appendChild(hint(LABELS.tabHint[active]));
  }

  function buildListTab(body) {
    body.appendChild(field(LABELS.enabled, checkbox(P("enabled"), function (v) {
      prefs.set("enabled", v);
    })));
    if (!P("enabled")) body.appendChild(hint(LABELS.hintInfoOff));

    body.appendChild(section(LABELS.layout));
    body.appendChild(field(LABELS.phoneColumns, select([
      { value: "auto", label: LABELS.columns.auto },
      { value: "2", label: LABELS.columns["2"] },
      { value: "1", label: LABELS.columns["1"] },
      { value: "full", label: LABELS.columns.full },
    ], P("phoneColumns"), function (v) {
      prefs.set("phoneColumns", v);
      openPanel();   /* rebuild: the rows that only exist in 1-column mode come and go */
    })));
    body.appendChild(field(LABELS.textSize, select([
      { value: "s", label: LABELS.sizes.s }, { value: "m", label: LABELS.sizes.m },
      { value: "l", label: LABELS.sizes.l }, { value: "xl", label: LABELS.sizes.xl },
    ], P("textSize"), function (v) { prefs.set("textSize", v); })));
    body.appendChild(sliderRow(LABELS.cardGap, PREF_RANGES.cardGap[0], PREF_RANGES.cardGap[1], 2, P("cardGap"),
      function (v) { return v === 0 ? LABELS.gapSite : v + "px"; },
      function (v) { prefs.set("cardGap", v); }));

    if (oneColumnMode()) {
      expander(body, "cardSize", LABELS.secCardSize, function (box) {
        box.appendChild(sliderRow(LABELS.cardWidth, PREF_RANGES.cardMaxWidth[0], PREF_RANGES.cardMaxWidth[1], 5, P("cardMaxWidth"),
          function (v) { return v + "%"; }, function (v) { prefs.set("cardMaxWidth", v); }));
        box.appendChild(sliderRow(LABELS.artHeight, PREF_RANGES.cardMaxHeight[0], PREF_RANGES.cardMaxHeight[1], 20, P("cardMaxHeight"),
          function (v) { return v === 0 ? LABELS.artHeightAuto : v + "px"; }, function (v) { prefs.set("cardMaxHeight", v); }));
        box.appendChild(field(LABELS.artNative, checkbox(P("artNative"), function (v) {
          prefs.set("artNative", v);
        })));
        box.appendChild(field(LABELS.hiRes, checkbox(P("hiRes"), function (v) {
          prefs.set("hiRes", v); queueThumbs();
        })));
        box.appendChild(hint(LABELS.hintCardSize));
      });
    } else {
      body.appendChild(hint(LABELS.hintOneColumn));
    }

    body.appendChild(field(LABELS.hovering, select([
      { value: "site", label: LABELS.hoverChoices.site },
      { value: "overlay", label: LABELS.hoverChoices.overlay },
      { value: "zoom", label: LABELS.hoverChoices.zoom },
      { value: "none", label: LABELS.hoverChoices.none },
    ], hoverChoiceValue(), applyHoverChoice)));

    body.appendChild(section(LABELS.nameSection));
    body.appendChild(field(LABELS.nameAbove, checkbox(P("nameAbove"), function (v) {
      prefs.set("nameAbove", v);
      openPanel();   /* rebuild: the name moves between the picture and the info */
    })));
    body.appendChild(field(LABELS.marqueeName, checkbox(P("marqueeName"), function (v) {
      prefs.set("marqueeName", v);
    })));
    body.appendChild(hint(LABELS.hintName));

    body.appendChild(section(LABELS.textSection));
    body.appendChild(field(LABELS.showDesc, lineSelect("showDesc", "descLines", DEFAULTS.descLines, function () { })));
    body.appendChild(field(LABELS.showNotes, lineSelect("showNotes", "notesLines", DEFAULTS.notesLines, function () { })));
    body.appendChild(field(LABELS.notesFirst, checkbox(P("notesFirst"), function (v) { prefs.set("notesFirst", v); })));
    body.appendChild(field(LABELS.openCards, checkbox(P("openCards"), function (v) { prefs.set("openCards", v); })));
    body.appendChild(field(LABELS.moreBehavior, select([
      { value: "both", label: LABELS.moreTargets.both },
      { value: "desc", label: LABELS.moreTargets.desc },
      { value: "notes", label: LABELS.moreTargets.notes },
    ], P("moreBehavior"), function (v) { prefs.set("moreBehavior", v); })));
    body.appendChild(hint(LABELS.hintText));

    body.appendChild(section(LABELS.tagsSection));
    body.appendChild(field(LABELS.tagsOnCard, select([
      { value: "off", label: LABELS.tagsOff },
      { value: "2", label: LABELS.tagsCount(2) }, { value: "4", label: LABELS.tagsCount(4) },
      { value: "8", label: LABELS.tagsCount(8) }, { value: "0", label: LABELS.tagsAll },
    ], P("showTags") ? String(P("tagCap")) : "off", function (v) {
      prefs.set("showTags", v !== "off");
      if (v !== "off") prefs.set("tagCap", parseInt(v, 10));
    })));
    body.appendChild(field(LABELS.showStats, checkbox(P("showStats"), function (v) { prefs.set("showStats", v); })));
    body.appendChild(field(LABELS.cardUploader, checkbox(P("cardUploader"), function (v) {
      prefs.set("cardUploader", v);
    })));
    body.appendChild(hint(LABELS.hintUploader));

    body.appendChild(field(LABELS.onDemandData, checkbox(P("onDemandData"), function (v) { prefs.set("onDemandData", v); })));
    body.appendChild(hint(LABELS.hintOnDemand));

    expander(body, "siteCopies", LABELS.siteCopies, function (box) {
      box.appendChild(field(LABELS.dupPager, checkbox(P("dupPager"), function (v) { prefs.set("dupPager", v); })));
      box.appendChild(field(LABELS.dupSearch, checkbox(P("dupSearch"), function (v) { prefs.set("dupSearch", v); })));
      box.appendChild(hint(LABELS.hintSiteCopies));
    });
  }

  function buildPageTab(body) {
    body.appendChild(field(LABELS.dlDuplicate, checkbox(P("dlDuplicate"), function (v) {
      prefs.set("dlDuplicate", v);
    })));
    body.appendChild(field(LABELS.detailBar, checkbox(P("detailBar"), function (v) {
      prefs.set("detailBar", v);
    })));
    expander(body, "cardPage", LABELS.secCardPage, function (box) {
      box.appendChild(field(LABELS.dlCompact, checkbox(P("dlCompact"), function (v) {
        prefs.set("dlCompact", v);
      })));
    });
    body.appendChild(hint(LABELS.hintCardPage));
  }

  function buildExtTab(body) {
    body.appendChild(section(LABELS.headerSection));
    body.appendChild(field(LABELS.headerCompact, checkbox(P("headerCompact"), function (v) {
      prefs.set("headerCompact", v);
    })));
    body.appendChild(hint(LABELS.hintHeaderCompact));
    body.appendChild(field(LABELS.loginShortcut, checkbox(P("loginShortcut"), function (v) { prefs.set("loginShortcut", v); })));
    body.appendChild(field(LABELS.showBlChip, checkbox(P("showBlChip"), function (v) { prefs.set("showBlChip", v); })));

    /* the drawer is the site's phone control: on a wide screen there is no drawer to open, so the
       row is not offered there */
    if (wideScreen()) body.appendChild(hint(LABELS.hintPhoneOnly));
    else body.appendChild(field(LABELS.swipeDrawer, checkbox(P("swipeDrawer"), function (v) {
      prefs.set("swipeDrawer", v);
      if (!v) swipeOff();
    })));

    expander(body, "gear", LABELS.gearSection, function (box) {
      box.appendChild(sliderRow(LABELS.gearOpacity, PREF_RANGES.gearOpacity[0], PREF_RANGES.gearOpacity[1], 10, P("gearOpacity"),
        function (v) { return v + "%"; }, function (v) { prefs.set("gearOpacity", v); }));
      box.appendChild(hint(LABELS.hintGear));
    });

    var reset = el("button", NS + "-reset", LABELS.reset);
    reset.setAttribute("type", "button");
    reset.addEventListener("click", function (e) {
      e.preventDefault();
      e.stopPropagation();
      Object.keys(DEFAULTS).forEach(function (k) { prefs.set(k, DEFAULTS[k]); });
      uiSet(DEFAULTS.ui);
      refreshAll();
      detailPass(true);
      openPanel();
    });
    body.appendChild(reset);
    body.appendChild(el("div", NS + "-ver", LABELS.version(VERSION)));
  }

  function openPanel() {
    closePanel();
    var panel = el("div", NS + "-panel");
    panel.setAttribute("data-" + NS + "-panel", "1");
    panel.setAttribute("role", "dialog");
    panel.setAttribute("aria-label", LABELS.panelTitle);

    /* The title and the tabs ride at the top together while the settings scroll under them: on a
       phone the sheet is taller than the screen, and the way from one group to another has to stay
       in reach the whole time. */
    var top = el("div", NS + "-panel-top");
    var head = el("div", NS + "-panel-head");
    head.appendChild(el("h4", null, LABELS.panelTitle));
    var closeBtn = el("button", NS + "-panel-close", "\u00D7");   // ×
    closeBtn.setAttribute("type", "button");
    closeBtn.setAttribute("title", LABELS.close);
    closeBtn.setAttribute("aria-label", LABELS.close);
    closeBtn.addEventListener("click", function (e) {
      e.preventDefault(); e.stopPropagation();
      closePanel();
    });
    head.appendChild(closeBtn);
    top.appendChild(head);
    panel.appendChild(top);

    var body = el("div", NS + "-panel-body");
    panel.appendChild(body);

    var active = uiTab();
    tabStrip(top, body, active);

    if (active === "page") buildPageTab(body);
    else if (active === "ext") buildExtTab(body);
    else buildListTab(body);

    var host = document.body || null; // never <head>: it is display:none, the panel would be unreachable
    if (host) { host.appendChild(panel); startAwayWatch(); }
    else setTimeout(function () { if (document.body) openPanel(); }, 300);
  }

  function closePanel() {
    stopAwayWatch();
    var old = panelOpen();
    if (old && old.parentNode) old.parentNode.removeChild(old);
  }

  function ensureGear() {
    if (document.querySelector("." + NS + "-gear")) return;
    // The button lives in <body>: an element parked in <head> is display:none
    // and silently unreachable, which is exactly how the gear once vanished.
    if (!document.body) { scheduleGearRetry(); return; }
    var gear = el("button", NS + "-gear", "⚙");
    gear.setAttribute("type", "button");
    gear.setAttribute("title", "Botbooru Mod — settings");
    gear.setAttribute("aria-label", "Botbooru Mod settings");
    gear.addEventListener("click", function (e) {
      e.preventDefault(); e.stopPropagation();
      var open = document.querySelector("[" + "data-" + NS + "-panel" + "]");
      if (open) closePanel(); else openPanel();
    });
    document.body.appendChild(gear);
  }

  var gearRetryScheduled = false;
  function scheduleGearRetry() {
    if (gearRetryScheduled) return;
    gearRetryScheduled = true;
    [100, 400, 1200, 3000, 6000].forEach(function (t) {
      setTimeout(function () { if (document.body) ensureGear(); }, t);
    });
  }

  /* Rebuild every card after a pref that changes the block's content. */
  function refreshAll() {
    var tiles = document.querySelectorAll("a[data-post-id][" + "data-" + NS + "-done" + "]");
    tiles.forEach(function (tile) {
      var old = tile.querySelector("[" + "data-" + NS + "-info" + "]");
      if (old && old.parentNode) old.parentNode.removeChild(old);
      var title = tile.querySelector(":scope > ." + NS + "-title");
      if (title && title.parentNode) title.parentNode.removeChild(title);
      /* a name we lifted into a title has to be put back where the site keeps it */
      tile.querySelectorAll("." + NS + "-hidden-name, ." + NS + "-hidden-foot").forEach(function (n) {
        n.classList.remove(NS + "-hidden-name");
        n.classList.remove(NS + "-hidden-foot");
      });
      unwrapMarquee(tile);
      /* hand the art and the name row back to the site unmarked: the next pass names
         them again, and a stale stamp would hide them from the lookups */
      [].slice.call(tile.querySelectorAll(":scope > ." + NS + "-art, :scope > ." + NS + "-foot")).forEach(function (n) {
        n.classList.remove(NS + "-art");
        n.classList.remove(NS + "-foot");
      });
      tile.removeAttribute("data-" + NS + "-done");
    });
    scan(document);
    chromePass();
  }

  function installMenu() {
    if (typeof GM_registerMenuCommand !== "function") return;
    try {
      GM_registerMenuCommand("Card info settings", function () {
        var open = document.querySelector("[" + "data-" + NS + "-panel" + "]");
        if (open) closePanel(); else openPanel();
      });
      GM_registerMenuCommand(P("enabled") ? "Disable inline preview" : "Enable inline preview", function () {
        prefs.set("enabled", !P("enabled")); refreshAll(); detailPass(true);
      });
      GM_registerMenuCommand("Cycle phone columns", function () {
        var order = ["auto", "2", "1", "full"];
        var at = order.indexOf(String(P("phoneColumns")));
        prefs.set("phoneColumns", order[(at + 1) % order.length]);
      });
    } catch (e) { /* menu not available */ }
  }

  /* ───────────────────────── boot ───────────────────────── */

  var started = false;

  function boot() {
    if (started) return;
    // An init script can be evaluated before the document has an element to hang
    // the stylesheet on (document-start injection, Cloudflare challenge frames).
    if (!document.documentElement) { waitForDocument(); return; }
    started = true;

    // Self-report the running build so a test (or a user in DevTools) can prove
    // which copy of the script is actually live in the page.
    try { pageWin()[NS + "_mod_version"] = VERSION; } catch (e) { /* frozen window */ }

    if (!document.getElementById(NS + "-style")) {
      var style = document.createElement("style");
      style.id = NS + "-style";
      style.textContent = CSS;
      (document.head || document.documentElement).appendChild(style);
    }

    applyClasses();
    startObserver();
    scan(document);
    chromePass();
    exposeApi();

    /* The page's own answers are watched from before the page asks for them. */
    installUploaderCapture();

    ensureGear(); // parks itself until <body> exists
    document.addEventListener("DOMContentLoaded", function () {
      ensureGear();
      installMenu();
      scan(document);
      chromePass();
    });
    // SPA views settle a beat later than the markup they swap in
    [300, 1200, 3000].forEach(function (t) {
      setTimeout(function () { scan(document); applyThumbs(); detailPass(true); chromePass(); }, t);
    });

    chromeState.viewportWidth = Math.round(window.innerWidth || 0);

    /* The one-column layouts, the picture tier and the safe-area padding all depend on the
       viewport, so a rotation or a window resize has to re-derive them. The header's one-row
       decision is re-measured on the same event but only for the half of it that matters: the
       width. A phone fires resize every time its address bar slides in or out; re-deciding the
       header on that is what made it switch between two rows and one on every opposite scroll. */
    window.addEventListener("resize", function () {
      var wide = Math.round(window.innerWidth || 0);
      var roomChanged = wide !== chromeState.viewportWidth;
      chromeState.viewportWidth = wide;
      applyClasses();
      syncHeaderOffset();
      if (roomChanged) { chromeState.signature = ""; chromeState.plan = -1; }
      scheduleApply("chrome");
    }, { passive: true });
  }

  function waitForDocument() {
    var done = false;
    function retry() {
      if (done) return;
      if (!document.documentElement) return;
      done = true;
      try { mo.disconnect(); } catch (e) { /* already disconnected */ }
      boot();
    }
    // Observing the Document node works even while <html> does not exist yet.
    var mo = new MutationObserver(retry);
    try { mo.observe(document, { childList: true }); } catch (e) { /* engine without document observation */ }
    document.addEventListener("DOMContentLoaded", retry);
    setTimeout(retry, 200);
    setTimeout(retry, 1500);
  }

  try { boot(); } catch (e) { waitForDocument(); }
})();