☰

NHentai Custom Brew

Add customizable favorites and many other features and improvements for nHentai. Also adds API request caching to reduce the frequency of rate limits.

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

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

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

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

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

You will need to install a user script manager extension to install this script.

(I already have a user script manager, let me install it!)

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

(I already have a user style manager, let me install it!)

// ==UserScript==
// @name         NHentai Custom Brew
// @namespace    NHCB
// @version      8.0
// @description  Add customizable favorites and many other features and improvements for nHentai. Also adds API request caching to reduce the frequency of rate limits.
// @author       FB6000
// @license      MIT
// @icon         https://icons.duckduckgo.com/ip2/nhentai.net.ico
// @match        https://nhentai.net/*
// @exclude      https://nhentai.net/api/*
// @run-at       document-start
// @grant        GM_info
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_deleteValue
// @grant        GM_listValues
// @grant        GM_addStyle
// @grant        GM_setClipboard
// @grant        GM_registerMenuCommand
// ==/UserScript==
/** @typedef {import('tampermonkey')} */

// Note: If you are trying to read/edit code, use the Region Helper extension for vscode.


//#region -- Wall of Text ----------------------------------
//#region Intro
/*
    Because Svelte updates the page and removes added elements, there needs to be some system to re-add elements
    This is made even harder since the script persists between page navigation because you are not actually "navigating" to a new page, its just updating the existing html to match (term: SPA)
    Plus you have to deal with the fact that API calls are limited and tampermonkey scripts can get quite long
    It basically requires a concrete structure to prevent things from getting unreadable and to prevent making unneeded API calls

    The basic loop is this:
    1. Load data and setup basic script scope variables
    2. Do API calls if determined necessary (see notes #ApiLimits and #InitialPageRequest)
    3. Determine what changes need to made to page and cache those decisions if expensive
    4. Apply changes
    5. Use mutation observer to force those changes to stick by reapplying them (only if changes undone)
    6. On new page, cleanup changes (see note #SvelteClean)

    Lastly, in no particular order, you add the CSS.
    It also persists between pages, so you only need to do it once.
*/
//#endregion

//#region Svelte Clean
/*
    #SvelteClean
    Why do I have to clean up changes made on the previous page?
    Svelte reuses elements on a page when it can. This means that in many situations, your changes don't get removed when you navigate to a simlar page
    One example being the next page of a search (but this also applies if you navigate to another gallery while on the gallery page by using recommended links or other)
    If you add a badge to a gallery as a child, that badge will persist, even if it's not correct for the current gallery shown
    Eg:
        Badge showing page number of gallery is added to gallery Foo, which has X pages, in position (1)
        User navigates to next page of search
        Gallery that is in position (1) is no longer gallery Foo but instead gallery Bar
        However, gallery Foo still has the page count of X instead of the correct number Y because the badge still existed

    For classes it is handled slightly differently
    When a class is written to, it generally overwrites all existing classes on the element
    However, this only applies if the new class is different, based on the internal state
    Eg:
        initial <lang-gb>     -->  'lang-gb'
        add <foo-bar>         -->  'lang-gb foo-bar'
        updated to <lang-gb>  -->  'lang-gb foo-bar'
        updated to <lang-jp>  -->  'lang-jp'

    One thing to keep in mind is that if you make an element that exists outsite of the page's "content", it will generally be left alone.
    This is dependent if it the added element is a child of page element which got repopulated or replaced by the website.
    The main problem is that on page init, the page refreshes the content on the page, clearing all added content.
    However, after that, the page generally doesn't remove stuff untill you go to a new page.
*/
//#endregion

//#region Api Limits
/*
    #ApiLimits
    Many of the stuff done for the API is simple and just requires the gallery info.
    Basically all the info you need is given to you by the matching endpoint for the page.
    The main issue is that the api has very conservative rate limits, meaning you have put a lot of effort into reducing the number of calls.
    To do that, several strategies are used in this script.
    This includes caching, grabbing the initial api response given by the html (see note #InitialPageRequest), and piggybacking off the websites own API calls (see note #Monkeypatch).
    All of these are used to try get down the number of extra API calls. The most important being piggybacking as the others only matter for people who like using multiple tabs.
*/
//#endregion

//#region Initial Page Request
/*
    #InitialPageRequest
    At some point I noticed that the the website doesn't make a separate fetch request to the API on page init.
    After doing some digging, I found out that this data is actually bundled with the HTML for page.
    It is put into a script tag with a "data-sveltekit-fetched" attribute.
    The main problem is that becuase this is a SPA that modifies the page, that initial data gets wiped out after the page hydrates.
    So in order to grab that data, you have to get it before it gets wiped out, but doing that is a bit a challenge.

    The main roadblock with that is how tampermonkey runs this script.
    It's suppose to run at a set time, but that time isn't precise enough for this use case.
    It can sometimes run slightly early or late and the chances of that seem to depend on the length of the HTML.
    So in order to grab the data from the page it tries two methods.
    First it tries grabbing it immidiately, which would be for a late injection.
    If that doesn't work, then it adds a mutation observer to watch for them being written into the DOM.
    These two alone seem to cover all cases and timings.

    The data itself is a object that contains the data for the response, not an instance of Response.
    You use that data to create an instance of Response or just use it directly.
    The url for the request is attached to a "data-url" attribute
*/
//#endregion

//#region Monkey Patch
/*
    #Monkeypatch
    This code money patches the fetch function. This could be used by a bad actor to do malicious things.
    To do this, it make use of unsafeWindow.
    So this requires some explanation as to what it does and why.
    TLDR: Sketchy code used for legitimate purpose. It is used to reduce the number of API calls to prevent being rate limited.

    Why the monkey patch:
    Short answer: API rate limits so small
    Long answer:
    This script makes requests to the API, but the website itself also makes the exact same request to the API.
    Both of these request count towards the rate limit for the API. Meaning by using the script, your rate limits are cut in half.
    This is made worse because the website does not cache anything. So for something like search, you have an effective limit of 5 requests per min.
    If you use make a search, go the next page, and then use the back and forward browser buttons, the website makes the exact same requests until you hit the rate limit.
    So I wanted to fix that while also piggybacking off the API request the website makes.

    What the monkey patch does:
    The monkey patch intercepts all fetch requests made by the website. This is limited to fetch request made in code.
    It then reads the url of the request to check if it is a rate limited and cacheable API endpoint.
    If so, it checks the cache first.
    If there is no cache, it sends the request out as normal and then caches and returns the response.
    If there is a cache, it stops the request from being sent and instead returns the cached response.
    In some edge cases, it will upgrade the request to ask for all the optional data to prevent cache miss on a request that asks for less info than the one before it.

    Why this could be bad:
    This could be used to spy on you or steal login info.
    However, that is the case for all programs, extensions, and tamper monkey scripts. So it's not a real issue.
    The use of unsafeWindow could lead to security problems.
    It could be used by someone who has access to the page's code to do bad stuff.
    I don't see this as an issue either since it requires code access which means they could already do bad stuff.
    It could be used by the website to hijack the script. But why tho.
    Overall, it is something to keep in mind but I don't think presents a practical security risk.
*/
//#endregion

//#region Todo
/*
    changes:

    next update:
    - tag sentiment page change (can filter for any)

    priority:
    - auto backup / backup reminders
    - artist rating
        - over tag sentiments, many artists are meh
    
    unsorted:
    - change css for page thumbs to use css grid instead?
    - change cleaner to use weakref
    - artist rating
    - system for "saving" tags (tag highlights?)
        - rating
        - notes
        - description?
        - highlight?
        - subscribe/follow?
            - list of artists/tags you follow
            - get notified if gallery is one you follow?
        - bookmark (like book not web browser) latest browsed gallery
    - new japanese tag?
        - /language/japanese-definition-revised-please-read-the-wiki/
        - seems to be because of some rule change on e-hentai
        - new id: 168289
        - seems like nhentai are fixing it and replacing the tag
    - tag aliases for tag sentiments for pipes
    - follow system for reminder for checking tags/pages
        - set interval for checking
        - get notified if something new
    - tag description badge or maybe card when hover

    todo:
    - improve auto refresh
        - make it check request cache and if cached, auto refresh
            - should work with programtic navigation changes now triggering svelte instead of html navigation
    - artist/tag rating
        - instead more tag sentiments
            - favorite (current green, renamed from liked)   
            - liked (lighter green)
            - meh (darker grey)

    planned:
    - features
        - more info
             - custom info to gallery:
                - alt sources? (merge into try alt source?)
                - media id?
        - collections
            - tsumino style collections for series
            - able to to set create collections so that you can see all other galleries that are a part of the series
            - view collections
            - auto collections based on tag (generated on page or update every time?)
        - browse mode (make queue, then read/read later/pass/fav)
        - gallery prieview
            - preview pages without having to go to the page
            - combine with browse mode?
        - super specific search
            - helper to filter out galleries with similar artist names
            - only if single tag is artist or group (not including language)
            - steps
                1. do search
                2. get all tags ids from galleries on page
                3. check if artist has exact match, if not exlucde all artists
                4. do only once option to repeat manually if necessary
        - estimated gallery enjoyment ratings
            - pick one or other
                - favorite artist and favorite tag badge (separate, add counts)
                - content blessings? opposite of content warning badge
        - more customizable tag sentiments and highlighting
        - customize tags
            - change tag names
            - change tag description
            - add/remove tags for favorites
        - off site favorites, for stuff that gets dmca (maybe)
            - /nhcb-g/123456/
            - only appears on favorites page
            - can use normal favorite data but need to give id
                - id needed for sorting, use instead of upload_date because upload_date is only given in detailed info
            - how to handle view? just link to other site?
            - how is that better than hijacking random gallery and customizing?
    - visual changes
        - new icons for pass and read
        - book shelf icon for browsed
        - tag changes
            - liked badge for tagonpage == 1
        - setting for making search bar bigger
    - systems
        - auto 404 detection by checking gallery thumbs
            - .jpg, .png, .webp.webp (yes twice)
            - shouldn't auto mark in case server is being slow, just flag them to user
        - cache for recently removed later or favorites rather than just the page
        - import labels from read later to favorite/import labels from favorite to read later (just make them share tags)
        - auto labels based on tag
        - something so that you can update minor info on stored data
            - counts, tags, favorite count
    - functionality
        - edit alt source
        - support for read later + already read (just change the button, make read later higher priority in opacity)
        - auto refresh rate limit non gallery pages
            - search
            - namespace
        - browse later support for (search, pages?)
        - search tagchip make api call to verify
    - settings
        - import/export alternative script settings
        - auto backup reminders
        - auto backup
*/
//#endregion
//#endregion

(async function () {
    'use strict';

    //#region -- Logging and Debugging --------------------------------------------
    //#region Logger
    const logger = (() => {
        /** @enum {number  & { __brand: 'LogLevel' }} */
        const LogLevel = { ALL: 0, VERBOSE: 1, DEBUG: 2, LOG: 3, INFO: 4, SUCCESS: 5, ISSUE: 6, WARN: 7, ERROR: 8, SILENT: 9 }

        const loggerOverrides = GM_getValue('DEBUG_ModuleLevels', {}); // set in debug command

        /** @enum {number  & { __brand: 'LogLevel' }} */
        const LoggerModule = {
            GENERAL:                      loggerOverrides.GENERAL ?? LogLevel.LOG,
            ISSUE_HANDLER:          loggerOverrides.ISSUE_HANDLER ?? LogLevel.LOG,
            REQUEST_PIGGYBACK:  loggerOverrides.REQUEST_PIGGYBACK ?? LogLevel.LOG,
            CONTROL_LOOP:            loggerOverrides.CONTROL_LOOP ?? LogLevel.SUCCESS,
            STORE_UPDATES:          loggerOverrides.STORE_UPDATES ?? LogLevel.LOG,
            EXPERIMENTAL_FEATURES:      loggerOverrides.EXPERIMENTAL_FEATURES ?? LogLevel.SILENT,
        };

        const shouldLog = (messageLevel, moduleLevel) => messageLevel >= moduleLevel;
        function createLogger(moduleLevel) {
            const LOGGER_STYLE = {
                BLUE: 'color:#2196F3;font-weight:bold;',
                ORANGE: 'color:#FF9800;font-weight:bold;',
                RED: 'color:#EB2A6A;font-weight:bold;',
                GREEN: 'color:#4CAF50;font-weight:bold;',
                PURPLE: 'color:#D252EB;font-weight:bold;',
                get DEFAULT() { return LOGGER_STYLE.BLUE; },
                get WARN() { return LOGGER_STYLE.ORANGE; },
                get ERROR() { return LOGGER_STYLE.RED; },
                get DEBUG() { return LOGGER_STYLE.PURPLE; },
                get SUCCESS() { return LOGGER_STYLE.GREEN; },
            }
            return {
                shouldLog: (/** @type {LogLevel} */ messageLevel) => shouldLog(messageLevel, moduleLevel),
                log: shouldLog(LogLevel.LOG, moduleLevel) ? console.log.bind(console, '%c[NHCB]', LOGGER_STYLE.DEFAULT) : () => {},
                info: shouldLog(LogLevel.INFO, moduleLevel) ? console.info.bind(console, '%c[NHCB]', LOGGER_STYLE.DEFAULT) : () => {},
                issue: shouldLog(LogLevel.ISSUE, moduleLevel) ? console.log.bind(console, '%c[NHCB:ISSUE]', LOGGER_STYLE.WARN) : () => {},
                warn: shouldLog(LogLevel.WARN, moduleLevel) ? console.warn.bind(console, '%c[NHCB:WARN]', LOGGER_STYLE.WARN) : () => {},
                error: shouldLog(LogLevel.ERROR, moduleLevel) ? console.error.bind(console, '%c[NHCB:ERROR]', LOGGER_STYLE.ERROR) : () => {},
                success: shouldLog(LogLevel.SUCCESS, moduleLevel) ? console.info.bind(console, '%c[NHCB]', LOGGER_STYLE.SUCCESS) : () => {},
                apiFail: shouldLog(LogLevel.ISSUE, moduleLevel) ? console.warn.bind(console, '%c[NHCB:API]', LOGGER_STYLE.WARN) : () => {},
                apiError: shouldLog(LogLevel.ERROR, moduleLevel) ? console.error.bind(console, '%c[NHCB:API]', LOGGER_STYLE.ERROR) : () => {},
                debug: shouldLog(LogLevel.DEBUG, moduleLevel) ? console.debug.bind(console, '%c[NHCB:DEBUG]', LOGGER_STYLE.DEBUG) : () => {},
                verbose: shouldLog(LogLevel.VERBOSE, moduleLevel) ? console.debug.bind(console, '%c[NHCB:DEBUG]', LOGGER_STYLE.DEBUG) : () => {},
            };
        }

        return {
            LEVELS: LogLevel,
            MODULES: LoggerModule,
            ...createLogger(LoggerModule.GENERAL),
            issueHandler: createLogger(LoggerModule.ISSUE_HANDLER),
            requestPiggyback: createLogger(LoggerModule.REQUEST_PIGGYBACK),
            controlLoop: createLogger(LoggerModule.CONTROL_LOOP),
            storeUpdates: createLogger(LoggerModule.STORE_UPDATES),
            experimentalFeatures: createLogger(LoggerModule.EXPERIMENTAL_FEATURES), // holy jank
        };
    })();
    //#endregion

    //#region Reporting
    function reportIssue(issueName, ctx = {}, notifierDurationOverride = undefined) {
        const issue = Issue[issueName];
        if (!issue) {
            notifier?.error(`An error has occured. If you weren't messing with code, something is bugged. If you were, fix your code dumbass! Issue "${issueName}" doesn't exist.`);
            logger.error(`Issue data for "${issueName}" doesn't exist. context:`, ctx);
            return;
        }

        const simpleStr = issue.simple?.(ctx);
        const detailStr = issue.detail?.(ctx);

        switch(issue.severity) {
            case IssueSeverity.INFO:
                simpleStr && notifier?.info(simpleStr, notifierDurationOverride);
                detailStr && logger.issueHandler.log(detailStr);
                break;
            case IssueSeverity.ISSUE:
                simpleStr && notifier?.warn(simpleStr, notifierDurationOverride);
                detailStr && logger.issueHandler.issue(issueName, detailStr);
                break;
            case IssueSeverity.ERROR:
                simpleStr && notifier?.error(simpleStr, notifierDurationOverride !== undefined ? notifierDurationOverride : null);
                detailStr && logger.issueHandler.error(issueName, detailStr);
                break;
            case IssueSeverity.API_FAIL:
                simpleStr && notifier?.warn(simpleStr, notifierDurationOverride !== undefined ? notifierDurationOverride : 5 * 60);
                detailStr && logger.issueHandler.apiFail(issueName, detailStr);
                break;
            default:
                notifier?.error(`An error has occured. If you weren't messing with code, something is bugged. If you were, fix your code dumbass! Severity "${issue.severity}" for "${issueName}" doesn't exist.`);
                logger.error(`Issue severity for "${issueName}" is not valid. issue:`, issue, 'context:');
                break;
        }
    }
    function reportInputInvalidIssue(message, input) {
        reportIssue('INPUT_INVALID', { message, input });
    }
    //#endregion

    //#region Issues
    /** @enum {string & { __brand: 'IssueSeverity' }} */
    const IssueSeverity = { INFO: 'info', ISSUE: 'warn', ERROR: 'error', API_FAIL: 'apiFail' };
    /** @enum {{ severity: IssueSeverity, simple: ((ctx) => string)?, detail: ((ctx) => string)? }} */
    const Issue = {
        //#region Ops
        FAVORITE_MISSING: {
            severity: IssueSeverity.ISSUE,
            simple: (ctx) => `Gallery no longer appears to be a favorite. Was it modified on another page?`,
            detail: (ctx) => `Gallery no longer appears to be a favorite. Was it modified on another page? Gallery Path: (${ctx.galleryPath})`,
        },
        CANNOT_FAVORITE_API_FAIL: {
            severity: IssueSeverity.ERROR,
            simple: (ctx) => `Unable to add gallery to favorites, API request failed!`,
            detail: (ctx) => `Unable to add gallery to favorites, API request failed! Gallery Path: (${ctx.galleryPath})`,
        },
        ALT_SOURCE_MISSING: {
            severity: IssueSeverity.ISSUE,
            simple: (ctx) => `Alt source for favorite no longer appears to exist. Was it modified on another page?`,
            detail: (ctx) => `Alt source for favorite no longer appears to exist. Was it modified on another page? Gallery Path: (${ctx.galleryPath}), Alt Source Link: (${ctx.altSourceLink})`,
        },
        MIGRATION_TARGET_SELF: {
            severity: IssueSeverity.INFO,
            simple: (ctx) => `Why are you trying to migrate to itself?`,
            detail: (ctx) => `Cannot migrate. Migration target must be a different gallery.`,
        },
        MIGRATION_TARGET_IS_FAVORITE: {
            severity: IssueSeverity.ISSUE,
            simple: (ctx) => `Cannot migrate customizations. Migration target is already a favorite.`,
            detail: (ctx) => `Cannot migrate customizations. Migration target is already a favorite. Original: (${ctx.sourcePath}), Target: (${ctx.targetPath})`,
        },
        MIGRATION_TARGET_IS_READ_LATER: {
            severity: IssueSeverity.ISSUE,
            simple: (ctx) => `Cannot migrate read later. Migration target is already a read later.`,
            detail: (ctx) => `Cannot migrate read later. Migration target is already a read later. Original: (${ctx.sourcePath}), Target: (${ctx.targetPath})`,
        },
        READ_LATER_MISSING: {
            severity: IssueSeverity.ISSUE,
            simple: (ctx) => `Gallery no longer appears to be a marked as read later. Was it modified on another page?`,
            detail: (ctx) => `Gallery no longer appears to be a marked as read later. Was it modified on another page? Gallery Path: (${ctx.galleryPath})`,
        },
        BROWSE_LATER_MISSING: {
            severity: IssueSeverity.ISSUE,
            simple: (ctx) => `Page no longer appears to be a marked as browse later. Was it modified on another page?`,
            detail: (ctx) => `Page no longer appears to be a marked as browse later. Was it modified on another page? Page Key: (${ctx.pageId})`,
        },
        CANNOT_READ_LATER_API_FAIL: {
            severity: IssueSeverity.ERROR,
            simple: (ctx) => `Unable to add gallery to read later list, API request failed!`,
            detail: (ctx) => `Unable to add gallery to read later list, API request failed! Gallery Path: (${ctx.galleryPath})`,
        },
        CANNOT_CHANGE_TAG_SENTIMENT_API_FAIL: {
            severity: IssueSeverity.ERROR,
            simple: (ctx) => `Unable to make tag ${ctx.status}, API request failed!`,
            detail: (ctx) => `Unable to make tag ${ctx.status}, API request failed! Tag Path: (${ctx.tagPath})`,
        },
        IMPORT_FROM_FILE_FAILED: {
            severity: IssueSeverity.ERROR,
            detail: (ctx) => `Import from file failed.`,
        },        
        //#endregion
        //#region API
        API_TIMEOUT: {
            severity: IssueSeverity.API_FAIL,
            simple: (ctx) => `API request timeout. Servers are slow.`,
            detail: (ctx) => `API request failed! Reason: (timeout), Request Url: (${ctx.requestUrl})`,
        },
        API_RATE_LIMIT: {
            severity: IssueSeverity.API_FAIL,
            simple: (ctx) => `API request denied, too many requests. Wait a minute before trying again.`,
            detail: (ctx) => `API request failed! Reason: (rate limit), Request Url: (${ctx.requestUrl})`,
        },
        API_OTHER_ISSUE: {
            severity: IssueSeverity.API_FAIL,
            simple: (ctx) => `API request failed for some reason. Tis a mystery.`,
            detail: (ctx) => `API request failed! Reason: (${ctx.responseCode}), Request Url: (${ctx.requestUrl})`,
        },
        API_ERROR: {
            severity: IssueSeverity.API_FAIL,
            simple: (ctx) => `API request failed due to error.`,
            detail: (ctx) => `API request failed! Error Message: (${ctx.errorMessage}), Request Url: (${ctx.requestUrl})`,
        },
        //#endregion
        //#region Patches
        INVALID_PATCH: {
            severity: IssueSeverity.ERROR,
            simple: (ctx) => `Failed to patch an object. If you are seeing this and weren't messing with the code, something is bugged.`,
            detail: (ctx) => `Patch for object has failed. A programmer needs to fix it.\nPatch attempted:\n${JSON.stringify(ctx, null, '\t')}`,
        },
        INVALID_PATCH_ARRAY: {
            severity: IssueSeverity.ERROR,
            simple: (ctx) => `Failed to patch an object. If you are seeing this and weren't messing with the code, something is bugged.`,
            detail: (ctx) => `Patch for object has failed. A programmer needs to fix it.\nPatch attempted:\n${JSON.stringify(ctx, null, '\t')}`,
        },
        PATCH_ARRAY_REMOVE_FAIL: {
            severity: IssueSeverity.ERROR,
            simple: (ctx) => `Failed to patch an object. If you are seeing this and weren't messing with the code, something is bugged.`,
            detail: (ctx) => `Patch for object has failed. A programmer needs to fix it.\nPatch attempted:\n${JSON.stringify(ctx, null, '\t')}`,
        },
        PATCH_ARRAY_PROMOTION_FAIL: {
            severity: IssueSeverity.ERROR,
            simple: (ctx) => `Failed to patch an object. If you are seeing this and weren't messing with the code, something is bugged.`,
            detail: (ctx) => `Patch for object has failed. A programmer needs to fix it.\nPatch attempted:\n${JSON.stringify(ctx, null, '\t')}`,
        },
        //#endregion
        //#region Other
        INPUT_INVALID: {
            severity: IssueSeverity.ISSUE,
            simple: (ctx) => `${ctx.message}`,
            detail: (ctx) => `${ctx.message} Input: ${JSON.stringify(ctx.input)}`,
        },
        MISSING_CUSTOM_PAGE_ROUTE: {
            severity: IssueSeverity.INFO,
            simple: (ctx) => `Are you lost traveler? This page doesn't exist.`,
            detail: (ctx) => `Missing custom page route:  ${ctx.pagePath}`,
        },
        MISSING_SETTING: {
            severity: IssueSeverity.ERROR,
            simple: (ctx) => `The setting "${ctx.settingName}" is missing. Please report this issue.`,
            detail: (ctx) => `Missing setting ${ctx.settingName}. Current settings: ${ctx.settings}`,
        },
        //#endregion
    };
    //#endregion
    //#endregion 

    //#region -- Type Defs ------------------------------------------
    /** 
     * @typedef {number & { __brand: 'int' }} int
     * @typedef {number & { __brand: 'UnixSeconds' }} UnixSeconds
     * @typedef {string & { __brand: 'GalleryPath' }} GalleryPath
     * @typedef {string & { __brand: 'TagPath' }} TagPath
     * @typedef {string & { __brand: 'PageId' }} PageId Used to identify if a page is unique. Excludes all search params except the query.
     * @typedef {string & { __brand: 'PageKey' }} PageKey Use to identify if a page url has changed.
     * @typedef {string & { __brand: 'Label' }} Label When stored: unique, trimmed, must not include commas. Case insensitive for matching. Capitalization is preserved in data. `'none'` is reserved.
     * 
     * @typedef {'parody'|'character'|'tag'|'artist'|'group'|'language'|'category'} TagType
     * @typedef {-3|-2|-1|0|1|2|3} Priority
     * 
     * @typedef {Object} PatchOk
     * @property {true} ok
     * @property {any} data
     * 
     * @typedef {Object} PatchFail
     * @property {false} ok
     * @property {string} issue
     * @property {Object} ctx
     * 
     * @typedef {string|number|boolean|null|Object} PatchValue
     * @typedef {string|number} PatchId
     * 
     * @typedef {{op: 'push', value: PatchValue, unique?: boolean} |
     *           {op: 'pushObj', value: object, unique?: boolean, idKey?: string} |
     *           {op: 'remove', id: PatchId} |
     *           {op: 'removeObj', idKey: string, id: PatchId} |
     *           {op: 'removeAt', index: int} |
     *           {op: 'promote', idKey: string, id: PatchId} | 
     *           {op: 'replaceAll', value: any[]}
     *          } ArrayPatch
     * 
     * @typedef {Object.<string, PatchValue | ArrayPatch>} Patch 
     * `{ fieldName: newValue, ... }` or for arrays `{ arrayField: { op: 'removeObj', idKey: 'fieldName', id: 'id' }, ... }`
     *
     * @typedef {Object} PageData
     * @property {PageType} type
     * @property {string} path
     * @property {{type: TagType, name: string}|null} tagInfo
     * @property {string|null} galleryId
     * @property {URLSearchParams} searchParams
     * @property {string|''} query
     * @property {PageId} id
     * @property {PageKey} key
     * @property {string} href
     * 
     * @typedef {Object} CachedResponse
     * @property {string} body
     * @property {number} status
     * @property {object} headers
     * @property {number} expiresAt
     * 
     * @typedef {Object} GalleryData
     * @property {int} id
     * @property {string} media_id
     * @property {string} english_title
     * @property {string|null} japanese_title
     * @property {string} thumbnail
     * @property {number} thumbnail_width
     * @property {number} thumbnail_height
     * @property {int} num_pages
     * @property {int} num_favorites
     * @property {int[]} tag_ids
     * 
     * @typedef {Object} TagData
     * @property {int} id
     * @property {TagType} type
     * @property {string} name
     * @property {string} url
     * @property {int} count
     * @property {string|null} description
     * @property {true|null} is_community
     * @property {string|null} pending_describe_id
     * 
     * @typedef {Object} UserData
     * @property {int} id
     * @property {string} username
     * @property {string} slug
     * @property {string} avatar_url
     * 
     * @typedef {Object} FavoriteData
     * @property {int} id
     * @property {string} media_id
     * @property {string} english_title
     * @property {string|null} japanese_title
     * @property {string} thumbnail
     * @property {number} thumbnail_width
     * @property {number} thumbnail_height
     * @property {int} num_pages
     * @property {int} [num_favorites]
     * @property {int[]} tag_ids
     * @property {UnixSeconds} favorite_at
     * @property {string} [custom_title]
     * @property {string} [note]
     * @property {int} [rating]
     * @property {Label[]} [labels]
     * @property {AltCover} [alt_cover]
     * @property {AltSource[]} [alt_sources]
     * @property {'none'|'nudge'|'force'} [alt_source_action]
     * @property {bool} [primary_alt_source_is_translation]
     * @property {bool} [gallery_is_404]
     * 
     * @typedef {Object} AltCover
     * @property {string} thumbnail
     * @property {number} thumbnail_width
     * @property {number} thumbnail_height
     * 
     * @typedef {Object} AltSource
     * @property {string} name
     * @property {string} link
     * @property {string} thumbnail
     * @property {number} thumbnail_width
     * @property {number} thumbnail_height
     * 
     * @typedef {Object} ReadLaterData
     * @property {int} id
     * @property {string} media_id
     * @property {string} english_title
     * @property {string|null} japanese_title
     * @property {string} thumbnail
     * @property {number} thumbnail_width
     * @property {number} thumbnail_height
     * @property {int} num_pages
     * @property {int} [num_favorites]
     * @property {int[]} tag_ids
     * @property {UnixSeconds} added_at
     * @property {Priority} read_priority
     * @property {Label[]} [labels]
     * 
     * @typedef {Object} BrowseLaterData
     * @property {PageId} page_key
     * @property {UnixSeconds} added_at
     * @property {Priority} browse_priority
     * @property {string} [name] tag name
     * @property {string} [note]
     * @property {Label[]} [labels]
     * @property {int} [tag_id]
     * @property {boolean} [not_tag]
     * 
     * @typedef {Object} UserData
     * @property {int} id
     * @property {string} username
     * @property {string} slug Url safe version of username
     * @property {string} avatar_url like thumbnails, it needs to be put into a media server format (t1-4)
     * @property {string} theme
     * @property {boolean} is_staff
     * @property {boolean} is_superuser
     * @property {boolean} is_superuser
     * @property {string} about
     * @property {string} favorite_tags
     * @property {string} email
     * 
     * @typedef {Object} ContentWarningRule
     * @property {string} label "WARN"
     * @property {string} input "/tag/tag-name/,!/tag/other-tag/"
     * @property {[id: int]} logic [123,!456,789]
     * 
     * @typedef {Object} TagSentiment
     * @property {'liked'|'dubious'|'scorned'} status
     * @property {int} id Tag id
     * @property {string} name Tag name
     * @property {UnixSeconds} added_at
     * 
     * @typedef {'none'|'read'|'passed'|'liked'} ReadStatus
     * 
     * @typedef {Object} FactoryRoot
     * @property {HTMLElement} el
     * @property {DOMTokenList} classList
     * @property {boolean} hidden
     * @property {(...children: (FactoryChild)[]) => void} append
     * @property {(...children: (FactoryChild)[]) => void} replaceChildren
     * @property {(name: string, getter: () => any, setter: (value: any) => void) => void} addProperty
     * @property {() => string} toString
     * 
     * @typedef {string | HTMLElement | FactoryRoot} FactoryChild
     * @typedef {FactoryChild | FactoryChild[]} FactoryContent
     * 
     * @typedef {Array<string | [value: string, textContent: string]>} DropdownOptions
     * 
     * @typedef {Object} SearchTerm
     * @property {string | null} key
     * @property {string} value
     * @property {boolean} negated the term was prfix with a " -" 
     * @property {int} start       index of the term's first char in the input
     * @property {int} end         index just past the term's last char
     * @property {int|-1} colon    index of the colon separating key and info, or -1
     * @property {boolean} open    true if a quote was opened but never closed
     * 
     * @typedef {(galleryData: FavoriteData | ReadLaterData | GalleryData) => boolean} SearchFilter
     */
    //#endregion

    //#region -- Serialization -----------------------------
    // Giga overkill
    //#region Store
    const storeBackends = (() => {
        const browserStoragePrefix = 'nhcb-';
        return {
            gm: {
                get(key, defaultValue) { return GM_getValue(key, defaultValue); },
                set(key, value) { GM_setValue(key, value); }
            },
            sessionStorage: {
                get(key, defaultValue) {
                    const raw = sessionStorage.getItem(browserStoragePrefix + key);
                    return raw === null ? defaultValue : JSON.parse(raw);
                },
                set(key, value) { sessionStorage.setItem(browserStoragePrefix + key, JSON.stringify(value)); }
            },
            localStorageBackend: {
                get(key, defaultValue) {
                    const raw = localStorage.getItem(browserStoragePrefix + key);
                    return raw === null ? defaultValue : JSON.parse(raw);
                },
                set(key, value) { localStorage.setItem(browserStoragePrefix + key, JSON.stringify(value)); }
            }
        }
    })();

    class Store {
        /**
         * @template V
         * @typedef {Object} StoreField
         * @property {V} value
         * @property {string} name
         * @property {(dryRun?: boolean) => void} save
         * @property {() => V} load
         * @property {(listener: ()=>void) => ()=>void} subscribe Subcribe to commits made by the save function. Returns a function that unsubscribes.
         * @property {(listener: ()=>void) => void} unsubscribe
         * @property {(message?: string) => void} logValue
         * @property {() => { [fieldKey: string]: V }|{ [fieldKey: string]: any }} export
         * @property {(data: { [fieldKey: string]: V }|{ [fieldKey: string]: any }) => boolean} import
         */

        #backend;
        // encoders/decoders are for transforming non-serializable types into/from serializable types
        #encoders = {
            Map: v => [...v],
            Set: v => [...v],
            Date: v => v.toISOString()
        };
        #decoders = {
            Map: v => new Map(v),
            Set: v => new Set(v),
            Date: v => new Date(v)
        };
        /** @type {Set<string>} */
        #fieldKeys = new Set();
        /** @type {Map<string, Set<Function>>} */
        #listeners = new Map();

        /**
         * @example
         * const store = new Store(gmBackend)
         *     .addField('myMap', new Map())
         *     .addField('mySet', new Set())
         *     .addField('myString', '')
         *     .addField('myNum', 0);
         * store.myMap.value.set('key', 'value');
         * store.myString.value = 'Hello World!';
         * store.myString.save();
         */
        constructor(backend) {
            this.#backend = backend;
        }

        /**
         * Just as a warning, don't set `defaultValue` to exotic types that aren't serializable by using `encoders`.
         * @template {string} K
         * @template V
         * @param {K} key
         * @param {V} defaultValue
         * @param {Function} [explicitType]
         * @returns {this & Record<K, StoreField<V>>}
         */
        addField(key, defaultValue, explicitType = undefined) {
            // .constructor.name doesn't work in EVERY use case but should work for this
            const encode = (v) => this.#encoders[v?.constructor?.name]?.(v) ?? v;
            const decode = (raw, hint, explicitType) => {
                const name = explicitType?.name ?? hint?.constructor?.name;
                return this.#decoders[name]?.(raw) ?? raw;
            };
            const backend = this.#backend;
            const cloneDefault = () => {
                if (defaultValue == null) {
                    return defaultValue;
                }
                const encoded = encode(defaultValue);
                return decode(JSON.parse(JSON.stringify(encoded)), defaultValue, explicitType);
            };
            
            const addListener = (func) => this.#listeners.get(key).add(func);
            const removeListener = (func) => this.#listeners.get(key).delete(func);
            const notifyListeners = () => this.#listeners.get(key).forEach(func => func?.apply());

            this[key] = {
                value: cloneDefault(),
                get name() { return key; },
                save(dryRun = false) {
                    const encoded = encode(this.value);
                    if (dryRun) {
                        logger.storeUpdates.info(`Dry run save for (${key})`, encoded);
                    }
                    else {
                        backend.set(key, encoded);
                    }
                    notifyListeners();
                },
                load() {
                    const raw = backend.get(key, encode(cloneDefault()));
                    this.value = decode(raw, defaultValue, explicitType);
                    return this.value;
                },
                subscribe(func) {
                    addListener(func);
                    return () => removeListener(func);
                },
                unsubcribe(func) {
                    removeListener(func);
                },
                logValue(message = '') {
                    logger.storeUpdates.info(`${message ? message + ' - ' : '' }Store '${key}' data (raw, encoded):`, this.value, encode(this.value));
                },
                export() {
                    return { [key]: encode(this.value) };
                },
                import(data) {
                    try {
                        if (!data) {
                            return false;
                        }
                        if (!Object.hasOwn(data, key)) {
                            return true;
                        }
                        const decoded = decode(data[key], defaultValue, explicitType);
                        this.value = decoded;
                        return true;
                    } catch {
                        this.value = cloneDefault();
                        return false;
                    }
                },
            };

            this.#listeners.set(key, new Set());
            this.#fieldKeys.add(key);

            return this;
        }
        hasField(/** @type {string} */ key) {
            return this.#fieldKeys.has(key);
        }
        fieldKeys() {
            return [...this.#fieldKeys];
        }
        fields() {
            return /** @type {StoreField<any>[]} */ (this.fieldKeys().map(key => this[key]));
        }
        fieldEntries() {
            return /** @type {[key: string, field: StoreField<any>][]} */ (this.fieldKeys().map(key => [key, this[key]]));
        }
        loadAll() {
            this.fields().forEach(field => field.load());
        }
        // avoid using saveAll
        saveAll(dryRun = false) {
            this.fields().forEach(field => field.save(dryRun));
        }
        unsubscribeAll() {
            for (const fieldListeners of this.#listeners.values()) {
                fieldListeners.clear();
            }
        }
        /**
         * Exports all fields to a serializable object.
         * @returns {Object}
         */
        export() {
            const individualData = this.fields().map(field => field.export())
            const joinedData = {};
            Object.assign(joinedData, ...individualData);
            return joinedData;
        }
        /**
         * Takes in a serializable object and import the data to fields with matching keys.
         * 
         * If import was unsuccessful, field values will partially represent the data up to the point it failed. It is recommended that you manual load after a failure.
         * It was designed this way to enable debugging.
         * @param {Object} data 
         * @param {string} [name] 
         * @returns {boolean} Returns true or false if the import was successful.
         */
        import(data, name = null) {
            if (!data) {
                return true;
            }
            try {
                let successCount = 0;
                for (const [key, field] of this.fieldEntries()) {
                    const successful = field.import(data);
                    if (successful) {
                        successCount += 1;
                    } else {
                        logger.storeUpdates.warn(`Batch import failed${name ? ' on ' + name : ''}. Store key (${key}) failed to import. Data:`, data[key]);
                        return false;
                    }
                }
                logger.storeUpdates.success(`Batch import successfull${name ? ' for ' + name : ''}. Imported ${successCount}/${Object.entries(data).length} values from data.`);
                return true;
            } catch (e) {
                logger.storeUpdates.error(`Batch import failed${name ? ' on ' + name : ''}. An error has occurred. Data:`, data, 'Error:', e);
                return false;
            }
        }
    }
    //#endregion

    //#region Patches
    const patchOk = (data) => /** @type {PatchOk} */ ({ ok: true, data });
    const patchFail = (issue, ctx) => /** @type {PatchFail} */ ({ ok: false, issue, ctx });
    const reportPatchFail = (/** @type {PatchFail} */ result) => reportIssue(result.issue, result.ctx);

    /**
     * Applies patch to object wtihout mutating it. If successful, `data` is a new object with the patch applied.
     * Possible failure reasons: `INVALID_PATCH`, `INVALID_PATCH_ARRAY`, `PATCH_ARRAY_REMOVE_FAIL`, `PATCH_ARRAY_PROMOTION_FAIL`
     * @param {object} obj 
     * @param {Patch} patch 
     * @param {string[]} arrayKeys 
     * @returns {PatchOk | PatchFail}
     */
    function patchObject(obj, patch, arrayKeys = []) {
        if (!(obj && typeof obj === 'object' && patch && typeof patch === 'object')) {
            return patchFail('INVALID_PATCH', { obj, patch, arrayKeys });
        }

        const newObj = objectDeepCopy(obj);

        for (const [patchTarget, patchValue] of Object.entries(patch)) {
            const arrayKey = arrayKeys.find(key => key === patchTarget);
            if (arrayKey) {
                if (!newObj[arrayKey]) {
                    newObj[arrayKey] = [];
                }
                const result = patchArray(newObj[arrayKey], patchValue);
                if (!result.ok) {
                    return result;
                }
            } else {
                newObj[patchTarget] = patchValue;
            }
        }

        return patchOk(newObj);
    }

    /**
     * Applies array patch to an array in the object.
     * 
     * Possible failure reasons: `INVALID_PATCH_ARRAY`, `PATCH_ARRAY_REMOVE_FAIL`, `PATCH_ARRAY_PROMOTION_FAIL`
     * @param {object} arr 
     * @param {ArrayPatch} arrayPatch 
     * @returns {PatchOk | PatchFail}
     */
    function patchArray(arr, arrayPatch) {
        const patchFailInvalid = () => patchFail('INVALID_PATCH_ARRAY', { arr, arrayPatch });
        const patchFailRemove = () => patchFail('PATCH_ARRAY_REMOVE_FAIL', { arr, arrayPatch });
        const patchFailPromotion = () => patchFail('PATCH_ARRAY_PROMOTION_FAIL', { arr, arrayPatch });
        const isInvalid = (value) => (value == null || value === '');
        const idIsInvalid = () => isInvalid(arrayPatch.id);
        const idKeyIsInvalid = () => isInvalid(arrayPatch.idKey);

        if (!Array.isArray(arr) || arrayPatch == null || typeof arrayPatch !== 'object' || !arrayPatch.op ) {
            return patchFailInvalid();
        }

        switch (arrayPatch.op) {
            // eventually merge obj?
            case 'push': {
                if (isInvalid(arrayPatch.value)) {
                    return patchFailInvalid();
                }

                if (!arrayPatch.unique || !arr.includes(arrayPatch.value)) {
                    arr.push(arrayPatch.value);
                }

                return patchOk(arr);
            }

            case 'pushObj': {
                if (arrayPatch.value == null) {
                    return patchFailInvalid();
                }
                if (arrayPatch.unique && (idKeyIsInvalid() || isInvalid(arrayPatch.value[arrayPatch.idKey]))) {
                    return patchFailInvalid();
                }

                if (!arrayPatch.unique) {
                    arr.push(arrayPatch.value);
                } else {
                    const i = arr.findIndex(x => x[arrayPatch.idKey] === arrayPatch.value[arrayPatch.idKey]);
                    if (i === -1) {
                        arr.push(arrayPatch.value);
                    } else {
                        arr[i] = arrayPatch.value;
                    }
                }

                return patchOk(arr);
            }

            case 'remove': {
                if (idIsInvalid()) {
                    return patchFailInvalid();
                };

                const index = arr.findIndex(x => x === arrayPatch.id);

                if (index === -1) {
                    return patchFailRemove();
                }

                arr.splice(index, 1);

                return patchOk(arr);
            }

            case 'removeObj': {
                if (idKeyIsInvalid() || idIsInvalid()) {
                    return patchFailInvalid();
                };

                const index = arr.findIndex(x => x[arrayPatch.idKey] === arrayPatch.id);

                if (index === -1) {
                    return patchFailRemove();
                }

                arr.splice(index, 1);

                return patchOk(arr);
            }

            case 'removeAt': {
                if (!Number.isFinite(arrayPatch.index)) {
                    return patchFailInvalid();
                }
                if (isInvalid(arr.at(arrayPatch.index))) {
                    return patchFailRemove();
                }

                arr.splice(arrayPatch.index, 1);
                
                return patchOk(arr);
            }

            case 'promote': {
                if (idKeyIsInvalid() || idIsInvalid()) {
                    return patchFailInvalid();
                };

                const index = arr.findIndex(x => x[arrayPatch.idKey] === arrayPatch.id);

                if (index === -1) {
                    return patchFailPromotion();
                }
                if (index === 0) {
                    return patchOk(arr);
                }

                const [item] = arr.splice(index);
                arr.unshift(item);

                return patchOk(arr);
            }

            case 'replaceAll': {
                if (!Array.isArray(arrayPatch.value)) {
                    return patchFailInvalid();
                };
                
                arr.length = 0;
                arr.push(...arrayPatch.value)

                return patchOk(arr);
            }

            default:
                return patchFailInvalid();
        }
    }

    /**
     * Modifies existing favorite with a patch.  
     * Possible failure reasons: `FAVORITE_MISSING`, `INVALID_PATCH`, `INVALID_PATCH_ARRAY`, `PATCH_ARRAY_PROMOTION_FAIL`.  
     * Under normal conditions, it's usually only `FAVORITE_MISSING` or `PATCH_ARRAY_PROMOTION_FAIL`.
     * @example
     * const result = patchFavorite('/g/123456', {
     *     note: 'Ice Elf Suck',
     *     alt_sources: { op: 'pushObj', value: { ... }, unique: true, idKey: 'link' },
     * });
     * if (result.ok) {
     *     const favoriteData = result.data;
     * } else {
     *     reportPatchFail(result);
     * }
     * @param {GalleryPath} galleryPath
     * @param {Patch} patch
     * @param {boolean} dryRun
     * @returns {{ok: true, data: FavoriteData} | PatchFail}
     */
    function patchFavorite(galleryPath, patch, dryRun = false) {
        const favoriteData = dataStore.favoriteGalleries.load().get(galleryPath);

        if (!favoriteData) {
            return patchFail('FAVORITE_MISSING', { galleryPath });
        }
        
        const result = patchObject(favoriteData, patch, ['alt_sources', 'labels']);

        if (!result.ok) {
            if (result.issue === 'PATCH_ARRAY_REMOVE_FAIL') {
                return patchOk(favoriteData);
            }
            return result;
        }

        if (logger.storeUpdates.shouldLog(logger.LEVELS.LOG)) {
            const changes = Object.keys(patch).reduce(
                (acc, k) => {
                    acc.before[k] = favoriteData[k];
                    acc.after[k] = result.data[k];
                    return acc;
                },
                { before: {}, after: {} }
            );
            logger.storeUpdates.log(`Favorite data for ${galleryPath} patched successfully.`, '\nPatch:', patch, '\nBefore:', changes.before, '\nAfter:', changes.after);
        }
        
        Object.assign(favoriteData, result.data);
        dataStore.favoriteGalleries.save(dryRun);

        return patchOk(favoriteData);
    }
    /**
     * Modifies existing read later gallery with a patch.  
     * Possible failure reasons: `READ_LATER_MISSING`, `INVALID_PATCH`, `INVALID_PATCH_ARRAY`.  
     * @example
     * const result = patchReadLater('/g/123456', { read_priority: 3 });
     * if (result.ok) {
     *     const readLaterData = result.data;
     * } else {
     *     reportPatchFail(result);
     * }
     * @param {GalleryPath} galleryPath
     * @param {Patch} patch
     * @param {boolean} dryRun
     * @returns {{ok: true, data: ReadLaterData} | PatchFail}
     */
    function patchReadLater(galleryPath, patch, dryRun = false) {
        const readLaterData = dataStore.readLater.load().get(galleryPath);

        if (!readLaterData) {
            return patchFail('READ_LATER_MISSING', { galleryPath });
        }
        
        const result = patchObject(readLaterData, patch, ['labels']);

        if (!result.ok) {
            if (result.issue === 'PATCH_ARRAY_REMOVE_FAIL') {
                return patchOk(readLaterData);
            }
            return result;
        }

        if (logger.storeUpdates.shouldLog(logger.LEVELS.LOG)) {
            const changes = Object.keys(patch).reduce(
                (acc, k) => {
                    acc.before[k] = readLaterData[k];
                    acc.after[k] = result.data[k];
                    return acc;
                },
                { before: {}, after: {} }
            );
            logger.storeUpdates.log(`Read Later data for ${galleryPath} patched successfully.`, '\nPatch:', patch, '\nBefore:', changes.before, '\nAfter:', changes.after);
        }
        
        Object.assign(readLaterData, result.data);
        dataStore.readLater.save(dryRun);

        return patchOk(readLaterData);
    }
    /**
     * Modifies existing read later gallery with a patch.  
     * Possible failure reasons: `BROWSE_LATER_MISSING`, `INVALID_PATCH`, `INVALID_PATCH_ARRAY`.  
     * @example
     * const result = patchBrowseLater('/tag/milf/', { browse_priority: 3 });
     * if (result.ok) {
     *     const browseLaterData = result.data;
     * } else {
     *     reportPatchFail(result);
     * }
     * @param {PageId} pageId
     * @param {Patch} patch
     * @param {boolean} dryRun
     * @returns {{ok: true, data: BrowseLaterData} | PatchFail}
     */
    function patchBrowseLater(pageId, patch, dryRun = false) {
        const browseLaterData = dataStore.browseLater.load().get(pageId);

        if (!browseLaterData) {
            return patchFail('BROWSE_LATER_MISSING', { pageId });
        }
        
        const result = patchObject(browseLaterData, patch, ['labels']);

        if (!result.ok) {
            if (result.issue === 'PATCH_ARRAY_REMOVE_FAIL') {
                return patchOk(browseLaterData);
            }
            return result;
        }

        if (logger.storeUpdates.shouldLog(logger.LEVELS.LOG)) {
            const changes = Object.keys(patch).reduce(
                (acc, k) => {
                    acc.before[k] = browseLaterData[k];
                    acc.after[k] = result.data[k];
                    return acc;
                },
                { before: {}, after: {} }
            );
            logger.storeUpdates.log(`Browse Later data for ${pageId} patched successfully.`, '\nPatch:', patch, '\nBefore:', changes.before, '\nAfter:', changes.after);
        }
        
        Object.assign(browseLaterData, result.data);
        dataStore.browseLater.save(dryRun);

        return patchOk(browseLaterData);
    }
    //#endregion

    //#region Ops
    /**
     * Moves customizations from one gallery to another.
     * 
     * Possible failure reasons: `MIGRATION_TARGET_SELF`, `FAVORITE_MISSING`, `MIGRATION_TARGET_IS_FAVORITE`, `CANNOT_FAVORITE_API_FAIL`
     * @param {GalleryPath} favoriteToMigratePath 
     * @param {GalleryPath} migrationTargetPath 
     * @param {boolean} dryRun
     * @returns {Promise<PatchOk | PatchFail>}
     */
    async function opMigrateFavorite(favoriteToMigratePath, migrationTargetPath, dryRun = false) {
        if (migrationTargetPath == favoriteToMigratePath) {
            return patchFail('MIGRATION_TARGET_SELF');
        }

        const favoriteData = dataStore.favoriteGalleries.load().get(favoriteToMigratePath);
        
        if (!favoriteData) {
            return patchFail('FAVORITE_MISSING', { galleryPath: favoriteToMigratePath });
        }

        // make sure new gallery is not favorite (prevent foot shooting)
        if (dataStore.favoriteGalleries.value.has(migrationTargetPath)) {
            return patchFail('MIGRATION_TARGET_IS_FAVORITE', { sourcePath: favoriteToMigratePath, targetPath: migrationTargetPath });
        }
        
        const newGalleryData = await getOrPullGalleryCacheData(migrationTargetPath);

        if (!newGalleryData) {
            return patchFail('CANNOT_FAVORITE_API_FAIL', { galleryPath: migrationTargetPath });
        }

        const migratedFavoriteData = objectDeepCopy(favoriteData);

        // migrate existing customization to new gallery
        Object.assign(migratedFavoriteData, objectDeepCopy(newGalleryData));
        dataStore.favoriteGalleries.value.set(migrationTargetPath, migratedFavoriteData);
        dataStore.favoriteGalleries.value.delete(favoriteToMigratePath);
        dataStore.favoriteGalleries.save(dryRun);

        logger.storeUpdates.log(`Migrated customizations for ${favoriteToMigratePath} to ${migrationTargetPath}.\n`, favoriteToMigratePath, favoriteData, '\n', migrationTargetPath, migratedFavoriteData);

        return patchOk(migratedFavoriteData);
    }
    /**
     * Moves read later from one gallery to another.
     * 
     * Possible failure reasons: `MIGRATION_TARGET_SELF`, `READ_LATER_MISSING`, `MIGRATION_TARGET_IS_READ_LATER`, `CANNOT_READ_LATER_API_FAIL`
     * @param {GalleryPath} readLaterToMigratePath 
     * @param {GalleryPath} migrationTargetPath 
     * @param {boolean} dryRun
     * @returns {Promise<PatchOk | PatchFail>}
     */
    async function opMigrateReadLater(readLaterToMigratePath, migrationTargetPath, dryRun = false) {
        if (migrationTargetPath == readLaterToMigratePath) {
            return patchFail('MIGRATION_TARGET_SELF');
        }

        const readLaterData = dataStore.readLater.load().get(readLaterToMigratePath);
        
        if (!readLaterData) {
            return patchFail('READ_LATER_MISSING', { galleryPath: readLaterToMigratePath });
        }

        // make sure new gallery is not read later (prevent foot shooting)
        if (dataStore.readLater.value.has(migrationTargetPath)) {
            return patchFail('MIGRATION_TARGET_IS_READ_LATER', { sourcePath: readLaterToMigratePath, targetPath: migrationTargetPath });
        }
        
        const newGalleryData = await getOrPullGalleryCacheData(migrationTargetPath);

        if (!newGalleryData) {
            return patchFail('CANNOT_READ_LATER_API_FAIL', { galleryPath: migrationTargetPath });
        }

        const migratedReadLaterData = objectDeepCopy(readLaterData);

        // migrate existing read later to new gallery
        Object.assign(migratedReadLaterData, objectDeepCopy(newGalleryData));
        dataStore.readLater.value.set(migrationTargetPath, migratedReadLaterData);
        dataStore.readLater.value.delete(readLaterToMigratePath);
        dataStore.readLater.save(dryRun);

        logger.storeUpdates.log(`Migrated read later for ${readLaterToMigratePath} to ${migrationTargetPath}.\n`, readLaterToMigratePath, readLaterData, '\n', migrationTargetPath, migratedReadLaterData);

        return patchOk(migratedReadLaterData);
    }
    /**
     * Changes the sentiment of a tag.
     * 
     * Possible failure reasons: `CANNOT_CHANGE_TAG_SENTIMENT_API_FAIL`
     * @param {TagPath} tagPath 
     * @param {'liked'|'dubious'|'scorned'} sentimentStatus 
     * @param {boolean} dryRun
     * @returns {Promise<PatchOk | PatchFail>}
     */
    async function opSetTagSentiment(tagPath, sentimentStatus, dryRun = false) {
        let sentimentData = dataStore.tagSentiments.load().get(tagPath);

        if (sentimentData) {
            sentimentData.status = sentimentStatus;
            sentimentData.added_at = getUnixTimestamp();
        } else {
            let tagData = cachedApiData.tags.get(tagPath);
            if (!tagData) {
                const tagInfo = tagInfoFromPath(tagPath);
                const apiData = await apiEndpoints.tag.fetch(tagInfo.type, tagInfo.name);
                cachedApiData.tags.addData(apiData);
                tagData = cachedApiData.tags.get(tagPath);
                if (!tagData) {
                    return patchFail('CANNOT_CHANGE_TAG_SENTIMENT_API_FAIL', { status: sentimentStatus, tagPath: tagPath });
                }
            }

            sentimentData = {
                status: sentimentStatus,
                id: tagData.id,
                name: tagData.name,
                added_at: getUnixTimestamp(),
            }

            dataStore.tagSentiments.value.set(tagPath, sentimentData);
        }

        dataStore.tagSentiments.save(dryRun);
        logger.storeUpdates.log(`Tag ${tagPath} marked ${sentimentData.status}.`);

        return patchOk(sentimentData);
    }
    /**
     * Imports info from json and overwrites the dataStore.
     * 
     * Possible failure reasons: `IMPORT_FROM_FILE_FAILED`
     * @param {string} json 
     * @returns {Promise<PatchOk | PatchFail>}
     */
    async function opImportDataFromJson(json) {
        let parsedData;
        try {
            parsedData = JSON.parse(json);
        } catch {
            return patchFail('IMPORT_FROM_FILE_FAILED', {});
        }

        const resetData = () => {
            metaStore.dataVersion.load();
            settingsStore.loadAll();
            settingsStore.loadAll();
            dataStore.loadAll();
        }
        
        const dataVersion = parsedData.dataVersion;
        if (!dataVersion) {
            resetData();
            return patchFail('IMPORT_FROM_FILE_FAILED', {});
        }
        metaStore.dataVersion.value = dataVersion;
        
        const secretsData = parsedData.secrets ?? parsedData.secretStore; // accidently put in the wrong name, gotta support both
        if (secretsData) {
            const successful = secretStore.import(secretsData, 'Secrets');
            if (!successful) {
                resetData();
                return patchFail('IMPORT_FROM_FILE_FAILED', {});
            }
        }

        const settingsData = parsedData.settings;
        if (settingsData) {
            const successful = settingsStore.import(settingsData, 'Settings');
            if (!successful) {
                resetData();
                return patchFail('IMPORT_FROM_FILE_FAILED', {});
            }
        }

        const generalData = parsedData.data;
        if (generalData) {
            const successful = dataStore.import(generalData, 'Data');
            if (!successful) {
                resetData();
                return patchFail('IMPORT_FROM_FILE_FAILED', {});
            }
        }

        metaStore.dataVersion.save();
        secretStore.saveAll();
        settingsStore.saveAll();
        dataStore.saveAll();

        logger.storeUpdates.debug('Import ok.');
        await checkDataVersion();
        return patchOk();
    }
    /**
     * Removes a given label from all existing data that use labels.
     * 
     * Possible failure reasons: none
     * @param {string} labelToRemove 
     * @returns {PatchOk | PatchFail}
     */
    function opRemoveLabelFromAll(labelToRemove, dryRun = false) {
        if (!labelToRemove) {
            return patchOk({ favoriteGalleriesAffectedCount: 0, readLaterAffectedCount: 0 });
        }

        dataStore.favoriteGalleries.load();
        dataStore.readLater.load();
        dataStore.browseLater.load();
        
        let favoriteGalleriesAffectedCount = 0;
        dataStore.favoriteGalleries.value.values().forEach((favoriteData) => {
            const existingLabels = favoriteData.labels;
            if (existingLabels) {
                const originalLength = existingLabels.length;
                favoriteData.labels = existingLabels.filter((labelName) => labelName !== labelToRemove);
                favoriteGalleriesAffectedCount += favoriteData.labels.length != originalLength;
                
            }
        });

        let readLaterAffectedCount = 0;
        dataStore.readLater.value.values().forEach((readLaterData) => {
            const existingLabels = readLaterData.labels;
            if (existingLabels) {
                const originalLength = existingLabels.length;
                readLaterData.labels = existingLabels.filter((labelName) => labelName !== labelToRemove);
                readLaterAffectedCount += readLaterData.labels.length != originalLength;
            }
        });

        let browseLaterAffectedCount = 0;
        dataStore.browseLater.value.values().forEach((browseLaterData) => {
            const existingLabels = browseLaterData.labels;
            if (existingLabels) {
                const originalLength = existingLabels.length;
                browseLaterData.labels = existingLabels.filter((labelName) => labelName !== labelToRemove);
                browseLaterAffectedCount += browseLaterData.labels.length != originalLength;
            }
        });

        dataStore.favoriteGalleries.save(dryRun);
        dataStore.readLater.save(dryRun);
        dataStore.browseLater.save(dryRun);

        logger.storeUpdates.log(`Deleted label (${labelToRemove}) from existing sources. ${favoriteGalleriesAffectedCount} favorites affected, ${readLaterAffectedCount} readlater affected, and ${browseLaterAffectedCount} browselater affected.`);

        return patchOk({ favoriteGalleriesAffectedCount, readLaterAffectedCount, browseLaterAffectedCount });
    }
    /**
     * Renames a given label across all existing data that use labels.
     * 
     * Possible failure reasons: none
     * @param {string} labelToRename
     * @param {string} newLabelName
     * @returns {PatchOk | PatchFail}
     */
    function opRenameLabel(labelToRename, newLabelName, dryRun = false) {
        if (!labelToRename || !newLabelName) {
            return patchOk({ favoriteGalleriesAffectedCount: 0, readLaterAffectedCount: 0 });
        }

        settingsStore.labels.load();
        dataStore.favoriteGalleries.load();
        dataStore.readGalleries.load();
        
        const renameLabelInPlace = (labelArr) => {
            if (!labelArr) {
                return false;
            }
            const i = labelArr.findIndex(label => label === labelToRename);
            if (i === -1) {
                return false;
            }
            labelArr[i] = newLabelName;
            return true;
        }

        const settingsLabelArr = [...settingsStore.labels.value];
        const renameOk = renameLabelInPlace(settingsLabelArr);
        
        if (!renameOk) {
            return patchOk({ favoriteGalleriesAffectedCount: 0, readLaterAffectedCount: 0 });
        }

        settingsStore.labels.value = new Set(settingsLabelArr);

        let favoriteGalleriesAffectedCount = 0;
        dataStore.favoriteGalleries.value.values().forEach((favoriteData) => {
            if (renameLabelInPlace(favoriteData.labels)) {
                favoriteGalleriesAffectedCount += 1;
            }
        });

        let readLaterAffectedCount = 0;
        dataStore.readLater.value.values().forEach((readLaterData) => {
            if (renameLabelInPlace(readLaterData.labels)) {
                readLaterAffectedCount += 1;
            }
        });

        let browseLaterAffectedCount = 0;
        dataStore.browseLater.value.values().forEach((browseLaterData) => {
            if (renameLabelInPlace(browseLaterData.labels)) {
                browseLaterAffectedCount += 1;
            }
        });

        settingsStore.labels.save(dryRun);
        dataStore.favoriteGalleries.save(dryRun);
        dataStore.readLater.save(dryRun);

        logger.storeUpdates.log(`Renamed label (${labelToRename}) to (${newLabelName}). ${favoriteGalleriesAffectedCount} favorites affected, ${readLaterAffectedCount} readlater affected, and ${browseLaterAffectedCount} readlater affected.`);

        return patchOk({ favoriteGalleriesAffectedCount, readLaterAffectedCount, browseLaterAffectedCount });
    }

    /**
     * Set the read status of gallery. Only one status is allowed to be set. If there is an existing status it will remove it before changing it.
     * 
     * Possible failure reasons: none 
     * @param {GalleryPath} galleryPath 
     * @param {ReadStatus} status 
     * @param {boolean} dryRun 
     * @returns {PatchOk | PatchFail}
     */
    function opSetGalleryReadStatus(galleryPath, status, dryRun = false) {
        dataStore.readGalleries.load();
        dataStore.passedGalleries.load();
        dataStore.likedGalleries.load();
        const [previousStatus, previousReadTimestamp] = getGalleryReadStatus(galleryPath);
        const timestamp = previousReadTimestamp ?? getUnixTimestamp();

        if (status === 'read') {
            dataStore.readGalleries.value.set(galleryPath, timestamp);
            dataStore.readGalleries.save(dryRun);
            logger.storeUpdates.log(`Gallery (${galleryPath}) added to read list.`);
        }
        else if (previousStatus === 'read') {
            dataStore.readGalleries.value.delete(galleryPath);
            dataStore.readGalleries.save(dryRun);
            logger.storeUpdates.log(`Gallery (${galleryPath}) removed from read list.`);
        }

        if (status === 'passed') {
            dataStore.passedGalleries.value.set(galleryPath, timestamp);
            dataStore.passedGalleries.save(dryRun);
            logger.storeUpdates.log(`Gallery (${galleryPath}) added to passed list.`);
        }
        else if (previousStatus === 'passed') {
            dataStore.passedGalleries.value.delete(galleryPath);
            dataStore.passedGalleries.save(dryRun);
            logger.storeUpdates.log(`Gallery (${galleryPath}) removed from passed list.`);
        }

        if (status === 'liked') {
            dataStore.likedGalleries.value.set(galleryPath, timestamp);
            dataStore.likedGalleries.save(dryRun);
            logger.storeUpdates.log(`Gallery (${galleryPath}) added to liked list.`);
        }
        else if (previousStatus === 'liked') {
            dataStore.likedGalleries.value.delete(galleryPath);
            dataStore.likedGalleries.save(dryRun);
            logger.storeUpdates.log(`Gallery (${galleryPath}) removed from liked list.`);
        }

        return patchOk({ timestamp: status === 'none' ? null : timestamp });
    }
    //#endregion

    //#region Other
    // stuff that is not quite the level of an op, but doesn't have a better place to go
    function exportDataToFile(includeSecrets = false) {
        //settingsStore.loadAll(); // can cause problems since on settings page
        dataStore.loadAll();

        // update last backup date and format to string
        const newBackupDate = new Date();
        const dateStr = newBackupDate.toLocaleString('en-CA').slice(0, 10); // "2026-04-21"
        dataStore.lastBackupAt.value = newBackupDate;
        dataStore.lastBackupAt.save();

        const data = {
            dataVersion: metaStore.dataVersion.value,
            ...(includeSecrets && { secrets: secretStore.export() }),
            settings: settingsStore.export(),
            data: dataStore.export(),
        };
        const json = formatJsonToDepth(data, 2);
           
        const url = URL.createObjectURL(new Blob([json], { type: 'application/json' }));

        const a = document.createElement('a');
        a.href = url;
        a.download = `nhcb-backup-${dateStr}.json`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);

        logger.storeUpdates.log('New backup made.');
    }
    function addSeenExclude(galleryPath) {
        const seenExcludeDuration = 7200000; //2h
        tmpDataStore.seenGalleriesExclude.value.set(galleryPath, seenExcludeDuration + getUnixTimestamp());
        tmpDataStore.seenGalleriesExclude.save();
        logger.storeUpdates.log(`Gallery ${galleryPath} added to seen exclude list.`);
    }
    function pruneSeenExclude() {
        const excludes = tmpDataStore.seenGalleriesExclude.value.entries();
        const nowTimestamp = getUnixTimestamp();
        for (const [galleryPath, expiration] of excludes) {
            if (nowTimestamp > expiration || dataStore.seenGalleries.value.has(galleryPath)) {
                tmpDataStore.seenGalleriesExclude.value.delete(galleryPath);
                logger.storeUpdates.log(`Gallery ${galleryPath} removed from seen exclude list.`);
            }
        }
        tmpDataStore.seenGalleriesExclude.save();
    }
    /**
     * Gets the read status of a gallery.
     * @param {GalleryPath} galleryPath
     * @returns {[ReadStatus, UnixSeconds]|['none', null]}
     */
    function getGalleryReadStatus(galleryPath) {
        const readData = dataStore.readGalleries.value.get(galleryPath);
        if (readData) {
            return ['read', readData];
        }
        const passedData = dataStore.passedGalleries.value.get(galleryPath);
        if (passedData) {
            return ['passed', passedData];
        }
        const likedData = dataStore.likedGalleries.value.get(galleryPath);
        if (likedData) {
            return ['liked', likedData];
        }
        return ['none', null];
    }
    //#endregion
    //#endregion

    //#region -- Script Vars ----------------------------------------
    //#region Constants
    //#region App Info
    const APP_INFO = (() => {
        const versionNumber = GM_info.script.version;
        const projectSite = 'https://sleazyfork.org/en/scripts/584951-nhentai-custom-brew';
        const dataVersion = '1.1';
        const userAgent = `TamperMonkey-CustomBrew/${versionNumber} (${projectSite})`;
        return {
            VERSION: versionNumber,
            SITE: projectSite,
            USER_AGENT: userAgent,
            DATA_VERSION: dataVersion,
        };
    })();
    //#endregion
    
    //#region Tag Types
    const TAG_TYPES = (() => {
        const types = {
            TAG: 'tag',
            ARTIST: 'artist',
            CHARACTER: 'character',
            PARODY: 'parody',
            GROUP: 'group',
            LANGUAGE: 'language',
            CATEGORY: 'category',
        }
        /** @type {Set<TagType>} */
        const set = new Set(Object.values(types));

        const plurals = {
            [types.PARODY]: 'parodies',
            [types.CATEGORY]: 'categories',
        };

        return {
            ...types,
            has: (value) => set.has(value),
            values: () => [...set],
            plural: (str) => /** @type {string} */ (plurals[str] ?? str + 's'),
        };
    })();
    //#endregion

    //#region Page Types
    const PAGE_TYPES = (() => {
        /** @enum {string  & { __brand: 'PageType' }} */
        const PageType = {
            HOME: 'home',
            GALLERY: 'gallery',
            READER: 'reader',
            NAMESPACE: 'namespace', // why namespace? closest that fits that is visually distinct. E-hentai also uses that to denote tag types
            SEARCH: 'search',
            TAG_LIST: 'taglist',
            COMMUNITY: 'community',
            CUSTOM: 'custom',
            LOGIN: 'login',
            USER_FAVORITES: 'user-favorites',
            UNKNOWN: 'unkown',
        }

        /** @type {Set<PageType>} */
        const set = new Set(Object.values(PageType));

        /**
         * @param {string} pathname
         * @returns {PageType}
         */
        function findPageType(pathname) {
            if (pathname === '/') {
                return PageType.HOME;
            }
            else if (/^\/g\/\d+(\/)?$/.test(pathname)) {
                return PageType.GALLERY;
            }
            else if (/^\/g\/\d+\/\d+/.test(pathname)) {
                return PageType.READER;
            }
            else if (/^\/(parody|character|tag|artist|group|language|category)\/./.test(pathname)) {
                return PageType.NAMESPACE;
            }
            else if (/^\/search/.test(pathname)) {
                return PageType.SEARCH;
            }
            else if (/^\/(parodies|characters|tags|artists|groups|languages|categories)$/.test(pathname)) {
                return PageType.TAG_LIST;
            }
            else if (/^\/(community\/.|info$)/.test(pathname)) {
                return PageType.COMMUNITY;
            }
            else if (/^\/nhcb-./.test(pathname)) {
                return PageType.CUSTOM;
            }
            else if (/^\/login/.test(pathname)) {
                return PageType.LOGIN;
            }
            else if (/^\/user\/favorites/.test(pathname)) {
                return PageType.USER_FAVORITES;
            }
            return PageType.UNKNOWN;
        }

        return {
            ...PageType,
            get: findPageType,
            has: (value) => set.has(value),
            values: () => [...set],
        };
    })();
    //#endregion
    
    //#region Defaults and Definitions
    const DEFAULTS = {
        get LABEL_OPTIONS() { return ['goated', 'classic', 'memorable', 'funny/meme', 'series', 'genuine art']; },
        get PRIORITY() { return 0; },
        get PRIORITY_DROPDOWN_OPTIONS() { return [['4', 'Priority'], ['3', 'Highest'], ['2', 'Very High'], ['1', 'High'], ['0', 'Default'], ['-1', 'Low'], ['-2', 'Very Low']]; },
        get CONTENT_WARNING_CONFIG() {
            return /** @type {ContentWarningRule[]} */ ([
                {label: 'LSCAT', input: '/tag/low-scat/', logic: [100327]},
                {label: 'SCAT', input: '/tag/scat/,!/tag/low-scat/', logic: [2820,-100327]},
                {label: 'CORPA', input: '/tag/coprophagia/', logic: [16518]},
                {label: 'FARTING', input: '/tag/farting/', logic: [4935]},
                {label: 'GURO', input: '/tag/guro/', logic: [27217]},
                {label: 'SNUFF', input: '/tag/snuff/', logic: [10542]},
            ]);
        },
    };

    const DEFINITIONS =  {
        NORMALIZED_SEARCH_PARAMS_ORDER: ['q', 'sort', 'display-removed', 'labels', 'page', 'tagFilters'],
        RESERVED_LABELS: ['none'],
        COMMON_TAG_IDS: {
            ENLGISH: 12227,
            JAPANESE: 6346,
            CHINESE: 29963,
            MACHINE_TRANSLATION: 163002,
            ROUGH_TRANSLATION: 138277,
            INCOMPLETE: 31101,
            ANTHOLOGY: 10988, // compilation of various artists (older galleries used [Anthology] instead of (Various))
            GOUDOUSHI: 108118, // compilation of various artists
            COMPILATION: 7584, // compilation of a single artist
        },
        LANGUAGE_TAGS: [12227, 6346, 29963, 165194], // english, japanese, chinese, textless (community tag, not used as often as it should be)
        FAVORITE_CUSTOM_TITLE_MAX_LENGTH: 300, // some titles are just really long
        FAVORITE_NOTES_MAX_LENGTH: 300,
        BROWSE_LATER_NOTES_MAX_LENGTH: 150,
        WEBSITE_DEFAULT_CONTAINER_WIDTH: '1200', // not used as a default but instead for reference
        PRETTY_TITLE_DISPLAY_OPTIONS: [['always', 'Always'], ['nothover', 'While Not Hovered'], ['hover','While Hovered'], ['never', 'Never']],
        THUMBNAIL_MAX_HEIGHT_FROM_WIDTH_RATIO: 1.82,
        TAXONOMY_AGREEMENT: { KEY: 'nh.gts.agreed.v1', VALUE: 1},
        SPECIAL_SELECTORS: { AGE_GATE: '#app > .age-gate', ERROR_PAGE: '#app > .error-page', ERROR_PAGE_IMAGE: '#app > .error-page .error-image', CLOUDFLARE: '.main-wrapper > .main-content' },
        ERROR_404_IMAGE: { path: '/errors/404-white.webp', width: 1920, height: 1080 }
    };
    //#endregion

    //#region Custom Pages
    const CUSTOM_PAGES = (() => {
        // order deretmines order in nav bar
        const pages = {
            BROWSE_LATER: {
                path: '/nhcb-browse-later/',
                title: 'Browse Later',
                label: 'Browse Later',
                handler: addCustomBrowseLaterPage,
            },
            READ_LATER: {
                path: '/nhcb-read-later/',
                title: 'Read Later',
                label: 'Read Later',
                handler: addCustomReadLaterPage,
            },
            FAVORITES: {
                path: '/nhcb-favorites/',
                title: 'Favorite Galleries',
                label: 'Favorites',
                handler: addCustomFavoritesPage,
            },
            FAVORITE_TAGS: {
                path: '/nhcb-tags/',
                title: 'Liked Tags',
                label: 'Liked Tags',
                handler: addCustomTagsPage,
            },
            SETTINGS: {
                path: '/nhcb-settings/',
                title: 'CB - Settings',
                label: 'Settings',
                handler: addCustomSettingsPage,
            },
        }

        const specialPages = {
            RECOVERY_404: {
                asyncHandler: apply404RecoveryPage,
            }
        }

        /** @type {Map<string, {path: string, title: string, label: string, handler: function}>} */
        const map = new Map(Object.values(pages).map(page => [page.path, page]));

        return {
            ...pages,
            SPECIAL_PAGES: specialPages,
            get: (path) => map.get(path),
            has: (path) => map.has(path),
            values: () => [...map.values()],
        }
    })();
    //#endregion
    //#endregion

    //#region Data
    //#region Page Data
    const pageData = (() => {
        /**
         * Builds a {@link PageKey} for the current path. Used to track unique pages.  
         * Can override the current path by giving a `url`.
         * 
         * @param {URL} [url] 
         * @returns {PageKey}
         */
        function buildPageKey(url) {
            // the option to override using the url isn't actually needed but it shows intent better

            // reminder: doing it this way because some pages use fragments
            if (url) {
                return url.pathname + url.search;
            }
            return location.pathname + location.search;
        }
        /**
         * Similar to page key but does not include sorting params or other url data. Used to track pages that contain unique data sets.
         * 
         * @param {string} pathname
         * @param {string|null} query
         * @returns {PageId} eg `"/g/1234/"`, `"/search?q=hot+men+eating+beans`
         */
        function buildPageId(pathname, query) {
            const search = query ? `?${new URLSearchParams({ q: query })}` : '';
            return pathname + search;
        }
        
        // Special handler for 404 pages. Because this just happens for some reason
        // need trailing slash for store key uniformity, easier to fix it here
        const fixPagePath = (pageType, pagePath) => !pagePath.endsWith('/') && pageType === PAGE_TYPES.GALLERY ? pagePath + '/' : pagePath;

        function createPageData(/** @type {URL} */ url) {
            const pageType = PAGE_TYPES.get(url.pathname);
            const fixedPath = fixPagePath(pageType, url.pathname);
            const trimmedQuery = url.searchParams.get('q')?.trim();
            return /** @type {PageData} */ ({
                type: pageType,
                path: fixedPath,
                tagInfo: pageType === PAGE_TYPES.NAMESPACE ? tagInfoFromPath(url.pathname) : null,
                galleryId: pageType === PAGE_TYPES.GALLERY || pageType === PAGE_TYPES.READER ? pathToGalleryId(url.pathname) : null,
                searchParams: url.searchParams,
                query: trimmedQuery ?? '',
                id: buildPageId(fixedPath, trimmedQuery),
                key: buildPageKey(url),
                href: url.href,
            });
        }

        function refreshPageData() {
            const newUrl = new URL(location.href);
            const newData = createPageData(new URL(location.href));
            Object.assign(data, newData);
            data.layoutDepenenciesInitialized = false;
        }
        function isPage(/** @type {PageType} */ pageType) {
            return data.type === pageType;
        }

        function isNonStandardLayout() {
            // age gate
            if (document.querySelector(DEFINITIONS.SPECIAL_SELECTORS.AGE_GATE)) {
                return true;
            }
            // 429, 404, 500
            if (document.querySelector(DEFINITIONS.SPECIAL_SELECTORS.ERROR_PAGE)) {
                // document.querySelector('.error-image')
                // const errorCode = rateLimitImage.alt?.split(' ')[1];
                // const isRateLimit = errorCode === '429';
                return true;
            }
            // cloudflare rate limit
            if (document.querySelector(DEFINITIONS.SPECIAL_SELECTORS.CLOUDFLARE)) {
                return true;
            }
            return false;
        }
        
        const data = {
            refresh: refreshPageData,
            createKey: buildPageKey,
            isHomePage: () => isPage(PAGE_TYPES.HOME),
            isGalleryPage: () => isPage(PAGE_TYPES.GALLERY),
            isReaderPage: () => isPage(PAGE_TYPES.READER),
            isNamespacePage: () => isPage(PAGE_TYPES.NAMESPACE),
            isSearchPage: () => isPage(PAGE_TYPES.SEARCH),
            isTagListPage: () => isPage(PAGE_TYPES.TAG_LIST),
            isCommunityPage: () => isPage(PAGE_TYPES.COMMUNITY),
            isCustomPage: () => isPage(PAGE_TYPES.CUSTOM),
            isUnknownPage: () => isPage(PAGE_TYPES.UNKNOWN),
            isNonStandardLayout,
            layoutDepenenciesInitialized: false, // probably not the best place for this
            .../** @type {PageData} */ ({}), // stupid or genius, call it, friendo
        };

        return data;
    })();
    //#endregion

    //#region User Data
    const userData = (() => {
        let isLoggedIn = false;
        let accessToken = null;
        /** @type {UserData} */
        let userData = null; // not used because no way to get with current api

        function getAccessToken() {
            const m = document.cookie.match(new RegExp('(^|;\\s*)' + 'access_token' + '=([^;]*)'));
            return m ? decodeURIComponent(m[2]) : null;
        }

        function clearData() {
            isLoggedIn = false;
            userData = null;
            accessToken = null;
        }

        function checkIfLoggedIn () {
            accessToken = getAccessToken();
            isLoggedIn = accessToken != null;
            return isLoggedIn;
        }
        
        async function refeshData() {
            checkIfLoggedIn();
            // can't get data because endpoint is internal only
            // if (isLoggedIn && userData == null) {
            //     const data = await apiEndpoints.user.fetch();
            //     if (data) {
            //         userData = {
            //             id: data.id,
            //             username: data.username,
            //             slug: data.slug,
            //             avatar_url: data.avatar_url,
            //         };
            //     }
            // }
         }

        return {
            refreshData: refeshData,
            clear: clearData,
            checkIfLoggedIn: checkIfLoggedIn,
            get isLoggedIn() { return isLoggedIn; },
            get userToken() { return accessToken; },
            get info() { return userData; },
        };
    })();
    //#endregion

    //#region Cached Page Els
    const cachedPageEls = (() => {
        /** @type {Array<{el: HTMLElement, cover: HTMLElement, href: string, caption: HTMLElement, img: HTMLElement}}>} */
        const galleriesOnPage = [];
        /** @type {Array<{el: HTMLElement, href: string, typeStr: TagType, typeEl: HTMLElement, nameStr: string, nameEl: HTMLElement, countStr: string, countEl: HTMLElement, communityWrap: HTMLElement, isCommunity: boolean}}>} */
        const tagsOnPage = []
        const tagsHrefSet = new Set();

        function cacheElementsOnPage() {
            cachedPageEls.galleries.clear();
            document.querySelectorAll('.gallery').forEach(el => cachedPageEls.galleries.add(el));

            cachedPageEls.tags.clear();
            document.querySelectorAll('.tagchip').forEach(el => cachedPageEls.tags.add(el));
        }

        return {
            cacheElementsOnPage,
            galleries: {
                values() {
                    return galleriesOnPage;
                },
                add(/** @type {HTMLElement} */ el) {
                    const cover = el.querySelector('a.cover');
                    const href = cover?.getAttribute('href');
                    const caption = el.querySelector('div.caption');
                    const img = el.querySelector('a.cover > img');

                    galleriesOnPage.push({el, cover, href, caption, img});
                },
                clear() {
                    galleriesOnPage.length = 0;
                },
                get size() {
                    return galleriesOnPage.length;
                },
                forEach: galleriesOnPage.forEach.bind(galleriesOnPage),
            },
            tags: {
                values() {
                    return tagsOnPage;
                },
                add(/** @type {HTMLElement} */ el) {
                    const href = el.getAttribute('href');
                    // due to tag suggestions, it is possible for tentative tags to not have pages
                    if (!href) {
                        return;
                    }
                    const tagInfo = tagInfoFromPath(href); // do not get tag info from element text. If you do, trim it!
                    const nameEl = el.querySelector('span.name');
                    const countEl = el.querySelector('span.count');
                    const countStr = countEl?.textContent.trim();
                    const communityWrap = el.querySelector('span.cm-wrap');
                    const isCommunity = communityWrap != null; // can be either community suggested tag for gallery or community suggested tag for website
                    const typeEl = el.querySelector('span.type');

                    tagsOnPage.push({el, href, typeStr: tagInfo.type, typeEl, nameStr: tagInfo.name.replaceAll('-', ' '), nameEl, countStr, countEl, communityWrap, isCommunity });
                    tagsHrefSet.add(href);
                },
                clear() {
                    tagsOnPage.length = 0;
                    tagsHrefSet.clear();
                },
                get size() {
                    return tagsOnPage.length;
                },
                has(href) {
                    return tagsHrefSet.has(href);
                },
                forEach: tagsOnPage.forEach.bind(tagsOnPage),
            }
        };
    })();
    //#endregion

    //#region Cached Api Data
    const cachedApiData = (() => {
        const galleryApiData = /** @type {Map<GalleryPath, GalleryData>} */ (new Map());
        const tagApiData = /** @type {Map<TagPath, TagData>} */ (new Map());
        
        function normalizeGalleryData(data) {
            return /** @type {GalleryData} */ ({
                id: data.id,
                media_id: data.media_id,
                english_title: data.title?.english ?? data.english_title,
                japanese_title: data.title?.japanese ?? data.japanese_title ?? null,
                thumbnail: data.thumbnail.path ?? data.thumbnail,
                thumbnail_width: data.thumbnail?.width ?? data.thumbnail_width,
                thumbnail_height: data.thumbnail?.height ?? data.thumbnail_height,
                num_pages: data.num_pages,
                num_favorites: data.num_favorites ?? null,
                tag_ids: data.tags ? data.tags.map(({id}) => id) : data.tag_ids,
                //blacklisted: data.blacklisted ?? false, // I have not found a case where this will show true or be useful
            });
        }

        function normalizeTagData(data) {
            return /** @type {TagData} */ ({
                id: data.id,
                type: data.type,
                name: data.name,
                url: data.url,
                count: data.count,
                description: data.description ?? null,
                is_community: data.is_community ?? null,
                pending_describe_id: data.pending_describe_id ?? null,
            });
        }

        return {
            galleries: {
                get: galleryApiData.get.bind(galleryApiData),
                set: galleryApiData.set.bind(galleryApiData),
                has: galleryApiData.has.bind(galleryApiData),
                values: galleryApiData.values.bind(galleryApiData),
                keys: galleryApiData.keys.bind(galleryApiData),
                entries: galleryApiData.entries.bind(galleryApiData),
                get size() { return galleryApiData.size },
                addData(/** @type {Array<Object|GalleryData>} */ ...galleryData) {
                    galleryData.filter(data => data?.id != null).forEach((data) => galleryApiData.set(galleryIdToPath(data.id), normalizeGalleryData(data)));
                }
            },
            tags: {
                get: tagApiData.get.bind(tagApiData),
                set: tagApiData.set.bind(tagApiData),
                has: tagApiData.has.bind(tagApiData),
                values: tagApiData.values.bind(tagApiData),
                keys: tagApiData.keys.bind(tagApiData),
                entries: tagApiData.entries.bind(tagApiData),
                get size() { return tagApiData.size },
                addData(/** @type {Array<Object|TagData>} */ ...tagData) {
                    // why the url exists on the tag info but not the gallery info
                    tagData.filter(data => data?.url != null).forEach(data => tagApiData.set(data.url, normalizeTagData(data)));
                }
            },
        };
    })();
    //#endregion

    //#region Caculated Data
    const calculatedData = (() => {
        /** @type {Map<int, TagSentiment>} */
        let artistTagSentiments;
        /** @type {Map<int, BrowseLaterData>} */
        let artistBrowseLater;

        function findArtistTagSentiments() {
            const artistTypes = ['artist', 'group'];
            artistTagSentiments = new Map([...dataStore.tagSentiments.value.entries()].filter(([tagPath, tagSentiment]) => artistTypes.includes(tagInfoFromPath(tagPath).type)).map(([tagPath, tagSentiment]) => ([tagSentiment.id, tagSentiment])));
        }
        function findArtistBrowseLater() {
            const artistTypes = ['artist', 'group'];
            artistBrowseLater = new Map([...dataStore.browseLater.value.entries()].filter(([tagPath, browseLaterData]) => browseLaterData.not_tag != false && artistTypes.includes(tagInfoFromPath(tagPath).type)).map(([tagPath, browseLaterData]) => ([browseLaterData.tag_id, browseLaterData])));
        }

        function onNewPage() {
            findArtistTagSentiments();
            findArtistBrowseLater();
        }

        return {
            recalculate: onNewPage,
            get artistTagSentiments() { return artistTagSentiments },
            get artistBrowseLater() { return artistBrowseLater },
        };
    })();
    //#endregion
    //#endregion

    //#region Persistant Elements
    const notifier = createNotifier(10);
    //#endregion

    //#region  Data Stores
    // Note: Field names should be unique per backend
    const secretStore = new Store(storeBackends.gm)
        .addField('apiKey', /** @type {string} */ (''))
        .addField('username', /** @type {string} */ (''))
        .addField('password', /** @type {string} */ (''));
    const settingsStore = new Store(storeBackends.gm)
        // auto login
        .addField('enableAutoLogin', /** @type {boolean} */ (false))
        .addField('enableAutoFillForLogin', /** @type {boolean} */ (true))
        .addField('autoSubmitAfterAutoFill', /** @type {boolean} */ (false))
        // labels
        .addField('labels', /** @type {Set<string>} */ (new Set(DEFAULTS.LABEL_OPTIONS)))
        // view system
        .addField('enableViewSystemButtons', /** @type {boolean} */ (true))
        .addField('enableBrowseSystemButtons', /** @type {boolean} */ (true))
        .addField('autoRemoveReadLaterIfRead', /** @type {boolean} */ (true))
        .addField('autoRemoveBrowseLaterIfBrowsed', /** @type {boolean} */ (true))
        .addField('autoSeenIfRead', /** @type {boolean} */ (true))
        .addField('autoSeenIfVisited', /** @type {boolean} */ (true))
        // tag sentiments
        .addField('enableTagSentimentButtons', /** @type {boolean} */ (true))
        .addField('enableTagSentimentHighlights', /** @type {boolean} */ (true))
        // badges
        .addField('enableViewSystemBadge', /** @type {boolean} */ (true))
        .addField('enableFavoriteGalleryBadge', /** @type {boolean} */ (true))
        .addField('enablePageCountBadge', /** @type {boolean} */ (true))
        .addField('enablePageCountBadgeColorIndicator', /** @type {boolean} */ (true))
        .addField('pageCountBadgeColorIndicatorBlendAmount', /** @type {number} */ (.6))
        .addField('adjustPageCountForMultiLang', /** @type {boolean} */ (false))
        .addField('enableArtistInfoBadge', /** @type {boolean} */ (true))
        .addField('enableArtistInfoAnthology', /** @type {boolean} */ (true))
        .addField('enableArtistInfoBrowseLater', /** @type {boolean} */ (true))
        .addField('enableArtistInfoTagSentiment', /** @type {boolean} */ (true))
        .addField('enableArtistInfoCompilation', /** @type {boolean} */ (true))
        .addField('enableBadTranslationBadge', /** @type {boolean} */ (true))
        .addField('enableBadTranslationRoughTranslationTag', /** @type {boolean} */ (true))
        .addField('enableBadTranslationMachineTranslationTag', /** @type {boolean} */ (false))
        .addField('enableBadTranslationMtlTitle', /** @type {boolean} */ (true))
        .addField('enableBadTranslationAiTranslateTitle', /** @type {boolean} */ (true))
        .addField('badTranslationMinConditions', /** @type {number} */ (2))
        .addField('enableIncompleteBadge', /** @type {boolean} */ (true))
        .addField('enableBrowseSystemBadges', /** @type {boolean} */ (true))
        .addField('enableBadgesOnBigCover', /** @type {boolean} */ (true))
        .addField('enableBcViewSystemBadge', /** @type {boolean} */ (true))
        .addField('enableBcFavoriteGalleryBadge', /** @type {boolean} */ (true))
        .addField('enableBcPageCountBadge', /** @type {boolean} */ (true))
        .addField('enableBcArtistInfoBadge', /** @type {boolean} */ (true))
        .addField('enableBcBadTranslationBadge', /** @type {boolean} */ (true))
        .addField('enableBcIncompleteBadge', /** @type {boolean} */ (true))
        .addField('enableBcContentWarningBadge', /** @type {boolean} */ (true))
        // opacity
        .addField('opacityReadLater', /** @type {number} */ (1))
        .addField('opacitLiked', /** @type {number} */ (0.6))
        .addField('opacityPassed', /** @type {number} */ (0.6))
        .addField('opacityRead', /** @type {number} */ (0.6))
        .addField('opacitySeen', /** @type {number} */ (0.9))
        .addField('opacityNotEnglish', /** @type {number} */ (0.2))
        // custom favorites
        .addField('enableCustomFavoritesButton', /** @type {boolean} */ (true))
        .addField('customFavoritesSeparateButton', /** @type {boolean} */ (true))
        .addField('allowRatingHalf', /** @type {boolean} */ (false))
        .addField('showRatingsOnCover', /** @type {boolean} */ (true))
        .addField('useTenPointRating', /** @type {boolean} */ (false))
        .addField('displayCustomTitles', /** @type {boolean} */ (true))
        // display adjustments
        .addField('galleryContainerWidth', /** @type {string|''} */ ('1300'))
        .addField('thumbnailContainerWidth', /** @type {string|''} */ ('1300'))
        .addField('thumbnailWidth', /** @type {string|''} */ ('244'))
        .addField('enableThumbnailCentering', /** @type {boolean} */ (true))
        .addField('enablePrettyTitleLists', /** @type {boolean} */ (true))
        .addField('prettyTitleListsShorten', /** @type {string|'always'|'hover'|'nothover'|'never'} */ ('never'))
        .addField('prettyTitleListsHighlight', /** @type {string|'always'|'hover'|'nothover'|'never'} */ ('always'))
        .addField('removeBorderOnButtonsWithTooltip', /** @type {boolean} */ (true))
        .addField('fixMultiLanguageGalleries', /** @type {string|'labelEnglish'|'multiFlag'|'disabled'} */ ('multiFlag'))
        // reader changes
        .addField('enableReaderAutoPlayer', /** @type {boolean} */ (true))
        .addField('readerDontExitOnArrowNav', /** @type {boolean} */ (true))
        .addField('readerEnableImprovedZoom', /** @type {boolean} */ (true))
        .addField('readerDontOverZoom', /** @type {boolean} */ (true))
        .addField('readerZoomCapImageNaturalSize', /** @type {boolean} */ (false))
        .addField('readerEnableFullscreen', /** @type {boolean} */ (true))
        .addField('readerFullscreenCapImageNaturalSize', /** @type {boolean} */ (false))
        // browsing
        .addField('enableJumpToPageOnElipsis', /** @type {boolean} */ (true))
        .addField('enableArrowKeyNavigationForPagination', /** @type {boolean} */ (true))
        .addField('enableEnglishOnlyButton', /** @type {boolean} */ (true))
        .addField('enableFixPipeButton', /** @type {boolean} */ (true))
        .addField('enableSortPopularMonthButton', /** @type {boolean} */ (true))
        .addField('hideGtsDescriptionIfNone', /** @type {boolean} */ (true))
        .addField('addTagChipFromSearch', /** @type {boolean} */ (true))
        .addField('copyTagOnClick', /** @type {boolean} */ (true))
        // gallery custom info
        .addField('enableGalleryCustomInfo', /** @type {boolean} */ (true))
        .addField('enableGalleryCustomInfoReadStatus', /** @type {boolean} */ (true))
        .addField('enableGalleryCustomInfoReadLaterStatus', /** @type {boolean} */ (true))
        .addField('enableGalleryCustomInfoReadLaterPriority', /** @type {boolean} */ (true))
        .addField('enableGalleryCustomInfoReadLaterLabels', /** @type {boolean} */ (true))
        .addField('enableGalleryCustomInfoFavoriteStatus', /** @type {boolean} */ (true))
        .addField('enableGalleryCustomInfoFavoriteRating', /** @type {boolean} */ (true))
        .addField('enableGalleryCustomInfoFavoriteLabels', /** @type {boolean} */ (true))
        .addField('enableGalleryCustomInfoFavoriteNote', /** @type {boolean} */ (true))
        .addField('hideGalleryCustomInfoReadIfFavorite', /** @type {boolean} */ (true))
        // caching
        .addField('requestCacheGalleryListTtl', /** @type {number} */ (2 * 60 * 1000))
        .addField('requestCacheGalleryTtl', /** @type {number} */ (20 * 60 * 1000))
        .addField('requestCacheTagTtl', /** @type {number} */ (120 * 60 * 1000))
        // auto refresh
        .addField('enableAutoRefreshRateLimitGallery', /** @type {boolean} */ (true))
        .addField('enableAutoRefreshCloudflareGallery', /** @type {boolean} */ (true))
        // misc
        .addField('groupTagNavLinks', /** @type {boolean} */ (true))
        .addField('enableNavDropdownFix', /** @type {boolean} */ (true))
        .addField('enableAutoPipeFix', /** @type {boolean} */ (true))
        .addField('enableTryAnotherSiteButton', /** @type {boolean} */ (true))
        .addField('addNavBarToErrorPages', /** @type {boolean} */ (true))
        .addField('bypassTaxonomyAgreement', /** @type {string|'nowating'|'enabled'|'disabled'} */ ('nowaiting'))
        .addField('bypassAgeGate', /** @type {boolean} */ (true))
        .addField('autoSubmitAgeGate', /** @type {boolean} */ (true))
        // content warning
        .addField('enableContentWarningBadge', /** @type {boolean} */ (true))
        .addField('contentWarningConfig', /** @type {ContentWarningRule[]} */ (DEFAULTS.CONTENT_WARNING_CONFIG));
    const dataStore = new Store(storeBackends.gm)
        .addField('readGalleries', /** @type {Map<GalleryPath, UnixSeconds>} */ (new Map()))
        .addField('likedGalleries', /** @type {Map<GalleryPath, UnixSeconds>} */ (new Map()))
        .addField('passedGalleries', /** @type {Map<GalleryPath, UnixSeconds>} */ (new Map()))
        .addField('seenGalleries', /** @type {Set<GalleryPath>} */ (new Set()))
        .addField('tagSentiments', /** @type {Map<TagPath, TagSentiment>} */ (new Map()))
        .addField('favoriteGalleries', /** @type {Map<GalleryPath, FavoriteData>} */ (new Map()))
        .addField('readLater', /** @type {Map<GalleryPath, ReadLaterData>} */ (new Map()))
        .addField('browsedPages', /** @type {Map<PageId, UnixSeconds>} */ (new Map()))
        .addField('browseLater', /** @type {Map<PageId, BrowseLaterData>} */ (new Map()))
        .addField('lastBackupAt', null, Date);
    const sessionStore = new Store(storeBackends.sessionStorage)
        .addField('zoomLevel', /** @type {number} */ (1.0))
        .addField('autoPlayEnabled', /** @type {boolean} */ (false));
    const tmpDataStore = new Store(storeBackends.gm)
        .addField('seenGalleriesExclude', /** @type {Map<GalleryPath, UnixSeconds>} */ (new Map()))
        .addField('autoPlayerDelay', /** @type {number} */ (10));
    const localStore = new Store(storeBackends.localStorageBackend)
        .addField('cachedApiRequests', /** @type {Map<string, CachedResponse>} */ (new Map()));
    const metaStore = new Store(storeBackends.gm)
        .addField('dataVersion', /** @type {string} */ ('')) // change to 'default' on Oct 2027
        .addField('migrationLock', /** @type {number} */ (-1)) // timestamp, if Date.Now() > migrationLock, assume unlocked

    function loadData() {
        metaStore.dataVersion.load(); // background updates can update in another tab
        secretStore.loadAll();
        settingsStore.loadAll();
        dataStore.loadAll();
        sessionStore.loadAll();
        tmpDataStore.loadAll();
        // localStore.cachedApiRequests.load(); // handled by api cache directly
    }
    //#endregion

    //#region API Vars
    // reminder: cant group this with other constants because it is dependent on setting store
    const SCRIPT_FETCH_TIMEMOUT = 15 * 1000;
    
    const CACHE_ENDPOINT_TARGETS = (() => {
        const TTL_GALLERY_LIST = settingsStore.requestCacheGalleryListTtl.load();
        const TTL_GALLERY = settingsStore.requestCacheGalleryTtl.load();
        const TTL_TAG = settingsStore.requestCacheTagTtl.load(); // only used by tag endpoint, which is generally only used to grab tag id

        return [
            { pattern: /\/api\/v2\/galleries\?/i,  ttl: TTL_GALLERY_LIST, name: 'galleries'},
            { pattern: /\/api\/v2\/galleries\/popular$/i, ttl: TTL_GALLERY_LIST, name: 'popular'},
            { pattern: /\/api\/v2\/galleries\/\d+($|\?)/i, ttl: TTL_GALLERY, name: 'gallery'},
            { pattern: /\/api\/v2\/galleries\/tagged\?/i, ttl: TTL_GALLERY_LIST, name: 'tagged'},
            { pattern: /\/api\/v2\/tags\/.+\/.+/i, ttl: TTL_TAG, name: 'tag'},
            { pattern: /\/api\/v2\/search\?/i, ttl: TTL_GALLERY_LIST, name: 'search'},
            { pattern: /\/api\/v2\/favorites\?/i, ttl: TTL_GALLERY_LIST, name: 'userFavorites'},
        ]
    })();

    const originalFetch = unsafeWindow.fetch;
    //#endregion
    //#endregion

    //#region  -- Cleanup Page ----------------------------------------
    // See note #SvelteClean
    const cleaner = (() => {
        /** @type {{el: HTMLElement, func: (el: HTMLElement) => void}[]} */
        const tasks = [];

        function cleanup() {
            tasks.forEach(({el, func}) => {
                if (el && func && document.contains(el)) {
                    func(el);
                }
            });
            tasks.length = 0; // HOW LONG WAS THIS MISSING AND HOW WERE THINGS STILL WORKING
        }
        function addTask(el, func) {
            tasks.push({el: factoryUnwrapEl(el), func});
        }
        function addTaskNoFail(func) {
            addTask(document.body, func);
        }
        function addTaskRemoveElement(el) {
            addTask(el, (el) => el.remove());
        }
        function addTaskRemoveClass(el, ...classNames) {
            addTask(el, (el) => classNames.forEach(className => el.classList.remove(className)));
        }

        return { get count() { return tasks.length; }, cleanup, addTask, addTaskNoFail, addTaskRemoveElement, addTaskRemoveClass };
    })();

    const injector = (() => {
        /**
         * Inject an element into a page as a child to a parent element.
         * @param {FactoryChild} parent
         * @param {FactoryChild} child
         * @param {-1|int} position
         * @param {true|boolean} removeOnNewPage If true, changes will be added to cleaner.
         */
        function injectElementDirect(parent, child, position = -1, removeOnNewPage = true) {
            const parentEl = factoryUnwrapEl(parent);
            const childEl = factoryUnwrapEl(child);
            if (parentEl && childEl) {
                if (position == -1 || position >= parentEl.children.length) {
                    parentEl.appendChild(childEl);
                } else {
                    const index = position < 0
                        ? Math.max(0, parentEl.children.length + position + 1)
                        : position;
                    parentEl.insertBefore(childEl, parentEl.children[index]);
                }

                if (removeOnNewPage) {
                    cleaner.addTaskRemoveElement(childEl);
                }
            }
        }
        /**
         * Inject and elment into a page as a child to a parent using a factory function that produces an element. The element will not be inject if it already exists as a child to the parent.
         * @param {()=>FactoryChild} elementFactory
         * @param {string} parentSelector
         * @param {string} elementSelector ID or some way to query the parent to check if the element already exists
         * @param {-1|int} position
         * @param {true|boolean} removeOnNewPage If true, changes will be added to cleaner.
         */
        function injectElement(elementFactory, parentSelector, elementSelector, position = -1, removeOnNewPage = true) {
            const parent = document.querySelector(parentSelector);
            if (parent && !parent.querySelector(elementSelector)) {
                const factoryItem = elementFactory();
                injectElementDirect(parent, factoryItem, position, removeOnNewPage);
            }
        }
        /**
         * Injects a class into an target element.
         * @param {FactoryChild} target 
         * @param {string} className 
         * @param {true|boolean} removeOnNewPage If true, changes will be added to cleaner.
         */
        function injectClass(target, className, removeOnNewPage = true) {
            const targetEl = factoryUnwrapEl(target);
            if (targetEl) {
                targetEl.classList.add(className);
                if (removeOnNewPage) {
                    cleaner.addTaskRemoveClass(targetEl, className);
                }
            }
        }

        /**
         * Makes a change to the page. Mostly just a helper for a common workflow.
         * @param {string} changeId Eg 'nhcb-make-change'. Will automatically be added to the target.
         * @param {string} targetSelector Eg '.target-class button'
         * @param {(target: HTMLElement) => void} change Change to apply. Make sure to cleanup changes.
         * @param {true|boolean} cleanUpChangeId If set to true, it will add a task to remove the changeId from the target.
         */
        function injectChange(changeId, targetSelector, change, cleanUpChangeId = true) {
            const target = document.querySelector(targetSelector);
            if (target && !target.classList.contains(changeId)) {
                injector.injectClass(target, changeId, cleanUpChangeId);
                change(target);
            }
        }

        /**
         * Replace the text of an target element. Use this instead of `textContent` for existing elements becasue they break otherwise.
         * @param {FactoryChild} target 
         * @param {string} text 
         */
        function replaceText(target, text) {
            const targetEl = factoryUnwrapEl(target);
            if (!targetEl) {
                return;
            }

            // find first text node, then replace text
            let node = targetEl.firstChild;
            while (node && node.nodeType !== Node.TEXT_NODE) {
                node = node.nextSibling;
            }            
            if (node) {
                node.data = text;
            } else {
                targetEl.appendChild(document.createTextNode(text));
            }
        }

        /**
         * Set the value of an input element in a way that the webpage scripts can recognize.
         * @param {FactoryChild} target  
         * @param {string|number} value 
         */
        function setInputValue(el, value) {
            const proto = el instanceof HTMLTextAreaElement
                ? HTMLTextAreaElement.prototype
                : el instanceof HTMLSelectElement
                ? HTMLSelectElement.prototype
                : HTMLInputElement.prototype;
            const setter = Object.getOwnPropertyDescriptor(proto, 'value').set;
            setter.call(el, value);

            el.dispatchEvent(new Event('input', { bubbles: true }));
            el.dispatchEvent(new Event('change', { bubbles: true }));
        }

        return { injectElementDirect, injectElement, injectClass, injectChange, replaceText, setInputValue }
    })();
    //#endregion

    //#region -- API Calls -----------------------------------------------
    //#region Request Cache Mapper
    const requestCacheMapper = (() => {
        const loadOnGetCooldown = 1000; // mostly just used to prevent constant reloading on get
        let nextLoadOnGetPermitted = 0;
        const saveBufferDuration = 300;
        let saveTimeout;

        function loadLatest() {
            try {
                const previous = new Map(localStore.cachedApiRequests.value);
                const loaded = localStore.cachedApiRequests.load();
                const now = Date.now();

                // merge
                for (const [url, previousEntry] of previous) {
                    const loadedEntry = loaded.get(url);
                    if (!loadedEntry || previousEntry.expiresAt > loadedEntry.expiresAt) {
                        loaded.set(url, previousEntry);
                    }
                }

                // prune
                for (const [url, entry] of loaded) {
                    if (entry.expiresAt <= now) {
                        localStore.cachedApiRequests.value.delete(url);
                    }
                }
                
                nextLoadOnGetPermitted = Date.now() + loadOnGetCooldown;
                return loaded;
            } catch (err) {
                logger.requestPiggyback.error('Failed to load cache from sessionStorage, starting fresh:', err);
                return new Map();
            }
        }
        function scheduleSave() {
            clearTimeout(saveTimeout);
            saveTimeout = setTimeout(save, saveBufferDuration);
        }
        function save() {
            loadLatest();
            localStore.cachedApiRequests.save();
        }
        function get(url) {
            if (Date.now() > nextLoadOnGetPermitted) {
                loadLatest();
            }
            
            const entry = localStore.cachedApiRequests.value.get(normalizeUrl(url));

            if (entry) {
                // Build a fresh Response from the stored data
                return new Response(entry.body, {
                    status: entry.status,
                    headers: new Headers(entry.headers),
                });
            }

            return null;
        }
        async function set(url, response, ttl) {
            try {
                const body = await response.clone().text();
                logger.requestPiggyback.verbose('Caching response', response);
                setDirect(url, body, response.status, Object.fromEntries(response.headers), Date.now() + ttl);
            } catch (err) {
                logger.requestPiggyback.apiError(`Cannot cache response, response is likely not valid. Response: ${response}`);
            }            
        }
        // hacky way for initial page request
        function setDirect(url, body, status, headers, expiresAt) {
            localStore.cachedApiRequests.value.set(normalizeUrl(url), {
                body,
                status,
                headers,
                expiresAt,
            });
            scheduleSave();
        }
        return { get, set, setDirect };
    })();
    //#endregion

    //#region Initial Page Request
    // see note #InitialPageRequest
    function addInitialPageRequestToCache() {
        const SELECTOR = 'script[type="application/json"][data-sveltekit-fetched][data-url]';

        // debugging vars
        const foundResponses = new Map();
        const captureLog = [];

        // take in script el, return parsed response
        function parseScript(scriptEl) {
            try {
                const parsed = JSON.parse(scriptEl.textContent);
                const response = {
                    body: (typeof parsed.body === 'string') ? JSON.parse(parsed.body) : parsed.body,
                    status: parsed.status,
                    headers: parsed.headers
                };
                return { url: scriptEl.dataset.url, response };
            } catch (e) {
                return {
                    url: scriptEl.dataset.url,
                    response: { __parseError: e.message, __raw: scriptEl.textContent }
                };
            }
        }

        // take in found script els and process them
        function ingest(source, dataScriptEls) {
            if (dataScriptEls && dataScriptEls.length > 0) {
                let added = 0;
                for (const el of dataScriptEls) {
                    if (el.dataset.url && !foundResponses.has(el.dataset.url)) {
                        const {url, response} = parseScript(el);
                        addResponseToCache(url, response);
                        foundResponses.set(el.dataset.url, { url, response, source });
                        added++;
                    }
                }
                if (logger.requestPiggyback.shouldLog(logger.LEVELS.DEBUG)) {
                    if (added) {
                        captureLog.push({ source, added, total: foundResponses.size });
                        logger.requestPiggyback.debug(`[capture:${source}] +${added} (total ${foundResponses.size})`);
                    }
                }
            }
        }

        // take in parsed response and add to cache
        function addResponseToCache(url, response) {
            let matchedTarget = null;
            for (const target of CACHE_ENDPOINT_TARGETS) {
                if (target.pattern.test(url)) {
                    matchedTarget = target;
                    break;
                }
            }

            // If target endpoint
            if (matchedTarget) {
                // note: don't upgrade url. already have response, can't ask for more

                if (response.status == 200) {
                    requestCacheMapper.setDirect(url, JSON.stringify(response.body), response.status, response.headers, Date.now() + matchedTarget.ttl);
                    logger.requestPiggyback.debug('Caching initial page data for url:', prettyNormalUrl(url), response);
                } else if (response.status == 404) {
                    // do nothing
                } else if (response.status == 429) {
                    reportIssue('API_RATE_LIMIT', { requestUrl: url });
                } else {
                    reportIssue('API_OTHER_ISSUE', { requestUrl: url, responseCode: response.status });
                }
            }
        }

        // Source: immediate
        ingest('immediate', document.querySelectorAll(SELECTOR));

        // Source: mutation
        const obs = new MutationObserver(muts => {
            const found = [];
            for (const m of muts) {
                for (const n of m.addedNodes) {
                    if (n.nodeType === 1) {
                        if (n.matches?.(SELECTOR)) {
                            found.push(n);
                        }
                        n.querySelectorAll?.(SELECTOR).forEach(s => found.push(s));
                    }
                }
            }
            if (found.length) {
                ingest('mutation', found);
            }
        });
        obs.observe(document.documentElement, { childList: true, subtree: true });

        // Cleanup + summary
        window.addEventListener('load', () => setTimeout(() => {
            obs.disconnect();
            if (logger.requestPiggyback.shouldLog(logger.LEVELS.DEBUG)) {
                logger.requestPiggyback.debug(`=== final: ${foundResponses.size} script(s) ===`);
                logger.requestPiggyback.debug('sources:', captureLog);
                logger.requestPiggyback.debug('responses:', [...foundResponses.values()]);
            }
        }, 100));
    }
    //#endregion

    //#region Monkey Patch
    // See note: #Monkeypatch
    function applyMonkeypatch() {
        unsafeWindow.fetch = async function(...args) {
            // https://developer.mozilla.org/en-US/docs/Web/API/Window/fetch
            const resource = args[0]; // either a url string, Url like instance, or Request instance. Here, typically only string
            const options = {...(args[1] || {})}; // RequestInit object
            let url = resource instanceof Request ? resource.url : String(resource);
            const method = (resource instanceof Request ? resource.method : options.method) || 'GET';

            let matchedTarget = null;
            for (const target of CACHE_ENDPOINT_TARGETS) {
                if (target.pattern.test(url)) {
                    matchedTarget = target;
                    break;
                }
            }

            // If not a target endpoint, do normal behavior
            if (matchedTarget == null) {
                const response = await originalFetch.apply(this, args);
                return response;
            }
            // else is target endpoint

            // Check cache
            let cached = requestCacheMapper.get(url);

            // if not cache, try upgrading url, then try again
            if (!cached) {
                // special case, gallery request are upgraded to request full info. this is to reduce cache miss
                // more for case where reader makes 2nd request for less data
                if (matchedTarget.name == 'gallery') {
                    try {
                        const u = new URL(url, location.origin);
                        const paramsIncludeFavorite = u.searchParams.get('include')?.includes('favorite') ?? false;
                        if (paramsIncludeFavorite || userData.checkIfLoggedIn()) {
                            // favorite only used if logged in
                            u.searchParams.set('include', 'related,suggestions,comments,favorite');
                        } else {
                            u.searchParams.set('include', 'related,suggestions,comments');
                        }
                        url = u.href;
                        args[0] = url; // pass the upgraded URL through to originalFetch
                    } catch (e) {
                        logger.requestPiggyback.warn('Was not able to upgrade gallery URL');
                        logger.requestPiggyback.debug(e);
                    }
                }
                // once upgraded, try cache again
                cached = requestCacheMapper.get(url);
            }
            
            // if cached, return cached response
            if (cached) {
                logger.requestPiggyback.debug(`CACHE HIT [${method}] ${prettyNormalUrl(url)}`, cached);
                return cached;
            }
            // Else not cached, make new fetch then cache result


            // if no authorization, use api key
            if ( secretStore.apiKey.value) {
                const headers = new Headers(options.headers || {});
                if (!headers.get('Authorization')) {
                    headers.set('Authorization', `Key ${secretStore.apiKey.value}`);
                }
                // pass the modified options back to the args for originalFetch
                options.headers = headers;
                args[1] = options;
            }
  
            const response = await originalFetch.apply(this, args);
            
            logger.requestPiggyback.debug(`-- NEW REQUEST -- [${method}] ${response.status} ${prettyNormalUrl(url)}`, response.clone());
            if (response.ok) {
                await requestCacheMapper.set(url, response, matchedTarget.ttl);
            } else if (response.status == 404) {
                // do nothing
            } else if (response.status == 429) {
                reportIssue('API_RATE_LIMIT', { requestUrl: url });
            } else if (response.status == 504) {
                reportIssue('API_TIMEOUT', { requestUrl: url })
            } else {
                reportIssue('API_OTHER_ISSUE', { requestUrl: url, responseCode: response.status });
            }

            return response.clone();
        };
    }    
    //#endregion


    //#region API Interface
    /**
     * https://nhentai.net/api/v2/docs
     * @param {string} urlStr 
     * @returns {Promise<object[]|object|null>}
     */
    async function fetchApi(urlStr, postBody = null) {
        try {
            const res = await unsafeWindow.fetch(urlStr, {
                method: postBody ? 'POST' : 'GET',
                headers: {
                    'User-Agent': APP_INFO.USER_AGENT,
                    ...(postBody && {'Content-Type': 'application/json' }),
                },
                ...(postBody && { body: JSON.stringify(postBody) }),
                signal: AbortSignal.timeout(SCRIPT_FETCH_TIMEMOUT),
            });

            if (!res.ok) {
                // reporting is handled by the monkey patch
                // errors below are for edge cases
                return null;
            }

            const data = await res.json();
            // return data without pagination info
            return data?.result ?? data ?? null;
        } catch (err) {
            if (err.name === 'AbortError') {
                reportIssue('API_TIMEOUT', { requestUrl: urlStr });
            } else {
                reportIssue('API_ERROR', { requestUrl: urlStr, errorMessage: err.message });
            }
            return null;
        }
    }

    async function makeApiCallsForPage() {
        // this function used to do a lot more, but most of that is handled by #Monkeypatch
        await pullApiInfoForGalleriesOnPage();
    }

    async function pullApiInfoForGalleriesOnPage() {
        if (allGalleriesOnPageExistInCache()) {
            return;
        }
        const pageNumber = pageData.searchParams.get('page') ?? 1;
        const sort = pageData.searchParams.get('sort') ?? undefined;

        switch (pageData.type) {
            case PAGE_TYPES.HOME: {
                if (pageNumber === 1) {
                    //landing page
                    const popularDataList = await apiEndpoints.popularGalleries.fetch();
                    cachedApiData.galleries.addData(...toArray(popularDataList));
                }
                const galleryDataList = await apiEndpoints.galleries.fetch(pageNumber);
                cachedApiData.galleries.addData(...toArray(galleryDataList));
                break;
            }
            case PAGE_TYPES.GALLERY: {
                const galleryData = await apiEndpoints.gallery.fetch(pathToGalleryId(pageData.path));
                const relatedGalleries = await apiEndpoints.relatedGalleries.fetch(pathToGalleryId(pageData.path));
                cachedApiData.galleries.addData(galleryData, ...relatedGalleries);
                break;
            }
            case PAGE_TYPES.NAMESPACE: {
                if (!cachedApiData.tags.has(pageData.path)) {
                    const tagData = await apiEndpoints.tag.fetch(pageData.tagInfo.type, pageData.tagInfo.name);
                    cachedApiData.tags.addData(tagData);
                }
                // can fail and still not exist
                const tagId = cachedApiData.tags.get(pageData.path)?.id;
                if (tagId) {
                    const galleryDataList = await apiEndpoints.taggedGalleries.fetch(tagId, pageNumber, sort);
                    cachedApiData.galleries.addData(...toArray(galleryDataList));
                }
                break;
            }
            case PAGE_TYPES.SEARCH: {
                const galleryDataList = await apiEndpoints.searchGalleries.fetch(pageData.query, pageNumber, sort);
                cachedApiData.galleries.addData(...toArray(galleryDataList));
                break;
            }
            case PAGE_TYPES.USER_FAVORITES: {
                const galleryDataList = await apiEndpoints.userFavorites.fetch(pageNumber, pageData.query);
                cachedApiData.galleries.addData(...toArray(galleryDataList));
                break;
            }
            default:
                break;
        }
    }
    //#endregion

    //#region API Helpers
    function allGalleriesOnPageExistInCache() {
        const galleriesOnPage = document.querySelectorAll('.gallery'); // don't use cahcedPageEls because of race conditions

        if (galleriesOnPage.length > 0 && cachedApiData.galleries.size == 0) {
            return false;
        }

        for (const div of galleriesOnPage) {
            const href = div.querySelector('a.cover')?.getAttribute('href');
            cachedApiData.galleries.has(href);
            if (href && !cachedApiData.galleries.has(href)) {
                return false;
            }
        }

        return true;
    }

    async function getOrPullGalleryCacheData(galleryPath) {
        let galleryData = cachedApiData.galleries.get(galleryPath);

        // if data needed not in cache, pull data
        if (!galleryData) {
            const rawGalleryData = await apiEndpoints.gallery.fetch(pathToGalleryId(galleryPath)); // dont return raw data, cache normalizes
            cachedApiData.galleries.addData(rawGalleryData);
            galleryData = cachedApiData.galleries.get(galleryPath); // could still be undefined
        }

        return galleryData;
    }

    async function getOrPullTagCacheData(tagPath) {
        let tagData = cachedApiData.tags.get(tagPath);

        // if data needed not in cache, pull data
        if (!tagData) {
            const tagInfo = tagInfoFromPath(tagPath);
            const rawTagData = await apiEndpoints.tagSearch.fetch(tagInfo.type, tagInfo.name.replaceAll('-', ' ')); // dont return raw data, cache normalizes
            if (rawTagData == null) {
                cachedApiData.tags.addData(...toArray(rawTagData));
                tagData = cachedApiData.tags.get(tagPath); // could still be undefined
                return tagData;
            } else {
                // case where search returned nothing but request didn't error
                const exactTagData = await apiEndpoints.tag.fetch(tagInfo.type, tagInfo.name);
                cachedApiData.tags.addData(...toArray(exactTagData));
                tagData = cachedApiData.tags.get(tagPath); // could still be undefined
                return tagData;
            }
        }

        return tagData;
    }
    //#endregion

    //#region API Endpoints
    const apiEndpoints = {
        galleries: {
            buildUrl: (pageNumber = 1) => `/api/v2/galleries?page=${pageNumber}`,
            fetch: async (pageNumber = 1) => { return await fetchApi(apiEndpoints.galleries.buildUrl(pageNumber)); },
        },
        popularGalleries: {
            buildUrl: () => `/api/v2/galleries/popular`,
            fetch: async () => { return await fetchApi(apiEndpoints.popularGalleries.buildUrl()); },
        },
        gallery: {
            buildUrl: (galleryId) => `/api/v2/galleries/${galleryId}?include=related,suggestions,comments${userData.isLoggedIn ? ',favorite' : ''}`,
            fetch: async (galleryId) => { return await fetchApi(apiEndpoints.gallery.buildUrl(galleryId)); },
        },
        relatedGalleries: {
            // this was changed to better utilize cache, it no longer uses the dedicated endpoint for related
            buildUrl: (galleryId) => `/api/v2/galleries/${galleryId}?include=related,suggestions,comments${userData.isLoggedIn ? ',favorite' : ''}`,
            fetch: async (galleryId) => { const data = await fetchApi(apiEndpoints.relatedGalleries.buildUrl(galleryId)); return data?.related ?? null; },
        },
        searchGalleries: {
            buildUrl: (query, pageNumber = 1, sort = 'date') => `/api/v2/search?query=${query}&sort=${sort}&page=${pageNumber}`,
            fetch: async (query, pageNumber = 1, sort = 'date') => { return await fetchApi(apiEndpoints.searchGalleries.buildUrl(query, pageNumber, sort)); },
        },
        taggedGalleries: {
            buildUrl: (tagId, pageNumber = 1, sort = 'date') => `/api/v2/galleries/tagged?tag_id=${tagId}&sort=${sort}&page=${pageNumber}`,
            fetch: async (tagId, pageNumber = 1, sort = 'date') => { return await fetchApi(apiEndpoints.taggedGalleries.buildUrl(tagId, pageNumber, sort)); },
        },
        tag: {
            // note: both "exmaple" and "example | alt example" are different
            // note: should be simlar to how it looks in the url "example-tag", or like for above "example-alt-example"
            buildUrl: (tagType, tagName) => `/api/v2/tags/${tagType}/${tagName}`,
            fetch: async (tagType, tagName) => { return await fetchApi(apiEndpoints.tag.buildUrl(tagType, tagName)); },
        },
        multipleTags: {
            buildUrl: (tagIdArray) => `/api/v2/tags/ids?ids=${tagIdArray.join(',')}`,
            fetch: async (tagIdArray) => { return await fetchApi(apiEndpoints.multipleTags.buildUrl(tagIdArray)); },
        },        
        tagSearch: {
            buildUrl: () => `/api/v2/tags/search`,
            fetch: async (type, query) => { return await fetchApi(apiEndpoints.tagSearch.buildUrl(), { ...(type && { type }), ...(query && { query }), limit: 10 }); },
        },
        userFavorites: {
            buildUrl: (pageNumber = 1, query = '') => `/api/v2/favorites?page=${pageNumber}&q=${query}`,
            fetch: async (pageNumber = 1, query = '') => { return await fetchApi(apiEndpoints.userFavorites.buildUrl(pageNumber, query)); },
        }
        // not allowed to use endpoint. only for admins
        // user: {
        //     buildUrl: () => `/api/v2/user`,
        //     fetch: async () => { return await fetchApi(apiEndpoints.user.buildUrl()); },
        // },
    }
    //#endregion
    //#endregion

    //#region -- Changes to apply to page ---------------------
    //#region Gallery Lists
    function applyViewSystemBadge() {
        const states = [
            { changeId: 'nhcb-is-read-later', createBadge: createReadLaterBadge, isState: (href) => dataStore.readLater.value.has(href) },
            { changeId: 'nhcb-is-liked', createBadge: createLikedBadge, isState: (href) => dataStore.likedGalleries.value.has(href) },
            { changeId: 'nhcb-is-passed', createBadge: createPassedBadge, isState: (href) => dataStore.passedGalleries.value.has(href) },
            { changeId: 'nhcb-is-read', createBadge: createReadBadge, isState: (href) => dataStore.readGalleries.value.has(href) },
            { changeId: 'nhcb-is-seen', createBadge: createSeenBadge, isState: (href) => dataStore.seenGalleries.value.has(href) },
        ];
        cachedPageEls.galleries.forEach(gallery => {
            const viewState = states.find(state => state.isState(gallery.href));

            // if state found and state not already applied
            if (viewState && !gallery.el.classList.contains(viewState.changeId)) {
                injector.injectClass(gallery, viewState.changeId);

                const badge = viewState.createBadge();
                injector.injectElementDirect(gallery.cover, badge);
            }
        });
    }

    function applyFavoriteGalleryBadge() {
        cachedPageEls.galleries.forEach(gallery => {
            const favoriteData = dataStore.favoriteGalleries.value.get(gallery.href);
            if (favoriteData && !gallery.cover.querySelector('.nhcb-favorite-badge')) {
                const favoriteBadge = createFavoriteBadge(favoriteData.rating);

                injector.injectElementDirect(gallery.cover, favoriteBadge);
            }
        });
    }
    function applyContentWarningBadge() {
        cachedPageEls.galleries.forEach(gallery => {
            const galleryInfo = cachedApiData.galleries.get(gallery.href);
            if (galleryInfo && !gallery.cover.querySelector('.nhcb-content-warning-badge')) {

                const contentWarningBadge = createContentWarningBadge(galleryInfo.tag_ids);
                injector.injectElementDirect(gallery.cover, contentWarningBadge);
            }
        });
    }

    function applyInfoBadge() {
        const infoBadgesData = [
            {
                enabled: settingsStore.enablePageCountBadge.value,
                create: createPageCountInfoBadge,
            },
            {
                enabled: settingsStore.enableArtistInfoBadge.value,
                create: createArtistsInfoBadge,
            },
            {
                enabled: settingsStore.enableIncompleteBadge.value,
                create: createIncompleteInfoBadge,
            },
            {
                enabled: settingsStore.enableBadTranslationBadge.value,
                create: createBadTranslationInfoBadge,
            },
        ].filter(data => data.enabled).map(data => data.create);
        cachedPageEls.galleries.forEach(gallery => {
            const galleryData = cachedApiData.galleries.get(gallery.href);
            if (galleryData && !gallery.cover.querySelector('.nhcb-info-badge')) {
                const infoBadgeContent = [];
                const tagSet = new Set(galleryData.tag_ids);
                
                infoBadgesData.forEach((create) => {
                    const badge = create(galleryData, tagSet);
                    if (badge) {
                        infoBadgeContent.push(badge);
                    }
                })

                const infoBadge = createInfoBadgeBase(infoBadgeContent);
                injector.injectElementDirect(gallery.cover, infoBadge);
            }
        });
    }

    function applyAltSourceBadge() {
        cachedPageEls.galleries.forEach(gallery => {
            const favoriteData = dataStore.favoriteGalleries.value.get(gallery.href);
            if (favoriteData && (favoriteData.alt_source_action === 'nudge' || favoriteData.alt_source_action === 'force') && !gallery.cover.querySelector('.nhcb-alt-source-badge')) {
                const altSourceBadge = createAltSourceBadge({ sourceName: favoriteData.alt_sources?.at(0)?.name });

                injector.injectElementDirect(gallery.cover, altSourceBadge);
            }
        });
    }

    function applyThumbnailAltCoverReplacement() {
        cachedPageEls.galleries.forEach(gallery => {
            const altCoverData = dataStore.favoriteGalleries.value.get(gallery.href)?.alt_cover;
            if (altCoverData) {
                if (altCoverData && gallery.img.src != altCoverData.thumbnail) {
                    gallery.img.src = altCoverData.thumbnail;
                    gallery.cover.style = `padding: 0px 0px ${(altCoverData.thumbnail_height / altCoverData.thumbnail_width) * 100}%`;
                    
                    // no need to cleanup because the website will replace it
                }
            }
        });
    }

  function applyMultiLanguageEnglishFlag() {
        if (settingsStore.fixMultiLanguageGalleries.value === 'disabled') {
            return;
        }
        const changeId = settingsStore.fixMultiLanguageGalleries.value === 'multiFlag' ? 'nhcb-gb-multi' : 'nhcb-gb';
        cachedPageEls.galleries.forEach(gallery => {
            if (!gallery.el.classList.contains(changeId)) {
                const galleryInfo = cachedApiData.galleries.get(gallery.href);
                if (galleryInfo?.tag_ids.includes(DEFINITIONS.COMMON_TAG_IDS.ENLGISH)) {
                    injector.injectClass(gallery, changeId);
                }
            }
        });
    }

    function applyCustomGalleryTitleToLists() {
        const changeId = 'nhcb-custom-title';
        cachedPageEls.galleries.forEach(gallery => {
            const customTitle = dataStore.favoriteGalleries.value.get(gallery.href)?.custom_title;
            if (customTitle && !gallery.el.classList.contains(changeId)) {
                injector.injectClass(gallery, changeId);
                gallery.caption.textContent = customTitle;
            }
        });
    }

    function applyGalleryListsPrettyTitles() {
        const changeId = 'nhcb-pretty-title';
        const createTitleSection = (name, content) => createElement('span', { className: `nhcb-${name}` }, content);
        const createTitleSections = (before, pretty, after) => [createTitleSection('before', before), createTitleSection('pretty', pretty), createTitleSection('after', after)]
        cachedPageEls.galleries.forEach(gallery => {
            if (!gallery.el.classList.contains(changeId)) {
                injector.injectClass(gallery, changeId);
                const originalTitle = gallery.caption.textContent;
                const originalHref = gallery.href;
                const titleSecitons = parseTitleSections(gallery.caption.textContent);
                injector.replaceText(gallery.caption, "");
                cleaner.addTask(gallery.caption, (el) =>  {
                    if (el?.parentElement?.getAttribute('href') == originalHref) {
                        injector.replaceText(el, originalTitle);
                    }
                })
                const titleSecitonRoots = createTitleSections(titleSecitons.before, titleSecitons.pretty, titleSecitons.after);
                factoryAppend(gallery.caption, ...titleSecitonRoots);
                cleaner.addTaskRemoveElement(titleSecitonRoots[0]);
                cleaner.addTaskRemoveElement(titleSecitonRoots[1]);
                cleaner.addTaskRemoveElement(titleSecitonRoots[2]);
            }
        });
    }
    //#endregion

    //#region Tag Lists
    function applyTagBrowseBadges() {
        const states = [
            { changeId: 'nhcb-is-browse-later', createBadge: createBrowseLaterBadge, isState: (href) => dataStore.browseLater.value.has(href) },
            { changeId: 'nhcb-is-browsed', createBadge: createBrowsedBadge, isState: (href) => dataStore.browsedPages.value.has(href) },
        ];
        cachedPageEls.tags.forEach(tag => {
            const browseState = states.find(state => state.isState(tag.href));

            // if state found and state not already applied
            if (browseState && !tag.el.classList.contains(browseState.changeId)) {
                injector.injectClass(tag, browseState.changeId);

                const badge = browseState.createBadge();
                injector.injectElementDirect(tag.nameEl, badge);
            }
        });
    }
    function applyTagSentimentHightlight() {
        const tagSentimentsClassMap = {
            'liked': 'nhcb-liked-tag',
            'dubious': 'nhcb-dubious-tag',
            'scorned': 'nhcb-scorned-tag',
        };

        cachedPageEls.tags.forEach(tag => {
            const tagSentiment = dataStore.tagSentiments.value.get(tag.href);
            if (tagSentiment) {
                const sentimentClass = tagSentimentsClassMap[tagSentiment.status];

                injector.injectClass(tag, 'nhcb-tag-highlight');
                injector.injectClass(tag, sentimentClass);
            }
        });
    }
    function applyTagPipeFix() {
        const changeId = 'nhcb-taglist-pipe-fix';
        cachedPageEls.tags.forEach(tag => {
            if (!tag.el.classList.contains(changeId)) {
                injector.injectClass(tag, changeId);

                if (tag.nameEl.textContent.includes('|')) {
                    const tagName = tag.nameEl.textContent.split(' | ')[0].trim();
                    const href = `/${tag.typeStr}/${tagName.toLowerCase().replaceAll(' ', '-').replaceAll('.', '')}/`;
                    if (cachedPageEls.tags.has(href)) {
                        // special case added for community fixing the tag
                        injector.injectClass(tag, 'hidden');
                    } else {
                        tag.nameEl.textContent = tagName;
                        tag.el.setAttribute('href', href);
                    }
                }
            }
        });
    }
    //#endregion

    //#region Gallery page
    function applyCustomFavoriteButton() {
        let currentGalleryIsFavorite = dataStore.favoriteGalleries.value.has(pageData.path);
        let backupFavoriteData = dataStore.favoriteGalleries.value.get(pageData.path);
        
        const parent = document.querySelector('#info .buttons');
        const changeId = 'nhcb-custom-favorite';
        let target = null;
        let labelPrefix = ''; 

        if (!parent || parent.querySelector(`.${changeId}`)) {
            return;
        }

        if (settingsStore.customFavoritesSeparateButton.value) {
            const favoriteButton = createButton({ content: [createIcon('heart', { iconStyle: 'regular' }), createElement('span', {}, 'CB Favorite')], buttonStyle: 'primary' })
            labelPrefix = ' CB ';
            factoryAppend(parent, favoriteButton);
            target = favoriteButton.el;

        } else {
            target = document.querySelector('.buttons button:has(i.fa-heart)');
        }

        function updateButtonState(favoriteButton) {
            const text = favoriteButton.querySelector('span');
            const icon = favoriteButton.querySelector('i');
            const countSpan = favoriteButton.querySelector('span.nobold');

            if (text && icon) {
                text.textContent = labelPrefix + (currentGalleryIsFavorite ? 'Unfavorite ' : 'Favorite ');

                icon.classList.toggle('far', currentGalleryIsFavorite);
                icon.classList.toggle('fas', !currentGalleryIsFavorite);
                
                if (countSpan) {
                    text.appendChild(countSpan);
                }
            }
        }

        if (target && !target.classList.contains(changeId)) {
            injector.injectClass(target, changeId);
            target.classList.toggle('btn-disabled', false);
            target.disabled = false;

            updateButtonState(target);

            target.addEventListener('click', async (e) => {
                const favoriteButton = e.currentTarget; //need to store before next lines
                e.preventDefault();
                e.stopPropagation();

                // get updated set
                dataStore.favoriteGalleries.load();

                // determine operation using button state
                if (currentGalleryIsFavorite) {
                    // remove from favorites
                    currentGalleryIsFavorite = false;
                    const tmpBackup = dataStore.favoriteGalleries.value.get(pageData.path);
                    if (tmpBackup) {
                        backupFavoriteData = tmpBackup; // simple guard for it being removed on another page first
                    }
                    dataStore.favoriteGalleries.value.delete(pageData.path);
                    logger.storeUpdates.log(`Gallery ${pageData.path} removed from favorites. Can be restored.`);
                }
                else {
                    // add to favorites
                    if (backupFavoriteData) {
                        // use initial data to undo removal
                        dataStore.favoriteGalleries.value.set(pageData.path, backupFavoriteData);
                        logger.storeUpdates.log(`Gallery ${pageData.path} restored to favorites.`);
                    }
                    else {
                        let galleryData = await getOrPullGalleryCacheData(pageData.path);
                        // if data needed not in cache, pull data
                        if (!galleryData) {
                            reportIssue('CANNOT_FAVORITE_API_FAIL', { galleryPath: pageData.path });
                            return;
                        }

                        const favoriteData = objectDeepCopy(galleryData);
                        favoriteData.favorite_at = getUnixTimestamp();
    
                        dataStore.favoriteGalleries.value.set(pageData.path, favoriteData);
                        logger.storeUpdates.log(`Gallery ${pageData.path} added to favorites.`);
                    }
                    currentGalleryIsFavorite = true;
                }

                // save changes
                dataStore.favoriteGalleries.save();

                // update button
                updateButtonState(favoriteButton);
            });

            // no removal of event listener because not needed
            // customization is applied and then state is updated every apply and use pageData.path for correct gallery
        }
    }

    function applyPreviewAltCoverReplacement() {
        const target = document.querySelector('#cover a img');
        const changeId = 'nhcb-custom-cover';

        if (target && !target.classList.contains(changeId)) {
            injector.injectClass(target, changeId);

            let originalImage = {
                link: target.src,
                width: target.width,
                height: target.height,
            };

            function setImage(link, width, height) {
                if (target.src == link) {
                    return;
                }
                target.src = link;
                target.setAttribute('height', Math.round((height / width) * 350));
            }
            function updateImage() {
                const altCoverData = dataStore.favoriteGalleries.value.get(pageData.path)?.alt_cover;
                if (altCoverData) {
                    setImage(altCoverData.thumbnail, altCoverData.thumbnail_width, altCoverData.thumbnail_height);
                } else {
                    setImage(originalImage.link, originalImage.width, originalImage.height);
                }
            }

            updateImage();
            const unsubcribe = dataStore.favoriteGalleries.subscribe(updateImage)
            cleaner.addTaskNoFail(unsubcribe);
        }
    }

    function applyAutoMarkCurrentGalleryAsSeen() {
        const target = document.querySelector('#info-block');
        const changeId = 'nhcb-auto-mark-seen';

        if (target && !target.classList.contains(changeId)) {
            injector.injectClass(target, changeId);

            pruneSeenExclude();
            if (pageData.layoutDepenenciesInitialized && !dataStore.seenGalleries.value.has(pageData.path) && !tmpDataStore.seenGalleriesExclude.value.has(pageData.path)) {
                dataStore.seenGalleries.load();
                dataStore.seenGalleries.value.add(pageData.path);
                dataStore.seenGalleries.save();
                logger.storeUpdates.log(`Gallery ${pageData.path} added to seen list.`);
            }
        }
    }

    function applyAltSourceNudge() {
        const target = document.querySelector('#info-block');
        const changeId = 'nhcb-nudge-towards-alt-source';

        if (target && !target.classList.contains(changeId)) {
            injector.injectClass(target, changeId);
            
            const favoriteData = dataStore.favoriteGalleries.value.get(pageData.path);
            if (favoriteData && (favoriteData.alt_source_action === 'nudge' || favoriteData.alt_source_action === 'force')) {
                makeModal({
                    headerContent: 'Try Alt Source',
                    content: [
                        createElement('p', { style: 'font-size: 1.25rem;' }, 'Your customizations show that you really prefer this source instead.'),
                        createContainerGeneric({ content: [createGalleryFromData(favoriteData, { forceAltSource: true, elementProperties: { style: 'width: 250px;' } })] })                    
                    ],
                });
            }            
        }
    }

    function applyCustomGalleryTitleToGalleryPage() {
        const target = document.querySelector('#info .title');
        const changeId = 'nhch-custom-title';

        if (!target || target.classList.contains(changeId)) {
            return;
        }
        injector.injectClass(target, changeId);

        // a bit overkill but this needed a lot of setup
        const sections = (() => {
            const beforeOriginalEl = target.querySelector('.before');
            const beforeOriginalText = beforeOriginalEl?.textContent;
            const prettyOriginalEl = target.querySelector('.pretty');
            const prettyOriginalText = prettyOriginalEl?.textContent;
            const afterOriginalEl = target.querySelector('.after');
            const afterOriginalText = afterOriginalEl?.textContent;

            function makeSectionRoot(sectionOriginalEl, sectionName) {
                let section;
                if (sectionOriginalEl) {
                    section = makeFactoryRoot(sectionOriginalEl);
                } else {
                    section = createElement('span', { className: `${sectionName} nhcb-${sectionName}` });
                    cleaner.addTaskRemoveElement(section.el);
                }
                factoryAppend(target, section);
                cleaner.addTaskRemoveClass(sectionOriginalEl, 'hidden');
                return section;
            }

            // order dependent
            let beforeEl = makeSectionRoot(beforeOriginalEl, 'before');
            let prettyEl = makeSectionRoot(prettyOriginalEl, 'pretty');
            let afterEl = makeSectionRoot(afterOriginalEl, 'after');

            function setText(root, text) {
                injector.replaceText(root, text);
                root.hidden = text ? false : true;
            }

            function revertText(root, originalEl, originalText) {
                setText(root, originalText ? originalText : '');
            }

            return {
                before: {
                    el: beforeEl,
                    origialEl: beforeOriginalEl,
                    originalText: beforeOriginalText,
                    setText: (text) => setText(beforeEl, text),
                    revertText: () => revertText(beforeEl, beforeOriginalEl, beforeOriginalText),
                },
                pretty: {
                    el: prettyEl,
                    origialEl: prettyOriginalEl,
                    originalText: prettyOriginalText,
                    setText: (text) => setText(prettyEl, text),
                    revertText: () => revertText(prettyEl, prettyOriginalEl, prettyOriginalText),
                },
                after: {
                    el: afterEl,
                    origialEl: afterOriginalEl,
                    originalText: afterOriginalText,
                    setText: (text) => setText(afterEl, text),
                    revertText: () => revertText(afterEl, afterOriginalEl, afterOriginalText),
                },
            }
        })();

        function updateDisplay() {
            const favoriteData = dataStore.favoriteGalleries.value.get(pageData.path);
            const customTitle = favoriteData?.custom_title;
            
            if (customTitle) {
                const { before, pretty, after } = parseTitleSections(customTitle);
                sections.before.setText(before);
                sections.pretty.setText(pretty);
                sections.after.setText(after);
            } else {
                sections.before.revertText();
                sections.pretty.revertText();
                sections.after.revertText();
            }
        }
        
        updateDisplay();
        const unsubcribe = dataStore.favoriteGalleries.subscribe(updateDisplay);
        cleaner.addTaskNoFail(unsubcribe);
    }

    function applyCustomGalleryInfo() {
        const target = document.querySelector('#tags');
        const changeId = 'nhch-custom-info';

        if (!target || target.classList.contains(changeId)) {
            return;
        }

        injector.injectClass(target, changeId);
        const beforeTarget = target.querySelector('section.ts-root') ?? null;

        function createAndInsertInfoSection(label, content) {
            const infoSection = createInfoSection({ label, content, includeInfoBlockClasses: true })
            target.insertBefore(infoSection.el, beforeTarget);
            cleaner.addTaskRemoveElement(infoSection);
            return infoSection;
        }

        function labelsShouldClarifySource() {
            if (settingsStore.enableGalleryCustomInfoReadLaterLabels.value && settingsStore.enableGalleryCustomInfoFavoriteLabels.value) {
                const favoriteData = dataStore.favoriteGalleries.value.get(pageData.path);
                const readLaterData = dataStore.readLater.value.get(pageData.path);
                return favoriteData && favoriteData.labels?.length > 0 && readLaterData && readLaterData.labels?.length > 0;
            }
        }

        // read status (seen doesn't have the data needed)
        if (settingsStore.enableGalleryCustomInfoReadStatus.value) {
            // me no think, me use hammer
            const infoSectionRead = createAndInsertInfoSection('Read: ');
            const infoSectionLiked = createAndInsertInfoSection('Liked: ');
            const infoSectionPassed = createAndInsertInfoSection('Passed: ');

            function updateDisplay() {
                const [status, readTimestamp] = getGalleryReadStatus(pageData.path);
                const favoriteData = dataStore.favoriteGalleries.value.get(pageData.path);
                if (readTimestamp != null && !(settingsStore.hideGalleryCustomInfoReadIfFavorite.value && favoriteData)) {
                    infoSectionRead.replaceContent(createTimeAgoDisplay(readTimestamp));
                    infoSectionLiked.replaceContent(createTimeAgoDisplay(readTimestamp));
                    infoSectionPassed.replaceContent(createTimeAgoDisplay(readTimestamp));
                    infoSectionRead.hidden = status !== 'read';
                    infoSectionLiked.hidden = status !== 'liked';
                    infoSectionPassed.hidden = status !== 'passed';
                } else {
                    infoSectionRead.hidden = true;
                    infoSectionLiked.hidden = true;
                    infoSectionPassed.hidden = true;
                }
            }

            updateDisplay();

            const unsubscribeRead = dataStore.readGalleries.subscribe(updateDisplay);
            const unsubscribeLiked = dataStore.likedGalleries.subscribe(updateDisplay);
            const unsubscribePassed = dataStore.passedGalleries.subscribe(updateDisplay);
            const unsubscribeFavorite = dataStore.favoriteGalleries.subscribe(updateDisplay);
            cleaner.addTaskNoFail(unsubscribeRead);
            cleaner.addTaskNoFail(unsubscribeLiked);
            cleaner.addTaskNoFail(unsubscribePassed);
            cleaner.addTaskNoFail(unsubscribeFavorite);
        }
        // read later
        // - status
        if (settingsStore.enableGalleryCustomInfoReadLaterStatus.value) {
            const infoSection =  createAndInsertInfoSection('Read Later: ');

            function updateDisplay() {
                const readLaterData = dataStore.readLater.value.get(pageData.path);
                if (readLaterData) {
                    infoSection.replaceContent(createTimeAgoDisplay(readLaterData.added_at));
                    infoSection.hidden = false;
                } else {
                    infoSection.hidden = true;
                }
            }

            updateDisplay();

            const unsubscribe = dataStore.readLater.subscribe(updateDisplay);
            cleaner.addTaskNoFail(unsubscribe);
        }

        // - priority
        if (settingsStore.enableGalleryCustomInfoReadLaterPriority.value) {
            const infoSection =  createAndInsertInfoSection('Read Priority: ');

            function updateDisplay() {
                const readLaterData = dataStore.readLater.value.get(pageData.path);
                if (readLaterData) {
                    const readPriorityStr = readLaterData.read_priority.toString();
                    const readPriorityDisplay = DEFAULTS.PRIORITY_DROPDOWN_OPTIONS.find(x => x[0] === readPriorityStr)[1];
                    infoSection.replaceContent(createGalleryLabel(readPriorityDisplay, { href: buildUrl({ deleteAllParams: true, setParams: { q: `priority:"${readPriorityDisplay.toLowerCase()}"` }, newPath: CUSTOM_PAGES.READ_LATER.path }) }));
                    infoSection.hidden = false;
                } else {
                    infoSection.hidden = true;
                }
            }

            updateDisplay();

            const unsubscribe = dataStore.readLater.subscribe(updateDisplay);
            cleaner.addTaskNoFail(unsubscribe);
        }

        // - labels
        if (settingsStore.enableGalleryCustomInfoReadLaterLabels.value) {
            const infoSection = createAndInsertInfoSection('Labels: ');

            function updateDisplay() {
                const readLaterData = dataStore.readLater.value.get(pageData.path);
                if (readLaterData && readLaterData.labels?.length > 0) {
                    infoSection.renameLabel(labelsShouldClarifySource() ? 'Labels (Read Later): ' : 'Labels: ');
                    const labels = readLaterData.labels?.map((label) => createGalleryLabel(label, { href: buildUrl({ deleteAllParams: true, setParams: { q: `label:"${label}"` }, newPath: CUSTOM_PAGES.READ_LATER.path }) }));
                    infoSection.replaceContent(...labels);
                    infoSection.hidden = false;
                } else {
                    infoSection.hidden = true;
                }
            }

            updateDisplay();

            const unsubscribe = dataStore.readLater.subscribe(updateDisplay);
            cleaner.addTaskNoFail(unsubscribe);
        }

        // favorite
        // - status
        if (settingsStore.enableGalleryCustomInfoFavoriteStatus.value) {
            const infoSection =  createAndInsertInfoSection('Favorited: ');

            function updateDisplay() {
                const favoriteData = dataStore.favoriteGalleries.value.get(pageData.path);
                if (favoriteData) {
                    infoSection.replaceContent(createTimeAgoDisplay(favoriteData.favorite_at));
                    infoSection.hidden = false;
                } else {
                    infoSection.hidden = true;
                }
            }

            updateDisplay();

            const unsubscribe = dataStore.favoriteGalleries.subscribe(updateDisplay);
            cleaner.addTaskNoFail(unsubscribe);
        }

        // - rating
        if (settingsStore.enableGalleryCustomInfoFavoriteRating.value) {
            const infoSection =  createAndInsertInfoSection('Rating: ');

            function updateDisplay() {
                const favoriteData = dataStore.favoriteGalleries.value.get(pageData.path);
                if (favoriteData && favoriteData.rating > 0) {
                    infoSection.replaceContent(createRatingDisplay({ rating: favoriteData.rating, elementProperties: { style: 'font-size: 1.25em;' } }));
                    infoSection.hidden = false;
                } else {
                    infoSection.hidden = true;
                }
            }

            updateDisplay();

            const unsubscribe = dataStore.favoriteGalleries.subscribe(updateDisplay);
            cleaner.addTaskNoFail(unsubscribe);
        }

        // - labels
        if (settingsStore.enableGalleryCustomInfoFavoriteLabels.value) {
            const infoSection = createAndInsertInfoSection('Labels: ');

            function updateDisplay() {
                const favoriteData = dataStore.favoriteGalleries.value.get(pageData.path);
                if (favoriteData && favoriteData.labels?.length > 0) {
                    infoSection.renameLabel(labelsShouldClarifySource() ? 'Labels (Favorite): ' : 'Labels: ')
                    const labels = favoriteData.labels?.map((label) => createGalleryLabel(label, { href: buildUrl({ deleteAllParams: true, setParams: { q: `label:"${label}"` }, newPath: CUSTOM_PAGES.FAVORITES.path }) }));
                    infoSection.replaceContent(...labels);
                    infoSection.hidden = false;
                } else {
                    infoSection.hidden = true;
                }
            }

            updateDisplay();

            const unsubscribe = dataStore.favoriteGalleries.subscribe(updateDisplay);
            cleaner.addTaskNoFail(unsubscribe);
        }

        // - note
        if (settingsStore.enableGalleryCustomInfoFavoriteNote.value) {
            const infoSection =  createAndInsertInfoSection('Notes: ');

            function updateDisplay() {
                const favoriteData = dataStore.favoriteGalleries.value.get(pageData.path);
                if (favoriteData && favoriteData.note) {
                    infoSection.replaceContent(favoriteData.note);
                    infoSection.hidden = false;
                } else {
                    infoSection.hidden = true;
                }
            }

            updateDisplay();

            const unsubscribe = dataStore.favoriteGalleries.subscribe(updateDisplay);
            cleaner.addTaskNoFail(unsubscribe);
        }
    }

    async function applyGalleryCoverBadges() {
        const target = document.querySelector('#cover a');
        const changeId = 'nhcb-gallery-cover-badges';

        if (!target || target.classList.contains(changeId)) {
            return;
        }
        injector.injectClass(target, changeId);

        const coverBadgeClass = 'nhcb-gallery-cover-badge';

        // favorite
        if (settingsStore.enableBcFavoriteGalleryBadge.value) {
            const favoriteBadge = createFavoriteBadge(0);
            favoriteBadge.classList.add(coverBadgeClass);
            injector.injectElementDirect(target, favoriteBadge)
            function updateFavoriteDisplay() {
                favoriteBadge.hidden = !dataStore.favoriteGalleries.value.has(pageData.path);
            }
            updateFavoriteDisplay();
            const unsubscribeFavorite = dataStore.favoriteGalleries.subscribe(updateFavoriteDisplay);
            cleaner.addTaskNoFail(unsubscribeFavorite);
        }

        // read later (technically same as view status)
        if (settingsStore.enableBcViewSystemBadge.value) {
            const readLaterBadge = createReadLaterBadge();
            readLaterBadge.classList.add(coverBadgeClass);
            injector.injectElementDirect(target, readLaterBadge)
            function updateReadLaterDisplay() {
                readLaterBadge.hidden = !dataStore.readLater.value.has(pageData.path);
            }
            updateReadLaterDisplay();
            const unsubscribeReadLater = dataStore.readLater.subscribe(updateReadLaterDisplay);
            cleaner.addTaskNoFail(unsubscribeReadLater);
        }

        // view status
        if (settingsStore.enableBcViewSystemBadge.value) {
            /** @type {FactoryRoot?}  */
            let statusBadge = null;
            /** @type {ReadStatus}  */
            let status = 'none';
            function updateStatusBadge() {
                const [updatedStatus, readTimestamp] = getGalleryReadStatus(pageData.path);
    
                if (updatedStatus !== status) {
                    status = updatedStatus;
                    statusBadge?.el.remove();
                    switch (status) {
                        case 'liked':
                            statusBadge = createLikedBadge();
                            break;
                        case 'read':
                            statusBadge = createReadBadge();
                            break;
                        case 'passed':
                            statusBadge = createPassedBadge();
                            break;
                        default:
                            statusBadge = null;
                            break;
                    }
                    if (statusBadge) {
                        statusBadge.el.classList.add(coverBadgeClass);
                        factoryAppend(target, statusBadge);
                    }
                }
            }
            updateStatusBadge();
            const unsubscribeRead = dataStore.readGalleries.subscribe(updateStatusBadge);
            const unsubscribeLiked = dataStore.likedGalleries.subscribe(updateStatusBadge);
            const unsubscribePassed = dataStore.passedGalleries.subscribe(updateStatusBadge);
            cleaner.addTaskNoFail(unsubscribeRead);
            cleaner.addTaskNoFail(unsubscribeLiked);
            cleaner.addTaskNoFail(unsubscribePassed);
            cleaner.addTaskNoFail(() => statusBadge?.el.remove());
        }

        let galleryData = await getOrPullGalleryCacheData(pageData.path);

        // info badges
        const infoBadgesData = [
            {
                enabled: settingsStore.enableBcPageCountBadge.value,
                create: createPageCountInfoBadge,
            },
            {
                enabled: settingsStore.enableBcArtistInfoBadge.value,
                create: createArtistsInfoBadge,
            },
            {
                enabled: settingsStore.enableBcIncompleteBadge.value,
                create: createIncompleteInfoBadge,
            },
            {
                enabled: settingsStore.enableBcBadTranslationBadge.value,
                create: createBadTranslationInfoBadge,
            },
        ];
        const infoBadgeContent = [];
        const tagSet = new Set(galleryData.tag_ids);
        infoBadgesData.forEach(({enabled, create}) => {
            if (enabled) {
                const badge = create(galleryData, tagSet);
                if (badge) {
                    infoBadgeContent.push(badge);
                }
            }
        })
        const infoBadge = createInfoBadgeBase(infoBadgeContent);
        infoBadge.classList.add(coverBadgeClass);
        injector.injectElementDirect(target, infoBadge);

        // content warning
        if (settingsStore.enableBcContentWarningBadge.value) {
            const contentWarningBadge = createContentWarningBadge(galleryData.tag_ids);
            contentWarningBadge.classList.add(coverBadgeClass);
            injector.injectElementDirect(target, contentWarningBadge);
        }
    }

    function bypassTaxonomyAgreement() {
        if (settingsStore.bypassTaxonomyAgreement.value == 'enabled') {
            localStorage.setItem(DEFINITIONS.TAXONOMY_AGREEMENT.KEY, DEFINITIONS.TAXONOMY_AGREEMENT.VALUE);
        } else if (settingsStore.bypassTaxonomyAgreement.value == 'nowaiting') {
            injector.injectChange('nhcb-bypass-taxonomy-agree', '.ts-root .ts-agreement-ok', (target) => {
                const makeChanges = () => {
                    target.removeAttribute('disabled');
                    target.innerText = 'Agreed';
                }

                makeChanges();

                const observer = new MutationObserver(() => {
                    if (target.hasAttribute('disabled')) {
                        makeChanges();
                    }
                });

                observer.observe(target, {
                    attributes: true,
                    attributeFilter: ['disabled']
                });

                cleaner.addTaskNoFail(() =>{
                    observer.disconnect();
                })
            });
        }
    }
    //#endregion

    //#region Navigation bar
    function addNavBarToErrorPage() {
        injector.injectChange('nhcb-error-page-nav-bar', DEFINITIONS.SPECIAL_SELECTORS.ERROR_PAGE, () => {
            injector.injectElement(createPageNavBar, '#app', 'nav', 0);
        });
    }

    function applyCustomNavLinks() {
        const desktopLinkContainer = document.querySelector('nav div.collapse ul.left');
        const dropdownLinkContainer = desktopLinkContainer?.querySelector('li.dropdown ul.dropdown-menu');
        const changeId = 'nhcb-custom-links';

        if (!desktopLinkContainer || !dropdownLinkContainer || desktopLinkContainer.classList.contains(changeId)) { 
            return;
        }
        desktopLinkContainer.classList.add(changeId);

        // insert before element, with fallbacks. if none found, just append element
        const insertBeforeSelectors = ['li:has(> a[href^="//tsyndicate.com"])', 'li:has(> a[href="https://twitter.com/nhentaiOfficial"])', 'li:has(> #dropdown)'];
        const desktopInsertBeforeTarget = insertBeforeSelectors.map(selector => desktopLinkContainer.querySelector(selector)).find(target => target != null)
        const dropdownInsertBeforeTarget = insertBeforeSelectors.map(selector => dropdownLinkContainer.querySelector(selector)).find(target => target != null);

        // desktop
        const desktopLinks = CUSTOM_PAGES.values().map(page => createNavLink({ isDesktop: true, link: page.path, label: page.label, elementProperties: { className: 'nhcb-custom-nav-link' } }));
        const navGroup = createNavGroup({ label: 'Custom Brew', content: desktopLinks });
        desktopLinkContainer.insertBefore(navGroup.el, desktopInsertBeforeTarget ?? null);

        // dropdown
        const dropdownLinks = CUSTOM_PAGES.values().map(page => createNavLink({ isDesktop: false, link: page.path, label: 'CB ' + page.label, elementProperties: { className: 'nhcb-custom-nav-link' } }));
        dropdownLinks.forEach(linkRoot => dropdownLinkContainer.insertBefore(linkRoot.el, dropdownInsertBeforeTarget ?? null));
    }

    function applyCustomPageNavHighlight () {
        const activePageLinks = document.querySelectorAll(`li:has(a[href="${pageData.path}"])`);
        activePageLinks.forEach(link => {
            if (!link.classList.contains('active')) {
                injector.injectClass(link, 'active');
            }
        });
    }

    function applyNavDropdownNotClosingFix() {
        const changeId = 'nhcb-dropdown-fix';

        const dropdown = document.querySelector('nav .menu.left li.dropdown');
        const dropdownButton = dropdown?.querySelector('#dropdown');
        const dropdownMenu = dropdown?.querySelector('.dropdown-menu');

        if (dropdownButton && dropdownMenu && !dropdown.classList.contains(changeId)) {
            dropdown.classList.add(changeId);

            dropdownButton.addEventListener('click', (e) => {
                e.stopPropagation(); // override original behavior to prevent weirdness (original event handler is not on the button)
                showMenu(!dropdownMenu.classList.contains('open'));
            }, { capture: true });
            addClickOutsideEvent(dropdown, (e) => {
                showMenu(false);
            });
            
            function showMenu(isVisible) {
                dropdownMenu.classList.toggle('open', isVisible);
            }
        }
    }

    function moveTagLinksIntoMenu() {
        const desktopLinks = document.querySelector('nav div.collapse ul.menu.left');

        if (desktopLinks && !desktopLinks.querySelector('.nhcb-nav-group-tags')) {
            const foundLinks = TAG_TYPES.values().map(type => desktopLinks.querySelector(`li:has(a[href="/${TAG_TYPES.plural(type)}/"])`)).filter(el => el != null);

            if (foundLinks.length <= 1) {
                return;
            }
            // else at least 2 links

            const insertBeforeRef = foundLinks[0];

            const root = createNavGroup({ label: 'Browse Tags', className: 'nhcb-nav-group-tags'});
            desktopLinks.insertBefore(root.el, insertBeforeRef);
            root.append(...foundLinks); // do after inserting, easier code
        }

    }
    //#endregion

    //#region Reader changes
    function applyGalleryReaderKeyNavPreventExit() {
        // function to prevent arrow key from going back to gallery on last page
        function handleKeyNav(e) {
            if (e.key === 'ArrowRight') {
                e.stopImmediatePropagation();
                e.preventDefault();
            }
        }
        
        const currentPage = document.querySelector('.page-number .current')?.textContent;
        const lastPage = document.querySelector('.page-number .num-pages')?.textContent;

        // if last page
        if (currentPage && currentPage == lastPage) {
            window.addEventListener('keydown', handleKeyNav, true);
            cleaner.addTaskNoFail(() => window.removeEventListener('keydown', handleKeyNav, true));
        }
    }

    function applyFullScreenChanges() {
        function handleKeyFullScreen(e) {
            if (e.key === 'g') {
                e.preventDefault();
                toggleFullscreen();
            }
        }
        function handleClickFullScreen(e) {
            e.preventDefault();
            toggleFullscreen();
        }

        function toggleFullscreen() {
            // yes this bullshit is probably needed
            if (document.fullscreenElement) {
                if (document.exitFullscreen) { document.exitFullscreen(); } else if (document.webkitExitFullscreen) { document.webkitExitFullscreen(); } else if (document.mozCancelFullScreen) { document.mozCancelFullScreen(); } else if (document.msExitFullscreen) { document.msExitFullscreen(); }
            }
            else {
                const content = document.querySelector('#content');
                if (content.requestFullscreen) { content.requestFullscreen(); } else if (content.mozRequestFullScreen) { content.mozRequestFullScreen(); } else if (content.webkitRequestFullScreen) { content.webkitRequestFullScreen(); } else if (content.msRequestFullscreen) { content.msRequestFullscreen(); }
            }
        }
        
        const body = document.body;
        if (!body.classList.contains('nhcb-allow-fullscreen')) {
            body.classList.toggle('nhcb-allow-fullscreen', true);
            window.addEventListener('keydown', handleKeyFullScreen);

            cleaner.addTask(body, (el) => {
                window.removeEventListener('keydown', handleKeyFullScreen);
                el.classList.toggle('nhcb-allow-fullscreen', false);
            });
        }

        injector.injectChange('nhcb-fullscreen-button', '.zoom-buttons .box:last-child', (el) => {
            el.innerHTML = '<a aria-label="Full screen (g)" title="Full screen (g)">&#x26F6;</a>';
            el.addEventListener('click', handleClickFullScreen);

            cleaner.addTask(el, (el) => {
                el.removeEventListener('click', handleClickFullScreen);
                el.innerHTML = '';
            })
        })
    }

    function applyReaderImprovedZoom() {
        function handleZoomOut(e) {
            e.preventDefault();
            e.stopPropagation();
            const newZoom = clamp(sessionStore.zoomLevel.value - 0.1, 0.1, 3);
            setZoomLevel(newZoom);
            //applyZoom(); not needed
        }
        function handleZoomIn(e) {
            e.preventDefault();
            e.stopPropagation();
            const newZoom = clamp(sessionStore.zoomLevel.value + 0.1, 0.1, 3);
            setZoomLevel(newZoom);
            //applyZoom(); not needed
        }
        function setZoomLevel(value) {
            sessionStore.zoomLevel.value = value;
            sessionStore.zoomLevel.save();
            
            const zoomEl = document.querySelector('.zoom-level .value');
            if (zoomEl) {
                const newZoomText = value.toFixed(1);
                // if you don't do this, you brick the page with infinite loop
                if (zoomEl.textContent != newZoomText) {
                    zoomEl.textContent = newZoomText;
                }
            }
        }
        function applyZoom() {
            setZoomLevel(sessionStore.zoomLevel.value);
            const imageContainer = document.querySelector('#image-container img');
            if (imageContainer) {
                imageContainer.setAttribute('width', 1280 * sessionStore.zoomLevel.value);
            }
        }

        const zoomInButton = document.querySelector('button.reader-zoom-in');
        const zoomOutButton = document.querySelector('button.reader-zoom-out');

        if (zoomInButton && !zoomInButton.classList.contains('nhcb-improved-zoom')) {
            zoomInButton.classList.add('nhcb-improved-zoom');
            zoomInButton.addEventListener('click', handleZoomIn);
            cleaner.addTask(zoomInButton, (el) => {
                el.removeEventListener('click', handleZoomIn);
                zoomInButton.classList.toggle('nhcb-improved-zoom', false);
            });
        }
        if (zoomOutButton && !zoomOutButton.classList.contains('nhcb-improved-zoom')) {
            zoomOutButton.classList.add('nhcb-improved-zoom');
            zoomOutButton.addEventListener('click', handleZoomOut);
            cleaner.addTask(zoomOutButton, (el) => {
                el.removeEventListener('click', handleZoomOut);
                zoomOutButton.classList.toggle('nhcb-improved-zoom', false);
            });
        }

        applyZoom();
    }
    function applyAutoPlayer() {
        // does not clean up on page change because changes need to persist across pages
        // could have a store for a singleton interval or something but this works
        const target = document.querySelector('.reader-buttons-left');

        if (!target || target.querySelector('#nhcb-auto-player')) {
            return;
        }

        const convertRangeValueToDelay = (val) => Math.round(val * 1000);
        let rangeValue = tmpDataStore.autoPlayerDelay.value;
        let intervalDelay = convertRangeValueToDelay(rangeValue);
        let intervalId;
        const intervalRunning = () => intervalId != null;

        const min = 5;
        const stepSize = 5;
        const stepCount = 6;

        const root = createElement('div', { id: 'nhcb-auto-player' });
        const range = createElement('input', { type: 'range', min, max: min + stepSize * (stepCount - 1), value: rangeValue, onchange: handleDelayChange });
        const rangeWrapper = createElement('div', {},
            range,
            createElement('datalist', { id: 'nhcb-auto-player-ticks' },
                ...Array(stepCount).fill().map((_, n) => createElement('option', { value: (n * stepSize) + min }))
            ),
            createElement('div', { id: 'nhcb-auto-player-labels' }, 
                ...Array(stepCount).fill().map((_, n) => createElement('span', {}, (n * stepSize) + min))
            )
        )
        const button = createButton({ 
            id: 'nhcb-auto-player-button',
            content: createIcon('play', { iconStyle: 'solid' }), 
            altContent: createIcon('stop', { iconStyle: 'solid' }), 
            buttonStyle: 'secondary',
            onClick: toggleAutoPlay
        });

        range.el.setAttribute('list', 'nhcb-auto-player-ticks');
        root.append(rangeWrapper, button);
        factoryAppend(target, root);


        function handleDelayChange(e) {
            const newValue = parseFloat(e.target.value);
            //if changed and interval running, restart interval
            if (newValue != rangeValue) {
                rangeValue = newValue;
                tmpDataStore.autoPlayerDelay.value = rangeValue;
                tmpDataStore.autoPlayerDelay.save();
                intervalDelay = convertRangeValueToDelay(rangeValue);
                if (intervalId != null) {
                    startInterval();
                }
            }
        }

        function toggleAutoPlay() {
            button.classList.toggle('btn-secondary', intervalId != null);
            button.classList.toggle('btn-primary', intervalId == null);
            button.showAltContent(intervalId == null);

            if (intervalId == null) {
                startInterval();
            } else {
                stopInterval();
            }
        }

        function startInterval() {
            stopInterval();
            intervalId = setInterval(() => {
                if (pageData.type === PAGE_TYPES.READER) {
                    window.dispatchEvent(new KeyboardEvent('keydown', { key:'ArrowRight' })); // must dispatch on window for svelt to detect
                } else {
                    clearInterval(intervalId);
                }
            }, intervalDelay)
        }
        function stopInterval() {
            if (intervalId != null) {
                clearInterval(intervalId);
                intervalId = undefined;
            }
        }
    }
    //#endregion

    //#region Namespace Page
    function applyCopyTagSearchTermOnClick() {
        function copyTagToClipboard(e) {
            e.preventDefault();
            const tagEl = e.currentTarget;
            const tagInfo = tagInfoFromPath(tagEl.getAttribute('href')); // here is where I learned .href != .getAttribute('href')
            const formattedTag = formatTagSearchTerm(tagInfo.type, tagInfo.name);

            GM_setClipboard(formattedTag);

            notifier.info(`Copied "${formattedTag}" to clipboard.`);
        }

        const tagEl = cachedPageEls.tags.values()[0]?.el;
        if (tagEl && !tagEl.classList.contains('nhcb-tag-copy-on-click')) {
            tagEl.classList.toggle('nhcb-tag-copy-on-click', true);
            tagEl.addEventListener('click', copyTagToClipboard);
            cleaner.addTask(tagEl, (el) => {
                el.removeEventListener('click', copyTagToClipboard);
                el.classList.toggle('nhcb-tag-copy-on-click', false);
            });
        }
    }

    function applyHideEmptyGtsDescription() {
        if (!settingsStore.hideGtsDescriptionIfNone.value) {
            return;
        }
        const changeId = 'nhcb-hide-empty-gts-description';
        const target = document.querySelector('p.describe-cta');
        if (target) {
            injector.injectClass(target, changeId);
            const suggestionLink = target.querySelector('a');
            if (suggestionLink) {
                injector.injectClass(target, 'hidden');
            }
        }

    }
    //#endregion

    //#region Search Page
    function applyAddTagChipIfOnlyOneTerm() {
        injector.injectChange('nhcb-add-tag-chip-search', '#content', (target) => {
            const terms = extractSearchTerms(pageData.query);

            if (terms.length == 1 && terms[0].value && TAG_TYPES.has(terms[0].key)) {
                addTagToPage(terms[0].key, terms[0].value);
            } else {
                // if key, key does not start with '-', key is TAG_TYPES, key is not language
                // if not key, value is not english
                const filteredTerms = terms.filter(({key, value, negated}) => key ? (!negated && TAG_TYPES.has(key) && key.toLowerCase() !== TAG_TYPES.LANGUAGE) : (value.toLowerCase() !== 'english'));
                if (filteredTerms.length === 1 && filteredTerms[0].value && TAG_TYPES.has(filteredTerms[0].key)) {
                    addTagToPage(filteredTerms[0].key, filteredTerms[0].value);
                }
            }

            function addTagToPage(tagType, tagName) {
                // todo: make api call on tag path to verify it is a valid tag. search tag search endpoint not reliable enough for short names
                // actually may be reliable if check [0] exact match. seems to prioritieze exacty match first
                const tagPath = `/${slugify(tagType)}/${slugify(tagName)}/`;
                const tagChip = createTagChip(tagName, { tagType, href: tagPath});
                const root = createElement('h1', {}, tagChip);
                injector.injectElementDirect(target, root, 0);
                cachedPageEls.tags.add(factoryUnwrapEl(tagChip));
            }
        })
    }
    //#endregion

    //#region Auto Login
    function autoNavToLogin() {
        if (userData.isLoggedIn || pageData.type == PAGE_TYPES.LOGIN || !secretStore.username.value || !secretStore.password.value) {
            return;
        }

        const changeId = 'nhcb-auto-login';
        const changeTarget = document.querySelector('div');
        if (changeTarget && !changeTarget.classList.contains(changeId)) {
            injector.injectClass(changeTarget, changeId);
        }

        gotoPage('/login', 1); // can break without delay
        //notifier.info(`Going to login page for auto login. You can disable this in settings page if it breaks. nhentai.net${CUSTOM_PAGES.SETTINGS.path}`, 5);
    }
    function autoFillLogin() {
        if (!secretStore.username.value || !secretStore.password.value) {
            return;
        }

        const changeId = 'nhcb-auto-fill';
        const form = document.querySelector('form');

        if (!form || form.classList.contains(changeId)) {
            return;
        }

        const usernameField = form.querySelector('input[name="username_or_email"]');
        const passwordField = form.querySelector('input[name="password"]');
        const submitButton = form.querySelector('button[type="submit"]');

        if (!usernameField || !passwordField || !submitButton) {
            return;
        }

        form.classList.add(changeId);

        function fill(el, value) {
            el.focus();
            el.value = value;
            el.dispatchEvent(new InputEvent('input', {
                bubbles: true,
                data: String(value),
                inputType: 'insertText',
            }));
            el.dispatchEvent(new Event('change', { bubbles: true }));
            el.blur();
        }

        fill(usernameField, secretStore.username.value);
        fill(passwordField, secretStore.password.value);

        logger.info('Login auto fill sucessful.');

        if (!settingsStore.autoSubmitAfterAutoFill.value) {
            return;
        }

        let intervalId;
        intervalId = setInterval(() => {
            const captcha = form.querySelector('.captcha-container input[name="cf-turnstile-response"]');
            const captchaCompleted = captcha.value;
            if (captchaCompleted) {
                clearInterval(intervalId);
                submitButton?.click();
                logger.info('Login auto submit sucessful. Pray, you dont get blocked by anti-spam.');
            }
        }, 500);

        cleaner.addTaskNoFail(() => clearInterval(intervalId));
    }

    //#endregion

    //#region Misc changes
    function bypassAgeGate() {
        injector.injectChange('nhcb-age-gate-bypass', DEFINITIONS.SPECIAL_SELECTORS.AGE_GATE, (el) => {
            const monthField = el.querySelector('#age-month');
            const dayField = el.querySelector('#age-day');
            const yearField = el.querySelector('#age-year');
            const submitButtonSelector = '.age-actions .age-btn.primary[type="submit"]';
            const submitButton = el.querySelector('.age-actions .age-btn.primary[type="submit"]');

            injector.setInputValue(monthField, 1);
            injector.setInputValue(dayField, 1);
            injector.setInputValue(yearField, 1990);
            function isCurrent(el, selector) {
                return el.isConnected && document.querySelector(selector) === el;
            }

            if (settingsStore.autoSubmitAgeGate.value) {
                setTimeout(() => {
                    if (isCurrent(submitButton, submitButtonSelector)) {
                        submitButton.click();
                    }
                }, 500);
            }
        });
    }

    function rateLimitAutoRefresh() {
        injector.injectChange('nhcb-auto-refresh-error', DEFINITIONS.SPECIAL_SELECTORS.ERROR_PAGE_IMAGE, (rateLimitImage) =>{
            const errorCode = rateLimitImage.alt?.split(' ')[1];
            const isRateLimit = errorCode === '429';
            const isServerError = errorCode?.[0] === '5';

            if (isRateLimit || isServerError) {
                logger.debug(`Detected refreshable error ${errorCode} at `, new Date());

                // if page opened in current tab
                if (document.visibilityState === 'visible') {
                    const refreshDelay = 15 + getRandomInt(0, 5); // jitter
                    refreshPage(refreshDelay);
                    logger.info(`Detected refreshable error ${errorCode}. Auto refreshing the page in ${refreshDelay} seconds.`);
                // else if page opened in separate tab
                } else {
                    // random refreshes
                    const refreshDelay = 60 + getRandomInt(0, 60); // jitter
                    refreshPage(refreshDelay);
                    logger.info(`Detected refreshable error ${errorCode}. Auto refreshing the page in ${refreshDelay} seconds.`);

                    // switch to active tab
                    const minSwitchRefreshDelay = 15;
                    const pageOpenedTimestamp = getUnixTimestamp();
                    document.addEventListener('visibilitychange', () => {
                        const secondsSincePageOpened = getUnixTimestamp() - pageOpenedTimestamp;
                        const switchRefreshDelay = minSwitchRefreshDelay - secondsSincePageOpened;
                        refreshPage(switchRefreshDelay);
                        logger.info(`Background tab is now active. Auto refreshing the page in ${switchRefreshDelay} seconds.`);
                    }, { once: true });
                }
            }
        });
    }

    function cloudflareAutoRefresh() {
        injector.injectChange('nhcb-auto-refresh-cloudflare', DEFINITIONS.SPECIAL_SELECTORS.CLOUDFLARE, () => {
            logger.debug(`Detected cloudflare page at `, new Date());

            // if page opened in current tab
            if (document.visibilityState === 'visible') {
                const refreshDelay = 15 + getRandomInt(0, 5); // jitter
                refreshPage(refreshDelay);
                logger.info(`Detected cloudflare page. Auto refreshing the page in ${refreshDelay} seconds.`);
            // else if page opened in separate tab
            } else {
                // random refreshes
                // should wait longer since this is usually only for multiple rate limits in a row
                const refreshDelay = 120 + getRandomInt(0, 60); // jitter
                refreshPage(refreshDelay);
                logger.info(`Detected cloudflare page. Auto refreshing the page in ${refreshDelay} seconds.`);

                // switch to active tab
                const minSwitchRefreshDelay = 15;
                const pageOpenedTimestamp = getUnixTimestamp();
                document.addEventListener('visibilitychange', () => {
                    const secondsSincePageOpened = getUnixTimestamp() - pageOpenedTimestamp;
                    const switchRefreshDelay = minSwitchRefreshDelay - secondsSincePageOpened;
                    refreshPage(switchRefreshDelay);
                    logger.info(`Background tab is now active. Auto refreshing the page in ${switchRefreshDelay} seconds.`);
                }, { once: true });
            }
        });
    }

    function addJumpToPagePagination() {
        const changeId = 'nhcb-jump-page';
        const targets = document.querySelectorAll('.pagination span.page');

        if (!targets && targets.length === 0) {
            return;
        }

        function showJumpToPageModal() {
            function handleInputChange(input) {
                return parseValidIntInRange(input, 1) != null;
            }
            function handleInputCommit(input) {
                const page = parseValidIntInRange(input, 1);
                if (page == null) {
                    return false;
                } else {
                    const url = buildUrl({ setParams: { page }})
                    gotoPage(url);
                    return true;
                }
            }
            makeModal({content: createInputField({ submitButtonContent: 'Jump', initialValue: pageData.searchParams.get('page') ?? 1, placeholder: 'Enter number...',onInputChange: handleInputChange, onCommit: handleInputCommit, lockSubmitIfUnchanged: true, useSafetyLock: false }), headerContent: 'Jump to Page', })
        }

        targets.forEach(target => {
            if (!target.classList.contains(changeId)) {
                injector.injectClass(target, changeId);
                target.addEventListener('click', showJumpToPageModal);
                cleaner.addTask(target, () => {
                    target.removeEventListener('click', showJumpToPageModal);
                })
            }
        });
    }

    function addArrowKeyNavigationForPagination() {
        const changeId = 'nhcb-arrow-key-pagination';
        
        function handleKeyNav(e) {
            // Claude trully is the superior stackoverflow
            if (['INPUT', 'TEXTAREA', 'SELECT'].includes(e.target.tagName)) {
                return;
            }
            // Claude says this should be included to prevent conflciting with browser shortcuts
            if (e.altKey || e.ctrlKey || e.metaKey || e.shiftKey) {
                return
            }
            if (e.key === 'ArrowRight') {
                const nextLink = document.querySelector('.pagination .next');
                if (nextLink) {
                    nextLink.click();
                }

            } else if (e.key === 'ArrowLeft') {
                const nextLink = document.querySelector('.pagination .previous');
                if (nextLink) {
                    nextLink.click();
                }
            }
        }

        injector.injectChange(changeId, '.pagination', () => {
            window.addEventListener('keydown', handleKeyNav, true);
            cleaner.addTaskNoFail(() => window.removeEventListener('keydown', handleKeyNav, true));
        })
    }
    //#endregion
    //#endregion

    //#region -- Element factories -------------------------
    //#region Factory Base
    const factoryUnwrapEl = (/** @type {FactoryChild} */ item) => /** @type {HTMLElement} */ (item?.el ?? item);
    function factoryAppend(parent, /** @type {FactoryChild[]} */ ...children) {
        if (parent && children.length > 0) {
            const childItems = children.map(child => factoryUnwrapEl(child));
            factoryUnwrapEl(parent).append(...childItems);
        }
    }
    function factoryAppendSkipNull(parent, /** @type {FactoryChild[]} */ ...children) {
        if (parent && children.length > 0) {
            const childItems = children.map(child => factoryUnwrapEl(child)).filter(child => child != null);
            factoryUnwrapEl(parent).append(...childItems);
        }
    }
    function factoryReplaceChildren(parent, /** @type {FactoryChild[]} */ ...children) {
        if (parent) {
            const childItems = children?.map(child => factoryUnwrapEl(child)) ?? [];
            factoryUnwrapEl(parent).replaceChildren(...childItems);
        }
    }
    function factoryAddProperty(obj, name, getter, setter) {
        Object.defineProperty(obj, name, {
            get: getter,
            set: setter,
            enumerable: true,
            configurable: true,
        });
    }

    function makeFactoryRoot(element, elementProperties = {}) {
        if (!element) return null;

        const { hidden, baseClassName, ...restOfProperties } = elementProperties;

        if (baseClassName) {
            restOfProperties.className = restOfProperties?.className  ? `${baseClassName} ${restOfProperties.className}` : baseClassName;
        }
        if (hidden) {
            restOfProperties.className += ' hidden';
        }

        Object.assign(element, restOfProperties);

        /** @type {FactoryRoot} */ 
        const root = {
            el: element,
            classList: element.classList,
            get hidden() { return element.classList.contains('hidden'); },
            set hidden(v) { element.classList.toggle('hidden', v); },
            append: (...children) => { factoryAppend(element, ...children) },
            replaceChildren: (...children) => { factoryReplaceChildren(element, ...children) },
            addProperty: (name, getter, setter) => { factoryAddProperty(root, name, getter, setter); },
            toString() {
                const id = element.id ? `#${element.id}` : '';
                const classes = element.classList.length ? `.${[...element.classList].join('.')}` : '';
                return `FactoryRoot { el: <${element.tagName.toLowerCase()}${id}${classes}>, elementProperties: ${JSON.stringify(elementProperties)} }`;
            }
        };

        return root;
    }

    function createElement(htmlTagName, elementProperties = {}, /** @type {FactoryChild[]} */ ...children) {
        const el = document.createElement(htmlTagName);
        const root = makeFactoryRoot(el, elementProperties);
        root.append(...children);
        return /** @type {FactoryRoot} */ (root);
    }
    //#endregion 

    //#region Basic Elements
    function createSpan(/** @type {FactoryContent} */ content, { id = '', className = '', hidden = false, elementProperties = {} } = {}) {
        const root = createElement('span', {
            ...(id && { id }),
            ...(className && { baseClassName: className }),
            ...(hidden && { hidden }),
            ...elementProperties
        }, ...toArray(content));

        return root;
    }
    function createDiv({ id = '', className = '', hidden = false, elementProperties = {} } = {}, /** @type {FactoryChild[]} */ ...children) {
        const root = createElement('div', {
            ...(id && { id }),
            ...(className && { baseClassName: className }),
            ...(hidden && { hidden }),
            ...elementProperties
        }, ...children);

        return root;
    }
    function createFieldLayout({ content = /** @type {FactoryContent} */ ([]), id = '', className = '', hidden = false, elementProperties = {} } = {}) {
        const root = createElement('div', {
            ...(id && { id }),
            ...(className && { className }),
            ...(hidden && { hidden }),
            baseClassName: 'nhcb-field-layout',
            ...elementProperties
        }, ...toArray(content));

        return root;
    }

    function createLinkButton({ content = /** @type {FactoryContent} */ ([]), href = '', openInNewTab = true, hidden = false, elementProperties = {} } = {}) {
        const root = createElement('a', {
              ...(href && { href }),
            ...(openInNewTab && { target: '_blank', rel:'noopener noreferrer' }),
            ...(hidden && { hidden }),
            baseClassName: 'nhcb-link-button',
            ...elementProperties
        }, ...toArray(content));
        return root;
    }

    function createButton({ content = /** @type {FactoryContent} */ ([]), id = '', buttonStyle = /** @type {'none'|'primary'|'secondary'|'toggle'|'square'|any[]} */ ('secondary'), onClick = null, altContent = /** @type {FactoryContent} */ (''), hidden = false, disabled = false, elementProperties = {} } = {}) {
        const buttonStyles = {
            primary: 'btn-primary',
            secondary: 'btn-secondary',
            toggle: 'nhcb-btn-toggle',
            square: 'btn-square',
        }
        function resolveStyles(styles) {
            if (styles == null || styles.length == 0) {
                return '';
            }
            const mappedStyles = styles.map(s => buttonStyles[s]).filter(s => s != null);
            if (mappedStyles.length == 0) {
                return '';
            }
            return ' ' + mappedStyles.join(' ');
        }
        const root = createElement('button', {
                ...(id && { id }),
                ...(hidden && { hidden }),
                ...(disabled && { disabled }),
                ...(onClick && { onclick: onClick }),
                baseClassName: `btn${resolveStyles(toArray(buttonStyle))} nhcb-button`,
                ...elementProperties
            },
            ...toArray(content)
        );

        function setDisabled(isDisabled) {
            root.el.disabled = isDisabled;
            root.el.classList.toggle('btn-disabled', isDisabled);
        }
        setDisabled(disabled);

        root.addProperty('disabled', () => root.el.disabled, setDisabled);
        root.showAltContent = (show) => {
            root.replaceChildren(...toArray(show && altContent ? altContent : content))
            root.classList.toggle('nhcb-btn-toggle-alt', show);
        }

        return /** @type {FactoryRoot & {disabled: boolean, showAltContent: (boolean) => void}} */ (root);
    }

    function createSplitButton({ id = '', content = /** @type {FactoryContent} */ (''), onClick = /** @type {(e) => void} */ (null), items = /** @type {{key: string, content: FactoryContent, onClick: (e) => void, className: string, available?: boolean}[]} */ ([]), hidden = false, disabled = false, elementProperties = {} } = {}) {
        const root = createElement('div', {
            ...(id && { id }),
            baseClassName: `nhcb-split-button`,
            ...(hidden && { hidden }),
            ...elementProperties,
        });

        /** @type {Object<string, FactoryRoot & {available: boolean}>} */
        const itemRootsMap = {};
        let componentDisabled = disabled;
        
        const mainButton = createElement('button', {
            baseClassName: 'nhcb-split-button-main',
            type: 'button',
            ...(disabled && { disabled }),
            onclick: (e) => onClick && onClick(e),
        }, ...toArray(content));

        const dropdownButton = createElement('button', {
            baseClassName: 'nhcb-split-button-toggle',
            type: 'button',
            ariaHasPopup: 'menu',
            ariaExpanded: 'false',
            ariaLabel: 'More actions',
            onclick: () => (dropdownMenu.hidden ? openMenu() : closeMenu())
        }, createIcon('chevron-down', { iconStyle: 'none' }));

        const dropdownMenu = createElement('div', {
            baseClassName: 'nhcb-split-button-menu',
            role: 'menu',
            hidden: true,
        });
        function createDropdownMenuItem(content, onClick, className, available) {
            const itemRoot = createElement('button', {
                baseClassName: 'nhcb-split-button-menu-item',
                ...(className && { className }),
                type: 'button',
                role: 'menuitem',
                tabIndex: -1,
                ...(available === false && { hidden: true }),
                onclick: (e) => { closeMenu(); onClick?.(e); },
            }, ...toArray(content));

            itemRoot.addProperty('available', () => !itemRoot.hidden, (v) => { itemRoot.hidden = !v; });

            return /** @type {FactoryRoot & {available: boolean}} */ (itemRoot);
        }
        

        function updateDropdownDisabled() {
            if (componentDisabled) {
                dropdownButton.el.disabled = componentDisabled;
                closeMenu();
            } else {
                const anyItemsVisible = Object.values(itemRootsMap).some(itemRoot => itemRoot.available);
                dropdownButton.el.disabled = !anyItemsVisible; // componentDisabled is false
                if (anyItemsVisible) {
                    closeMenu();
                }
            }
        }

        function openMenu() {
            if (!dropdownMenu.hidden || dropdownButton.el.disabled) {
                return;
            }
            dropdownMenu.hidden = false;
            dropdownButton.el.ariaExpanded = 'true';
            //document.addEventListener('click', onOutside, true);
        }

        function closeMenu() {
            if (dropdownMenu.hidden) {
                return;
            }
            dropdownMenu.hidden = true;
            dropdownButton.el.ariaExpanded = 'false';
            //document.removeEventListener('click', onOutside, true);
        }
        
        items.forEach((item, i) => {
            const key = item.key != null ? item.key : `item-${i}`;

            const itemRoot = createDropdownMenuItem(item.content, item.onClick, item.className, item.available);

            itemRootsMap[key] = itemRoot;
            dropdownMenu.append(itemRoot);
        });

        updateDropdownDisabled();

        addClickOutsideEvent(root, closeMenu);
        function onOutside(e) {
            if (!root.el.contains(e.target)) {
                closeMenu();
            }
        }

        root.append(mainButton, dropdownButton, dropdownMenu);

        root.addProperty('disabled', () => componentDisabled, (v) => { componentDisabled = v; mainButton.el.disabled = v; updateDropdownDisabled(); });
        root.setAvailable = (keyOrMap, value) => {
            if (keyOrMap && typeof keyOrMap === 'object') {
                for (const [k, v] of Object.entries(keyOrMap)) {
                    if (itemRootsMap[k]) {
                        itemRootsMap[k].available = v;
                    }
                }
            } else if (itemRootsMap[keyOrMap]) {
                itemRootsMap[keyOrMap].available = value;
            }
            updateDropdownDisabled();
        };
        root.openMenu = openMenu;
        root.closeMenu = closeMenu;
        root.replaceChildren = mainButton.replaceChildren;
        root.append = mainButton.append;


        return /** @type {FactoryRoot & {disabled: boolean, setAvailable: (keyOrMap: string|Record<string, boolean>, value?: boolean) => void, openMenu: () => void, closeMenu: () => void}} */ (root);
    }

    function createInput({ id = '', placeholder = 'Input here...', initialValue = '', hidden = false, disabled = false, elementProperties = {} } = {}) {
        const root = createElement('input', {
            ...(id && { id }),
            ...(placeholder && { placeholder }),
            ...(initialValue && { defaultValue: initialValue }),
            ...(hidden && { hidden }),
            ...(disabled && { disabled }),
            baseClassName: 'nhcb-input',
            ...elementProperties
        });

        root.addProperty('disabled', () => root.el.disabled, (v) => root.el.disabled = v);
        root.addProperty('value',() => root.el.value, (v) => root.el.value = v);

        return /** @type {FactoryRoot & {disabled: boolean, value: string}} */ (root);
    }

    function createDropdownSelect({ id = '', options = /** @type {DropdownOptions} */ ([]), initialValue = undefined, onSelectedChange = /** @type {(value: string|'', index: int|-1) => void} */ (null), hidden = false, disabled = false, elementProperties = {} } = {}) {
        const root = createElement('select', {
            ...(id && { id }),
            ...(hidden && { hidden }),
            ...(disabled && { disabled }),
            baseClassName: 'nhcb-dropdown-select',
            ...elementProperties
        });

        root.el.addEventListener('input', (e) => {onSelectedChange?.(root.el.value, root.el.selectedIndex);})

        function replaceOptions(options) {
            const previousValue = root.el.value;
            
            // replace options
            const newOptions = [];
            const normalized = options?.map(item => Array.isArray(item) ? item : [item, item]); // if not 2d array, duplicate value to be value and display
            normalized?.forEach(([value, textContent]) => {
                newOptions.push(createElement('option', { value, textContent }));
            });
            root.replaceChildren(...newOptions);

            // preserve previous selection if still exists
            if (normalized?.some(([value, displayName]) => value === previousValue)) {
                root.el.value = previousValue;
            }
        };
        replaceOptions(options);
        if (initialValue !== undefined) {
            root.el.value = initialValue;
        }

        root.addProperty('disabled', () => root.el.disabled, (v) => root.el.disabled = v);
        root.addProperty('value',() => root.el.value, (v) => root.el.value = v);
        root.addProperty('selectedIndex',() => root.el.selectedIndex, (v) => root.el.selectedIndex = v);
        root.replaceOptions = replaceOptions;

        return /** @type {FactoryRoot & {disabled: boolean, value: string|'', selectedIndex: int|-1, replaceOptions: (options: DropdownOptions) => void}} */ (root);
    }
    
    function createTooltip({ content = /** @type {FactoryContent} */ (''), width = '150px', hidden = false, elementProperties = {} } = {}) {
        const root = createElement('div', {
                baseClassName: 'tooltip nhcb-tooltip',
                ...(hidden && { hidden }),
                ...elementProperties
            },
            createIcon('question-circle', { iconStyle: 'regular' })
        );
        
        const infoPopover = createElement('span', {
            className: 'top nhcb-tooltip-info',
            ...(!Array.isArray(content) && { innerHTML: content }),
            ...( width && width != '150px' && { style: `min-width: ${width};` })
        });
        // hacky solution, didn't want to spend time on real solution
        if (Array.isArray(content)) {
            infoPopover.append(...content);
        } else {
            infoPopover.el.innerHTML = content;
        }
        infoPopover.append(createElement('i'));

        root.append(infoPopover);

        root.el.addEventListener('mouseenter', () => {
            const rect = infoPopover.el.getBoundingClientRect();
            infoPopover.classList.toggle('nhcb-tooltip-flip', rect.bottom > window.innerHeight || rect.top < 0);
        });
        root.el.addEventListener('mouseleave', () => {
            infoPopover.classList.toggle('nhcb-tooltip-flip', false);
        });
        
        return root;
    }

    function createSafetyLock({ onChange = null, isLocked = true, hidden = false, elementProperties = {} } = {}) {
        const root = createElement('label', {
            baseClassName: 'nhcb-safety-lock',
            ...(hidden && { hidden }),
            ...elementProperties
        });
        
        const checkbox = createElement('input', { type: 'checkbox', checked: isLocked });
        const icon = createElement('i');

        function setLockDisplay(isLocked) {
            icon.el.className = `fas ${isLocked ? 'fa-lock' : 'fa-lock-open'}`;
        }
        setLockDisplay(isLocked);

        root.append(checkbox, icon);

        checkbox.el.addEventListener('change', (e) => {
            setLockState(e.currentTarget.checked);
        });

        function setLockState(isLocked) {
            checkbox.el.checked = isLocked; // change event only triggers due to ui interaction
            setLockDisplay(isLocked);
            onChange?.(isLocked);
        }

        root.addProperty('isLocked', () => checkbox.el.checked, setLockState)

        return /** @type {FactoryRoot & {isLocked: boolean}} */ (root);
    }

    function createIcon(iconName, { iconStyle = /** @type {'solid' | 'regular' | 'outline' | 'none'} */ ('solid'), hidden = false, elementProperties = {} } = {}) {
        // font awesome 5 is used by main site
        const fa5Stlyes = {
            solid: 'fas',
            regular: 'far',
            outline: 'far',
            none: 'fa',
        }

        const root = createElement('i', {
            baseClassName: `${fa5Stlyes[iconStyle] ?? fa5Stlyes.solid} fa-${iconName}`,
            ...(hidden && { hidden }),
            ...elementProperties
        });

        return root;
    }

    function createGalleryLabel(/** @type {Label} */ labelName, { allowRemoval = false, onRemoveClick = /** @type {(labelName: Label) => void} */ (null), href = '', elementProperties = {} } = {}) {
        const root = createElement('div', {
            baseClassName: 'nhcb-gallery-label',
            ...elementProperties
        });

        let name = labelName;

        const nameSpan = createElement(href ? 'a' : 'span', { className: 'nhcb-gallery-label-name', ...(href && { href })}, name);
        const removalIcon = createElement('button', { 
            onclick: () => onRemoveClick?.(name),
            hidden: !allowRemoval,
        }, '×');

        root.append(nameSpan, removalIcon);

        root.addProperty('name', () => name, (v) => {
            name = v;
            nameSpan.replaceChildren(v);
        });
        root.addProperty('allowRemoval', () => !removalIcon.hidden, (v) => removalIcon.hidden = !v);

        return /** @type {FactoryRoot & {name: Label, allowRemoval: boolean}} */ (root);
    }

    function createLabelBox({ initialList = /** @type {Label[]} */ ([]), readOnly = true, onLabelRemove = /** @type {(labelName: Label) => void} */ (null), placeholder = /** @type {FactoryContent} */ ('No Labels'), className = '', hidden = false, elementProperties = {} } = {}) {
        const root = createElement('div', {
            ...(className && { className }),
            ...(hidden && { hidden }),
            baseClassName: 'nhcb-label-box',
            ...elementProperties
        });
        const emptyPlaceholder = createElement('span', { className: 'nhcb-label-box-placeholder' }, placeholder);
        
        let isReadOnly = readOnly;
        let labels = /** @type {Set<Label>} */ (new Set());
        let labelRoots = /** @type {Array<FactoryRoot & {name: Label, allowRemoval: boolean}>} */ ([]);

        function replaceLabels(/** @type {Label[]} */ labelList) {
            labels = new Set(toArray(labelList));
            labelRoots = [...labels].map((labelName) => createGalleryLabel(labelName, { allowRemoval: !readOnly, onRemoveClick: removeLabel }));
            root.replaceChildren(emptyPlaceholder, ...labelRoots);
        }
        function addLabel(/** @type {Label} */ labelName) {
            if (!labels.has(labelName)) {
                labels.add(labelName);
                const newLabel = createGalleryLabel(labelName, { allowRemoval: !readOnly, onRemoveClick: removeLabel });
                labelRoots.push(newLabel);
                root.append(newLabel);
            }
        }
        function removeLabel(/** @type {Label} */ labelName) {
            if (labels.has(labelName)) {
                labels.delete(labelName);
                labelRoots = labelRoots.filter((root) => root.name !== labelName);
                root.replaceChildren(emptyPlaceholder, ...labelRoots);
                onLabelRemove?.(labelName);
            }
        }

        replaceLabels(initialList);

        root.addProperty('readOnly', () => isReadOnly, (v) => {
            isReadOnly = v;
            labelRoots.forEach((root) => root.allowRemoval = !isReadOnly);
        });
        root.replaceLabels = replaceLabels;
        root.addLabel = addLabel;
        root.removeLabel = removeLabel;

        return /** @type {FactoryRoot & {readOnly: boolean, replaceLabels: (labelList: Label[]) => void, addLabel: (labelName: Label) => void, removeLabel: (labelName: Label) => void}} */ (root);
    }

    function createSearchableDropdown({ inputId = '', availableOptions = /** @type {string[]} */ ([]), disabledOptions = /** @type {string[]} */ ([]), onSearchMatch = /** @type {(optionName: string, partialMatch: boolean) => void} */ (null), onSelect = /** @type {(selectedName: string) => void} */ (null), onSearchChange = /** @type {(input: string) => void} */ (null), initialValue = '',  placeholder = 'Search...', debounceMs = 200, disableFiltering = false, elementProperties = {} } = {}) {
        let searchableOptions = /** @type {Array<{name: string, disabled: boolean}>} */ ([]); // all possible options
        let searchMatches = /** @type {Array<{name: string, disabled: boolean}>} */ ([]);  // options matching search, subset of searchable options
        let optionRoots = /** @type {FactoryRoot[]} */ ([]); // roots contained in optionsDisplay
        let highlightedIndex = -1;
        let selectedOptionName = null;
        const highlightClass = 'selected';
        let debounceTimer = null;

        const root = createElement('div', {
            baseClassName: 'nhcb-searchable-dropdown',
            ...elementProperties
        });
        const searchInput = createInput({
            ...(inputId && { id: inputId }),
            placeholder,
            initialValue,
            elementProperties: {
                autocomplete: 'off',
                onfocus: openOptionsDisplay,
                oninput: scheduleSearch,
                onblur: closeOptionsDisplay,
                onkeydown: searchInputOnKeyDown
            }
        });
        const optionsDisplay = createElement('ul', {
            className: 'nhcb-searchable-dropdown-options',
            hidden: true,
            onmousedown: (e) => e.preventDefault(), // keep focus on the input so an option's click fires before blur
        });
        const emptyOptions = createElement('li', { className: 'nhcb-searchable-dropdown-empty' }, 'No matches');
        const createOption = (optionData) => createElement('li', { 
            baseClassName: 'nhcb-searchable-dropdown-option',
            ...( optionData.disabled && { className: 'nhcb-option-disabled' }),
            onclick: () => selectOption(optionData),
        }, optionData.name);
        

        function scheduleSearch() {
            clearTimeout(debounceTimer);
            debounceTimer = setTimeout(() => {
                if (document.activeElement !== searchInput.el) {
                    return;
                }
                repopulateOptionsDisplay();
                openOptionsDisplay();
                tryMatchSearch();    
                onSearchChange?.(searchInput.value);
            }, debounceMs);
        }

        function searchOptions() {
            if (disableFiltering) {
                return searchableOptions.map(option => ({ name: option.name, disabled: option.disabled }));
            }
            const query = searchInput.value.trim().toLowerCase();
            if (!query) {
                // browse mode: disabled options are hidden entirely
                return searchableOptions.filter(option => !option.disabled)
                            .map(option => ({ name: option.name, disabled: false }));
            }
            // search mode: disabled options reappear, but are not selectable
            return searchableOptions.filter(option => option.name.toLowerCase().includes(query))
                        .map(option => ({ name: option.name, disabled: option.disabled }));
        }
        function repopulateOptionsDisplay() {
            searchMatches = searchOptions();
            
            if (searchMatches.length === 0) {
                // no matches
                optionRoots = [];
                resetHighlight();
                selectedOptionName = null;
                optionsDisplay.replaceChildren(emptyOptions);
            } else {
                // display matches
                optionRoots = searchMatches.map((option) => createOption(option));
                resetHighlight();
                highlightNext();
                // if search no longer matches or if option no longer avaiable, remove selection
                if (selectedOptionName && (selectedOptionName !== searchInput.value || searchMatches.find((option) => !option.disabled && selectedOptionName === option.name) == null)) {
                    selectedOptionName = null;
                }
                optionsDisplay.replaceChildren(...optionRoots);
            }
        }

        function openOptionsDisplay() {
            optionsDisplay.hidden = false;
            resetHighlight();
            highlightNext();
        }
        function closeOptionsDisplay() {
            optionsDisplay.hidden = true;
            clearTimeout(debounceTimer);
        }

        function tryMatchSearch() {
            if (searchInput.value.trim() == '' || searchMatches.length == 0) {
                return;
            }
            if (searchMatches.length == 1 && !searchMatches[0].disabled) {
                selectedOptionName = searchMatches[0].name;
                onSearchMatch?.(searchMatches[0].name, searchInput.value != searchInput.value);
                return;
            }

            const exactMatch = searchMatches.find(({name, disabled}) => searchInput.value === name && !disabled);
            if (exactMatch) {
                selectedOptionName = exactMatch.name;
                onSearchMatch?.(exactMatch.name, false);
            }
        }
        function selectOption(option) {
            if (!option || option.disabled) {
                selectedOptionName = null;
                return;
            }
            searchInput.value = option.name;
            selectedOptionName = option.name;
            repopulateOptionsDisplay();
            onSelect?.(option.name);
            onSearchChange?.(option.name)
        }
        function selectHighlightedOption() {
            selectOption(searchMatches[highlightedIndex]);
        }

        // highlight via keyboard for selection
        function resetHighlight() {
            optionRoots[highlightedIndex]?.classList.remove(highlightClass);
            highlightedIndex = -1;
        }
        function highlightIndex(index) {
            highlightedIndex = index;
            optionRoots[index].classList.add(highlightClass);
            optionRoots[index].el.scrollIntoView({ block: 'nearest' });
        }
        function highlightNext(forwards = true) {
            if (searchMatches.length <= 0) {
                return;
            }
            const totalOptions = searchMatches.length;
            
            let i = highlightedIndex;
            const incrementAmount = forwards ? 1 : -1;
            for (let n = 0; n < totalOptions; n++) {
                i += incrementAmount;
                i = i >= totalOptions ? i - totalOptions : (i < 0 ? i + totalOptions : i);
                if (!searchMatches[i].disabled) {
                    resetHighlight();
                    highlightIndex(i);
                    return;
                }
            }
        }
        function searchInputOnKeyDown(e) {
            if (optionsDisplay.hidden && (e.key === 'ArrowDown' || e.key === 'ArrowUp')) {
                openOptionsDisplay();
                return;
            }
            switch (e.key) {
                case 'ArrowDown':
                    e.preventDefault();
                    highlightNext(true);
                    break;
                case 'ArrowUp':
                    e.preventDefault();
                    highlightNext(false);
                    break;
                case 'Tab':
                case 'Enter':
                    e.preventDefault();
                    selectHighlightedOption();
                    break;
                case 'Escape':
                    closeOptionsDisplay();
                    break;
            }
        }

        function setOptions(/** @type {string[]} */ options, /** @type {string[]} */ disabledOptions = null) {
            const optionToDisable = new Set(toArray(disabledOptions));
            searchableOptions = options?.map((name) => { return  { name, disabled: optionToDisable.has(name) } }) ?? [];
            repopulateOptionsDisplay();
        }
        function disableOptions(optionsToAlter, isDisabled = true) {
            const optionsMap = new Map(searchableOptions.map(option => [option.name, option]));
            toArray(optionsToAlter).forEach((name) => {
                const option = optionsMap.get(name);
                if (option) {
                    option.disabled = isDisabled;
                }
            });
            repopulateOptionsDisplay();
        }

        setOptions(availableOptions, disabledOptions);

        root.addProperty('searchInputValue', () => searchInput.value, (v) => { searchInput.value = v; });
        root.addProperty('selectedOption', () => selectedOptionName, (v) => { selectOption(searchableOptions.find((option) => option.name === v)) });
        root.getOptions = () => searchableOptions.map(option => option.text);
        root.replaceOptions = (options, disabledOptions = null) => setOptions(options, disabledOptions);
        root.disableOptions = disableOptions;
        root.clearSearch = () => {
            searchInput.value = '';
            repopulateOptionsDisplay();
            onSearchChange?.('');
        };

        root.append(searchInput, optionsDisplay);

        return /** @type {FactoryRoot & {searchInputValue: string, selectedOption: string|null, getOptions: () => string[], replaceOptions: (options: string[], disabledOptions: string[]) => void, disableOptions: (options: string|string[], isDisabled?: boolean) => void, clearSearch: () => void}} */ (root);
    }
    //#endregion

    //#region Site Elements
    function createContainerGeneric({ content = /** @type {FactoryContent} */ ([]), id = '', className = '', hidden = false, elementProperties = {} } = {}) {
        const root = createElement('div', {
            ...(id && { id }),
            ...(className && { className }),
            ...(hidden && { hidden }),
            baseClassName: 'container',
            ...elementProperties
        }, ...toArray(content));

        return root;
    }

    function createNavLink({ label = /** @type {FactoryContent} */ (''), link = '/', isDesktop = false, elementProperties = {} } = {}) {
        const root = createElement('li',
            { baseClassName: `${isDesktop ? 'desktop ' : ''}nhcb-nav-link`, ...elementProperties }, 
            createElement('a', { href: link }, ...toArray(label)),
        );
        
        return root;
    }

    function createNavGroup({ label = /** @type {FactoryContent} */ (''), content = /** @type {FactoryContent} */ ([]), id = '', className = '', hidden = false, elementProperties = {} } = {}) {
        const root = createElement('li', { 
            ...(id && { id }),
            ...(className && { className }),
            ...(hidden && { hidden }),
            baseClassName: 'desktop nhcb-nav-group',
            ...elementProperties            
        });

        const button = createElement('button',
            { className: 'nhcb-nav-group-button'},
            ...toArray(label),
            createIcon('chevron-down', { iconStyle: 'none', elementProperties: { className: '' } }),
        );
        button.el.setAttribute('aria-haspopup', true);
        button.el.setAttribute('aria-expanded', false);
        button.el.setAttribute('type', 'button');

        const menu = createElement('ul',
            { className: 'nhcb-nav-group-menu' },
            ...toArray(content),
        );

        button.el.onclick = () => {
            showMenu(!menu.classList.contains('open'));
        };

        addClickOutsideEvent(root, () => showMenu(false))

        function showMenu(isVisible) {
            menu.classList.toggle('open', isVisible);
            button.el.setAttribute('aria-expanded', isVisible);
        }

        root.append(button, menu);

        // override content target to
        root.append = (...children) => { factoryAppend(menu, ...children) },
        root.replaceChildren = (...children) => { factoryReplaceChildren(menu, ...children) };

        return root;
    }

    function createSortContainer({ content = /** @type {FactoryContent} */ ([]), hidden = false, elementProperties = {} } = {}) {
        const root = createElement('div', {
            ...(hidden && { hidden }),
            baseClassName: 'nhcb-sort-container sort',
            ...elementProperties
        }, ...toArray(content));

        return root;
    }
    function createSortTypeLink({ content = /** @type {FactoryContent} */ (''), href = '', isCurrent = false, hidden = false, elementProperties = {} } = {}) {
        const root = createElement('a', {
            ...(href && { href }),
            ...(hidden && { hidden }),
            ...(isCurrent && { baseClassName: 'current' }),
            ...elementProperties
        }, ...toArray(content));

        function setIsCurrent(isCurrent) {
            root.classList.toggle('current', isCurrent);
        }

        root.addProperty('isCurrent', () => root.classList.contains('current'), (v) => setIsCurrent(v));

        return /** @type {FactoryRoot & {isCurrent: boolean}} */ (root);
    }

    function createSortTypeGroup({ id = '', groupName = '', links = /** @type {{label: string, href: string, isCurrent: true|undefined }[]} */ ([]), hidden = false, elementProperties = {} } = {}) {
        const linkRoots = [];

        const root = createElement('div', {
            ...(id && { id }),
            ...(hidden && { hidden }),
            baseClassName: 'sort-type',
            ...elementProperties
        });

        if (groupName) {
            root.append(createElement('span', { className: 'sort-name' }, groupName));
        }

        links.forEach(({label, href, isCurrent}) => {
            linkRoots.push(createSortTypeLink({ content: label, href, isCurrent }));
        });

        root.append(...linkRoots);

        root.setIsCurrentExclusive = (targetIndex) => {
            linkRoots.forEach((linkRoot, i) => linkRoot.isCurrent(i === targetIndex));
        };

        return /** @type {FactoryRoot & {setIsCurrentExclusive: (targetIndex: int?) => void }} */ (root);
    }

    function createTagChip(/** @type {string} */ name, { href = '', count = /** @type {number} */ (null), tagType = /** @type {TagType} */ (null), hidden = false, elementProperties = {} } = {}) {
        const root = createElement('a', {
            baseClassName: 'nhcb-tagchip tagchip variant-pill state-normal',
            ...(href && { href }),
            ...(hidden && { hidden }),
            ...elementProperties,
        });

        if (tagType) {
            root.append(createElement('span', { className: `type type-${tagType}` }, tagType));
        }

        root.append(createElement('span', { className: `name` }, name.toString().replaceAll('-', ' ')));

        if (count != null) {
            const countString = count < 1000 ? count.toString() : (count / 1000).toFixed(1) + 'k';
            root.append(createElement('span', { className: `count`, title: `${count.toLocaleString()} galleries` }, countString));
        }

        return root;
    }

    function createPaginationNav({ currentPage = 1, totalPages = 2 }) {
        if (currentPage <= 0 || totalPages <= 0 || totalPages === 1) {
            return null;
        }
        // << < 1 ... 45(6)78 ... N > >>
        // << < 1(2)3456 ... N > >>
        // << < 123(4)56 ... N > >>
        // (1)23456 ... N > >>
        // << < 1 ... [-5][-4][-3][-2]([-1])[N] > >>
        // << < 1 ... [-5][-4]([-3])[-2][-1][N] > >>
        // << < 1 ... [-5][-4][-3][-2][-1]([N])
        function createHref(pageNumber) {
            return buildUrl({ setParams: {page: pageNumber} });
        }

        function createPageLink(pageNumber) {
            return createElement('a', { className: `page nhcb-pagination-page${currentPage == pageNumber ? ' current' : ''}`, href: createHref(pageNumber) }, pageNumber);
        }
        function createEtcSpan() {
            return createElement('span', { className: 'page nhcb-pagination-page' }, '...');
        }
        function createFirstLink() {
            return createElement('a', { className: 'first nhcb-pagination-first', href: createHref(1), ariaLabel: 'First page' }, createIcon('chevron-left', { iconStyle: 'none' }), createIcon('chevron-left', { iconStyle: 'none' }));
        }
        function createPreviousLink() {
            return createElement('a', { className: 'previous nhcb-pagination-previous', href: createHref(currentPage - 1), ariaLabel: 'Previous page' }, createIcon('chevron-left', { iconStyle: 'none' }));
        }
        function createNextLink() {
            return createElement('a', { className: 'next nhcb-pagination-next', href: createHref(currentPage + 1), ariaLabel: 'Next page' }, createIcon('chevron-right', { iconStyle: 'none' }));
        }
        function createLastLink() {
            return createElement('a', { className: 'first nhcb-pagination-last', href: createHref(totalPages), ariaLabel: 'Last page' }, createIcon('chevron-right', { iconStyle: 'none' }), createIcon('chevron-right', { iconStyle: 'none' }));
        }

        const content = [];
        const firstPage = 1;
        const lastPage = totalPages;
        const shouldShortenStart = (currentPage - firstPage) > 3;
        const shouldShortenEnd = (lastPage - currentPage) > 3;

        if (currentPage != firstPage) {
            // first/previous buttons
            content.push(createFirstLink());
            content.push(createPreviousLink());
        }

        // shorten (more than 7 pages)
        if (totalPages > 7) {
            // start - first 2 pages
            content.push(createPageLink(firstPage));
            if (shouldShortenStart) {
                content.push(createEtcSpan());
            } else {
                content.push(createPageLink(firstPage + 1));
            }

            // middle - currentPage +/- 2, (exclude first/last 2, show 6 on side not shortened)
            const start = Math.max(firstPage + 2, Math.min(currentPage - 2, lastPage - 5));
            const end = Math.min(lastPage - 2, Math.max(currentPage + 2, firstPage + 5));
            for (let pageNumber = start; pageNumber <= end; pageNumber++) {
                content.push(createPageLink(pageNumber));
            }

            // end - last 2 pages
            if (shouldShortenEnd) {
                content.push(createEtcSpan());
            } else {
                content.push(createPageLink(lastPage - 1));
            }
            content.push(createPageLink(lastPage));
        } 
        // else just add all pages (7 pages or less)
        else {
            for (let pageNumber = firstPage; pageNumber <= lastPage; pageNumber++) {
                content.push(createPageLink(pageNumber));
            }
        }

        if (currentPage != lastPage) {
            // next/last buttons
            content.push(createNextLink());
            content.push(createLastLink());
        }

        const root = createElement('section', { className: 'pagination nhcb-pagination' }, ...content);

        return root;
    }

    function createTimeAgoDisplay(/** @type {UnixSeconds} */ unixTimestamp, { className = '', hidden = false, elementProperties = {} } = {}) {
        const root = createElement('time', {
            ...(className && { className }),
            baseClassName: 'nhcb-time-ago-display',
            ...(hidden && { hidden }),
            ...elementProperties,
        });


        function toTimeAgoString(unixTimestamp) {
            const SecondsAgo = getUnixTimestamp() - unixTimestamp;

            if (SecondsAgo < 60) {
                return 'just now ';
            }

            let remainingSecondsAgo = SecondsAgo;

            const timeUnits = [
                { label: 'year',   sizeInSeconds: 31536000 },
                { label: 'month',  sizeInSeconds: 2628000  },
                { label: 'week',   sizeInSeconds: 604800   },
                { label: 'day',    sizeInSeconds: 86400    },
                { label: 'hour',   sizeInSeconds: 3600     },
                { label: 'minute', sizeInSeconds: 60       },
                { label: 'second', sizeInSeconds: 1        },
            ];

            const primaryIndex = timeUnits.findIndex(u => Math.floor(remainingSecondsAgo / u.sizeInSeconds) > 0);
            if (primaryIndex === -1) {
                return 'just now ';
            }

            const primaryTimeUnit = timeUnits[primaryIndex];
            const primaryTimeUnitCount = Math.floor(remainingSecondsAgo / primaryTimeUnit.sizeInSeconds);
            remainingSecondsAgo -= primaryTimeUnitCount * primaryTimeUnit.sizeInSeconds;

            const stringParts = [`${primaryTimeUnitCount} ${primaryTimeUnit.label}${primaryTimeUnitCount > 1 ? 's' : ''}`];

            const secondaryTimeUnit = timeUnits[primaryIndex + 1];
            if (secondaryTimeUnit) {
                const secondaryTimeUnitCount = Math.floor(remainingSecondsAgo / secondaryTimeUnit.sizeInSeconds);
                if (secondaryTimeUnitCount > 0) {
                    stringParts.push(`${secondaryTimeUnitCount} ${secondaryTimeUnit.label}${secondaryTimeUnitCount > 1 ? 's' : ''}`);
                }
            }

            return stringParts.join(', ') + ' ago ';
        }

        function changeTimestamp(unixTimestamp) {
            const date = getDateFromUnixTimestamp(unixTimestamp)
            root.el.setAttribute('datetime', date.toISOString());
            root.replaceChildren(toTimeAgoString(unixTimestamp), createElement('span', {}, `(${date.toLocaleDateString()})`));
        }

        changeTimestamp(unixTimestamp);

        root.changeTimestamp = changeTimestamp;

        return /** @type {FactoryRoot & {changeTimestamp: (unixTimestamp: UnixSeconds) => void}} */ (root);
    }

    function createInfoSection({ label = 'Info:', content = /** @type {FactoryContent} */ ([]), includeInfoBlockClasses = false, containsTags = false, hidden = false, elementProperties = {} } = {}) {
        const root = createElement('div', {
            ...(hidden && { hidden }),
            baseClassName: `${includeInfoBlockClasses || containsTags ? 'tag-container ' : ''}field-name nhcb-info-name`,
            ...elementProperties
        }, formatLabel(label));

        function formatLabel(text) {
            return text.endsWith(' ') ? text : text + ' '
        }

        const labelNode = root.el.firstChild;

        const infoSpan = createElement('span', { className: `${includeInfoBlockClasses ? 'tags ' : ''}nhcb-info-content` }, ...toArray(content));

        root.append(infoSpan);

        root.replaceContent = infoSpan.replaceChildren;
        root.renameLabel = (text) => labelNode.data = formatLabel(text);

        return /** @type {FactoryRoot & {replaceContent: (...children: (FactoryChild)[]) => void, renameLabel: (text) => void}} */ (root);
    }

    function createSearchResultsHeader({ resultCount = 0,  hidden = false, elementProperties = {} } = {}) {
        const root = createElement('div', {
            ...(hidden && { hidden }),
            baseClassName: `header-row nhcb-header-row`,
            ...elementProperties
        });


        root.append(createElement('h1', {}, createIcon('search', { iconStyle: 'none' }), ` ${resultCount.toLocaleString()} results`));

        return /** @type {FactoryRoot} */ (root);
    }

    function createPageContent() {
        const root = createElement('div', { id: 'content', style: 'padding-bottom: 1em' });
        return root;        
    }

    function createPageNavBar() {
        const root = createElement('nav');

        // no way to get user info without api key
        // need to implement that first
        const loggedIn = false; // userData.isLoggedIn; // note: this will not work because user data is unobtainable with current api
        // galaxy brain copy paste
        root.el.innerHTML = `<a class="logo" href="/"><img src="/logo.svg" alt="logo" width="46" height="30"></a>
        <form role="search" action="/search/" class="search"><input required="" type="search" name="q" autocapitalize="none" placeholder="e.g. full color"><button type="submit" class="btn btn-primary btn-square" aria-label="Search"><i class="fa fa-search fa-lg"></i></button></form>
        <button type="button" class="btn btn-secondary btn-square" id="hamburger" aria-label="Toggle menu"><span class="line"></span><span class="line"></span><span class="line"></span></button>
        <div class="collapse">
        <ul class="menu left"><li class="desktop  svelte-1ml9nak"><a href="/random/">Random</a></li><li class="desktop  svelte-1ml9nak"><a href="/tags/">Tags</a></li><li class="desktop  svelte-1ml9nak"><a href="/artists/">Artists</a></li><li class="desktop  svelte-1ml9nak"><a href="/characters/">Characters</a></li><li class="desktop  svelte-1ml9nak"><a href="/parodies/">Parodies</a></li><li class="desktop  svelte-1ml9nak"><a href="/groups/">Groups</a></li><li class="desktop community-menu svelte-1ml9nak"><button type="button" class="community-btn svelte-1ml9nak" aria-haspopup="true" aria-expanded="false">Community <i class="fa fa-chevron-down community-caret svelte-1ml9nak" aria-hidden="true"></i></button><ul class="community-panel svelte-1ml9nak"><li class="svelte-1ml9nak"><a href="/community/taxonomy/" class="svelte-1ml9nak">Taxonomy</a></li><li class="svelte-1ml9nak"><a href="/community/gts-backlog/" class="svelte-1ml9nak">GTS Backlog</a></li><li class="svelte-1ml9nak"><a href="/info/" class="svelte-1ml9nak">Info</a></li></ul></li><li class="desktop"><a href="//tsyndicate.com/api/v1/direct/e220320bd2e542b8a2ab7cd2c5a9df8c?" target="_blank" rel="noopener">Create AI Porn 💦</a></li><li class="desktop"><a href="https://twitter.com/nhentaiOfficial" aria-label="Twitter"><i class="fab fa-twitter fa-lg"></i></a></li><li class="dropdown"><button class="btn btn-secondary btn-square" type="button" id="dropdown" aria-label="More links"><i class="fa fa-chevron-down"></i></button><ul class="dropdown-menu"><li class="svelte-1ml9nak"><a href="/random/">Random</a></li><li class="svelte-1ml9nak"><a href="/tags/">Tags</a></li><li class="svelte-1ml9nak"><a href="/artists/">Artists</a></li><li class="svelte-1ml9nak"><a href="/characters/">Characters</a></li><li class="svelte-1ml9nak"><a href="/parodies/">Parodies</a></li><li class="svelte-1ml9nak"><a href="/groups/">Groups</a></li><li class="svelte-1ml9nak"><a href="/community/taxonomy/">Taxonomy</a></li><li class="svelte-1ml9nak"><a href="/community/gts-backlog/">GTS Backlog</a></li><li class="svelte-1ml9nak"><a href="/info/">Info</a></li><li><a href="//tsyndicate.com/api/v1/direct/e220320bd2e542b8a2ab7cd2c5a9df8c?" target="_blank" rel="noopener">Create AI Porn 💦</a></li><li><a href="https://twitter.com/nhentaiOfficial" aria-label="Twitter"><i class="fab fa-twitter fa-lg"></i></a></li></ul></li></ul>
        ${loggedIn
            ? `<ul class="menu right"><li><a href="/user/favorites/"><i class="fa fa-heart color-icon"></i> Favorites</a></li><li><a href="/users/${userData.info.id}/${userData.info.slug}/"><img loading="lazy" alt="" class="nav-avatar" src="${formatMediaServer(userData.info.avatar_url)}"><span class="username">${userData.info.username}</span></ul>`
            : `<ul class="menu right"><li class="menu-sign-in"><a href="/login/"><i class="fa fa-sign-in-alt"></i> Sign in</a></li><li class="menu-register"><a href="/register/"><i class="fa fa-edit"></i> Register</a></li></ul>`}
        </div>`;

        // if logged in (log out event needed)
        // <ul class="menu right"><li><a href="/user/favorites/"><i class="fa fa-heart color-icon"></i> Favorites</a></li><li><a href="/users/<UserData.id>/<UserData.slug>/"><img loading="lazy" alt="" class="nav-avatar" src="<formatMediaServer(UserData.avatar_url)>"><span class="username"><UserData.username></span></a></li><li><a href="/"><i class="fa fa-sign-out-alt"></i> Log out</a></li></ul>
        // if not logged in
        // <ul class="menu right"><li class="menu-sign-in"><a href="/login/"><i class="fa fa-sign-in-alt"></i> Sign in</a></li><li class="menu-register"><a href="/register/"><i class="fa fa-edit"></i> Register</a></li></ul>

        const hamburger = root.el.querySelector('#hamburger');
        const hamburgerMenu = root.el.querySelector('.collapse');
        if (hamburger && hamburger) {
            hamburger.addEventListener('click', () => {
                hamburger.classList.toggle('open');
            });
        }

        const dropdownButton = root.el.querySelector('#dropdown');
        const dropdownMenu = root.el.querySelector('.dropdown-menu');
        if (dropdownButton && dropdownMenu) {
            dropdownButton.addEventListener('click', () => {
                dropdownMenu.classList.toggle('open');
            });
        }

        const communityMenu = root.el.querySelector('.community-menu');
        const communityButton = root.el.querySelector('.community-menu .community-btn');
        const communityPanel = root.el.querySelector('.community-menu .community-panel');
        if (communityMenu && communityButton && communityPanel) {
            communityMenu.classList.add('nhcb-nav-group');
            communityButton.classList.add('nhcb-nav-group-button');
            communityPanel.classList.add('nhcb-nav-group-menu');
            communityButton.addEventListener('click', () => {
                communityPanel.classList.toggle('open');
                communityButton.ariaExpanded = !(communityButton.ariaExpanded === 'true');
            });
            addClickOutsideEvent(communityMenu, () => {
                communityPanel.classList.toggle('open', false);
                communityButton.ariaExpanded = false;
            });
        }

        return root;
    }

    /**
     * Expects tags to already be in cache. Will skip tags not in cache.
     */
    function createGalleryPageBigContainer(/** @type {GalleryData} */ galleryData, { disableCoverLink = false, coverOverride = /** @type { { href: string thumbnail: string, thumbnail_width: number, thumbnail_height: number}? } */ (null) } = {}) {
        const primaryTitle = galleryData.english_title ?? galleryData.japanese_title ?? 'Missing Title';

        // Structure
        // div#bigcontainer
        //   div#cover
        //     a
        //       img
        //   div#info-block
        //     div#info
        //       h1 (english, pretty)
        //       h2 (japanese)
        //       h3 (gallery id)
        //       section#tags
        //         ...div Label: ...tags
        //       div.buttons
        //         (favorite button)
        //         (download button)

        const coverInfo = {
            href: coverOverride?.href ?? `${galleryIdToPath(galleryData.id)}1/`,
            thumbnail: coverOverride?.thumbnail ?? galleryData.thumbnail ?? DEFINITIONS.ERROR_404_IMAGE.path,
            thumbnail_width:  coverOverride?.thumbnail_width ?? galleryData.thumbnail_width ?? DEFINITIONS.ERROR_404_IMAGE.width,
            thumbnail_height:  coverOverride?.thumbnail_height ?? galleryData.thumbnail_height ?? DEFINITIONS.ERROR_404_IMAGE.height,
        };
        const bigContainer = createDiv({ id: 'bigcontainer', className: 'container svelte-iec8wt'},
            createDiv({ id: 'cover', className: 'svelte-iec8wt' },
                createElement('a', { className: 'svelte-iec8wt', ...(!disableCoverLink && { href: coverInfo.href }) },
                    createElement('img', { className: 'lazyload', loading: 'eager', alt: primaryTitle, width: '350', height: `${Math.round((coverInfo.thumbnail_height/coverInfo.thumbnail_width)*350)}`, src: coverInfo.thumbnail })
                )
            )            
        );

        const infoBlock = createDiv({ id: 'info-block', className: 'svelte-iec8wt' });
        const infoContainer = createDiv({ id: 'info', className: 'svelte-iec8wt' });

        // titles
        const titleSections = parseTitleSections(primaryTitle);
        const titleRoot = createElement('h1', { className: 'title svelte-iec8wt' });
        factoryAppendSkipNull(titleRoot,
            titleSections.before != '' ? createSpan(titleSections.before, { className: 'before svelte-iec8wt' }) : null,
            titleSections.pretty != '' ? createSpan(titleSections.pretty, { className: 'pretty svelte-iec8wt' }) : null,
            titleSections.after  != '' ? createSpan(titleSections.after,  { className: 'after svelte-iec8wt' })  : null
        )
        infoContainer.append(titleRoot);

        if (galleryData.english_title == undefined && galleryData.japanese_title) {
            infoContainer.append(createElement('h2', { className: 'title svelte-iec8wt' }, galleryData.japanese_title));
        }
        const galleryId = galleryData.id ?? 'unknown';
        infoContainer.append(createElement('h3', { 
                id: 'gallery_id',
                className: 'svelte-iec8wt',
                style: 'cursor: pointer;',
                onclick: () => {
                    const id =
                    GM_setClipboard(galleryId);
                    notifier.info(`Copied "${galleryId}" to clipboard.`);
                }
            },
            createSpan('#', { className: 'hash svelte-iec8wt'}),
            galleryId
        ));

        // tags
        const tagSection = createElement('section', { id: 'tags', className: 'svelte-iec8wt' });
        const tagIdMap = new Map([...cachedApiData.tags.values()].map(data => ([data.id, data])));
        /** @type {Map<string, TagData[]>} */
        const tagTypeMap = new Map();
        galleryData.tag_ids.forEach((id) =>{
            const tagData = tagIdMap.get(id);
            if (tagData) {
                const tagType = tagData.type;
                let tagList = tagTypeMap.get(tagType);
                if (!tagList) {
                    tagList = []
                    tagTypeMap.set(tagType, tagList);
                }
                tagList.push(tagData);
            }
        });
        const tagTypeOrder = [TAG_TYPES.PARODY, TAG_TYPES.CHARACTER, TAG_TYPES.TAG, TAG_TYPES.ARTIST, TAG_TYPES.GROUP, TAG_TYPES.LANGUAGE, TAG_TYPES.CATEGORY];
        tagTypeOrder.forEach(tagType => {
            const tags = tagTypeMap.get(tagType);
            if (tags && tags.length > 0) {
                const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1);
                const label = `${capitalize(TAG_TYPES.plural(tagType))}: `;
                const content = tags.map(tag => createTagChip(tag.name, { href: tag.url, count: tag.count }));
                const infoSection = createInfoSection({ label, content, includeInfoBlockClasses: true });
                tagSection.append(infoSection);
            }
        });
        tagSection.append(createInfoSection({ label: 'Pages: ', includeInfoBlockClasses: true, content: (galleryData.num_pages != undefined ? createTagChip(galleryData.num_pages) : `¯\\(ツ)/¯`) }));
        tagSection.append(createInfoSection({ label: 'Uploaded: ', includeInfoBlockClasses: true, content: `¯\\(ツ)/¯` }));
        infoContainer.append(tagSection);

        // buttons
        const buttonsContainer = createDiv({ className: 'buttons btn-group svelte-iec8wt' });
        
        // favorite button
        if (settingsStore.enableCustomFavoritesButton.value && !settingsStore.customFavoritesSeparateButton.value) {
            buttonsContainer.append(
                createElement('button', { className: 'btn btn-primary btn-disabled tooltip svelte-iec8wt', type: 'button' },
                    createElement('i', { className: 'fas fa-heart svelte-iec8wt' }),
                    createElement('span', { className: 'svelte-iec8wt' },
                        'Favorite ',
                        createElement('span', { className: 'nobold svelte-iec8wt' }, `(404)`)
                    )
                )
            );
        }

        infoContainer.append(buttonsContainer);
        infoBlock.append(infoContainer);
        bigContainer.append(infoBlock);

        return bigContainer;
    }
    //#endregion

    //#region Combo Elements
    function createDropdownMenu({ content = /** @type {FactoryContent} */ ([]), className = '', hidden = false, disabled = false, elementProperties = {} } = {}) {
        const root = createElement('div', {
            ...(hidden && { hidden }),
            ...(className && { className }),
            baseClassName: 'nhcb-dropdown-wrapper',
            ...elementProperties
        });

        const dropdownButton = createButton({ content: createIcon('chevron-down', { iconStyle: 'none' }), buttonStyle: 'square', onClick: () => toggleMenu(), disabled, elementProperties: { className: 'nhcb-dropdown-button' } });
        const dropdownMenu = createElement('div', { className: 'nhcb-dropdown-menu', tabIndex: -1 }, ...toArray(content));

        addClickOutsideEvent(root, () => toggleMenu(false))

        function toggleMenu(openMenu = undefined) {
            const openState = openMenu != null ? openMenu : !dropdownMenu.classList.contains('nhcb-menu-open');
            dropdownMenu.classList.toggle('nhcb-menu-open', openState);
            dropdownMenu.hidden = !openState;
        }

        toggleMenu(false);
        root.append(dropdownButton, dropdownMenu);
        
        root.append = dropdownMenu.append;
        root.replaceChildren = dropdownMenu.replaceChildren;
        root.addProperty('disabled', () => dropdownButton.disabled, (v) => { dropdownButton.disabled = v; } )
        root.showMenu = (isVisible) => toggleMenu(isVisible);

        return /** @type {FactoryRoot & {showMenu: (isVisible: boolean) => void}} */ (root);
    }

    /**
     * The gigachad.
     * @param {Object} config
     * @param {FactoryContent} [config.labelContent]
     * @param {FactoryContent} [config.submitButtonContent]
     * @param {string} [config.tooltipInfo] If ommited, then no tooltip element is made
     * @param {string} config.tooltipWidth
     * @param {DropdownOptions} config.options
     * @param {any} [config.initialValue] If `lockSubmitIfUnchanged` is enabled, then this will act as the last commited value.
     * @param {false|boolean} config.lockSubmitIfUnchanged If enabled, the submit button will be deactivated while the value is same as the last commited value.
     * @param {true|boolean} config.useSafetyLock If `false`, the safety lock is hidden
     * @param {true|boolean} config.useSubmitButton If `false`, the submit button is hidden and values are commited at `onSelectedChange`.
     * @param {(value: string|'', index: int|-1) => boolean} config.onCommit Synonym to `onSubmit` but applies more broadly. Can return `false` to prevent updating the last commited value.
     * @param {(value: string|'', index: int|-1) => void} config.onSelectedChange
     * @param {boolean} config.hidden
     * @param {boolean} config.disabled
     * @param {Object} config.elementProperties
     */
    function createDropdownField({ id = '', labelContent = '', submitButtonContent = [], tooltipInfo = '', tooltipWidth = '200px', options = [], initialValue = undefined, lockSubmitIfUnchanged = false, useSafetyLock = true, useSubmitButton = true, onCommit = null, onSelectedChange = null, hidden = false, disabled = false, elementProperties = {} } = {}) {
        const root = createFieldLayout({ id, hidden, elementProperties });
        root.classList.add('nhcb-dropdown-field'); // done this way to prevent bug

        let lastCommitedValue = initialValue?.toString();
        let submitLocked = lockSubmitIfUnchanged;
        let isDisabled = disabled;
        let safetyLockLocked = useSafetyLock;

        const isDropdownDisabled = () => safetyLockLocked || isDisabled;
        const isSubmitDisabled = () => safetyLockLocked || isDisabled || submitLocked;

        // required elements
        const label = createElement('label', {}, labelContent);
        const dropdownSelect = createDropdownSelect({ options, initialValue, disabled: isDropdownDisabled(), onSelectedChange: handleSelectedChange });
        // optional elements
        const submitButton = useSubmitButton ? createButton({ content: submitButtonContent, disabled: isSubmitDisabled(), buttonStyle: 'primary', onClick: commitChange }) : null;
        const safetyLock = useSafetyLock ? createSafetyLock({ onChange: handleSafetyLockChange }) : null;
        const tooltip = tooltipInfo ? createTooltip({ content: tooltipInfo, width: tooltipWidth }) : null;

        const updateDropdownDisabled = () => { dropdownSelect.disabled = isSubmitDisabled() }; 
        const updateSubmitButtonDisabled = submitButton ? () => { submitButton.disabled = isSubmitDisabled() } : () => {};
        const setIsLocked = safetyLock ? (isLocked) => { safetyLock.isLocked = isLocked; safetyLockLocked = isLocked; } : () => {};

        updateSubmitButtonLock(dropdownSelect.value);


        function commitChange() {
            const ok = onCommit?.(dropdownSelect.value, dropdownSelect.selectedIndex) ?? true;
            if (ok) {
                lastCommitedValue = dropdownSelect.value;
                setIsLocked(true);
                updateSubmitButtonLock(lastCommitedValue);
            }
        }
        function handleSelectedChange(value, index) {
            onSelectedChange?.(value, index);
            if (!useSubmitButton) {
                commitChange();
            }
            updateSubmitButtonLock(value);
        }
        function handleSafetyLockChange(isLocked) {
            safetyLockLocked = isLocked;
            updateDropdownDisabled();
            updateSubmitButtonDisabled();
        }
        function updateSubmitButtonLock(currentValue) {
            if (lockSubmitIfUnchanged) {
                submitLocked = currentValue === lastCommitedValue;
            }
            updateSubmitButtonDisabled();
        }

        factoryAppendSkipNull(root, safetyLock, label, tooltip, dropdownSelect, submitButton);

        root.addProperty('disabled', () => isDisabled, (v) => { isDisabled = v; updateDropdownDisabled(); updateSubmitButtonDisabled(); });
        root.addProperty('selectedIndex', () => dropdownSelect.selectedIndex, (v) => dropdownSelect.selectedIndex = v);
        root.addProperty('value', () => dropdownSelect.value, (v) => dropdownSelect.value = v);
        root.addProperty('isLocked', () => safetyLock?.isLocked, setIsLocked);
        root.replaceOptions = dropdownSelect.replaceOptions;

        return /** @type {FactoryRoot & {disabled: boolean, value: string|'', selectedIndex: int|-1, isLocked: boolean, replaceOptions: (options: DropdownOptions) => void}} */ (root);
    }

    /**
     * @param {Object} config
     * @param {string} config.id
     * @param {string} config.labelContent
     * @param {string} config.submitButtonContent
     * @param {string} [config.tooltipInfo] If ommited, then no tooltip element is made
     * @param {string} config.tooltipWidth
     * @param {string} [config.initialValue]
     * @param {string} config.placeholder
     * @param {false|boolean} config.lockSubmitIfUnchanged If enabled, the submit button will be disabled while the value is same as the last commited value.
     * @param {true|boolean} config.useSafetyLock If `false`, the safety lock is hidden
     * @param {(value: string|'') => boolean} config.onInputChange Can return `false` to siginify that the new input is invalid and the submit button should be locked.
     * @param {(value: string|'') => boolean} config.onCommit Can return `false` to prevent updating the last commited value.
     * @param {int} config.debounceMs
     * @param {boolean} config.hidden
     * @param {boolean} config.disabled
     * @param {Object} config.elementProperties
     */
    function createInputField({ id = '', labelContent = '', submitButtonContent = [], tooltipInfo = '', tooltipWidth = '200px', initialValue = undefined, placeholder = 'Input...', lockSubmitIfUnchanged = false, useSafetyLock = true, onInputChange = null, onCommit = null, debounceMs = 200, hidden = false, disabled = false, elementProperties = {} } = {}) {
        const root = createFieldLayout({ id, hidden, elementProperties });
        root.classList.add('nhcb-input-field'); // done this way to prevent bug

        let debounceTimer = null;

        let lastCommitedValue = initialValue == null ? null : initialValue.toString();
        let submitLocked = lockSubmitIfUnchanged;
        let isDisabled = disabled;
        let safetyLockLocked = useSafetyLock;

        const isInputDisabled = () => safetyLockLocked || isDisabled;
        const isSubmitDisabled = () => safetyLockLocked || isDisabled || submitLocked;

        // required elements
        const label = createElement('label', {}, labelContent);
        const input = createInput({ initialValue: lastCommitedValue, placeholder, disabled: isInputDisabled(), elementProperties: {
                autocomplete: 'off',
                oninput: scheduleOnInputChange,
                onkeydown: searchInputOnKeyDown //disable submit while typing
            }});
        const submitButton = createButton({ content: submitButtonContent, disabled: isSubmitDisabled(), buttonStyle: 'primary', onClick: commitChange });
        // optional elements
        const safetyLock = useSafetyLock ? createSafetyLock({ onChange: handleSafetyLockChange }) : null;
        const tooltip = tooltipInfo ? createTooltip({ content: tooltipInfo, width: tooltipWidth }) : null;

        const updateInputDisabled = () => { input.disabled = isInputDisabled() }; 
        const updateSubmitButtonDisabled = submitButton ? () => { submitButton.disabled = isSubmitDisabled() } : () => {};
        const setIsLocked = safetyLock ? (isLocked) => { safetyLock.isLocked = isLocked; safetyLockLocked = isLocked; } : () => {};

        updateSubmitButtonLock(input.value);

        function scheduleOnInputChange() {
            clearTimeout(debounceTimer);
            debounceTimer = setTimeout(() => {
                if (document.activeElement !== input.el) {
                    return;
                }
                updateSubmitButtonLock(input.value);
                const inputValid = onInputChange?.(input.value) ?? true;
                if (!inputValid) {
                    submitLocked = true;
                    updateSubmitButtonDisabled();
                }
            }, debounceMs);
        }
        function searchInputOnKeyDown() {
            // i dont remember what this was suppose to do and it was causing unwanted behavior
            // if (debounceTimer > 0) {
            //     updateSubmitButtonLock(input.value);
            // }
        }


        function commitChange() {
            const ok = onCommit?.(input.value) ?? true;
            if (ok) {
                lastCommitedValue = input.value;
                setIsLocked(true);
                updateSubmitButtonLock(lastCommitedValue);
            }
        }
        function handleSafetyLockChange(isLocked) {
            safetyLockLocked = isLocked;
            updateInputDisabled();
            updateSubmitButtonDisabled();
        }
        function updateSubmitButtonLock(currentValue) {
            if (lockSubmitIfUnchanged) {
                submitLocked = currentValue === lastCommitedValue;
            }
            updateSubmitButtonDisabled();
        }

        factoryAppendSkipNull(root, safetyLock, label, tooltip, input, submitButton);

        root.addProperty('disabled', () => isDisabled, (v) => { isDisabled = v; updateInputDisabled(); updateSubmitButtonDisabled(); });
        root.addProperty('value', () => input.value, (v) => { input.value = v; lastCommitedValue = v; updateSubmitButtonLock(v); });
        root.addProperty('type', () => input.el.type, (v) => input.el.type = v);
        root.addProperty('isLocked', () => safetyLock?.isLocked, setIsLocked);

        return /** @type {FactoryRoot & {disabled: boolean, value: string|'', type: string?, isLocked: boolean}} */ (root);
    }

    function createLabelsField({ availableLabels = /** @type {Label[]} */ ([]), initialLabels =  /** @type {Label[]} */ ([]), onLabelAdd = /** @type {(labelName: Label) => void} */ (null), onLabelRemove = /** @type {(labelName: Label) => void} */ (null), addOnSelect = true, hidden = false, elementProperties = {} } = {}) {
        const root = createElement('div', {
            ...(hidden && { hidden }),
            baseClassName: 'nhcb-label-field',
            ...elementProperties
        });

        const availableLabelsSet = new Set(availableLabels);
        const labels = new Set(initialLabels);        
        const searchableDropdown = createSearchableDropdown({ availableOptions: availableLabels, disabledOptions: initialLabels, placeholder: 'Search labels...', onSearchChange: handleSearchChange, onSelect: handleSelect });
        const submitButton = createButton({ content: 'Add Label', buttonStyle: 'primary', onClick: handleSubmit, disabled: true });
        const labelBox = createLabelBox({ initialList: initialLabels, readOnly: false, onLabelRemove: handleLabelRemove });
        const fieldLayout = createFieldLayout({ content: [searchableDropdown, submitButton] })

        function handleSearchChange(search) {
            submitButton.disabled = (searchableDropdown.selectedOption != search.trim().toLowerCase());
        }
        function handleSelect(labelName) {
            if (addOnSelect) {
                handleSubmit();
                searchableDropdown.el.children[0].blur(); // a bit hacky, but its to close dropdown and deselect input after adding
            } else {
                submitButton.disabled = false;
            }
        }
        function handleSubmit() {
            const newLabel = searchableDropdown.selectedOption;
            if (newLabel && !labels.has(newLabel)) {
                addLabel(newLabel);
            }
            searchableDropdown.disableOptions(newLabel, true);
            searchableDropdown.clearSearch();
            submitButton.disabled = true;
        }
        function handleLabelRemove(labelName) {
            labels.delete(labelName);
            searchableDropdown.disableOptions(labelName, false);
            onLabelRemove?.(labelName);
        }

        function addLabel(labelName) {
            labels.add(labelName);
            labelBox.addLabel(labelName);
            onLabelAdd?.(labelName);
        }

        root.append(fieldLayout, labelBox);

        root.getLabels = () => [...labels];

        return /** @type {FactoryRoot & {getLabels: () => Label[]}} */ (root);
    }

    function createRatingDisplay({ rating = 0, hidden = false, elementProperties = {} } = {}) {
        const root = createElement('div', {
            ...(hidden && { hidden }),
            baseClassName: 'nhcb-rating-display',
            ...elementProperties
        });

        function createRatingHeart(value = /** @type {'full'|'half'|'none'} */ ('full')) {
            const resolveClass = (value) => `nhcb-rating-heart nhcb-heart-${value ?? 'none'}`;
            const root = createElement('div', {
                className: resolveClass(value),
            }, createIcon('heart', { iconStyle: 'solid' }), createIcon('heart', { iconStyle: 'solid' }));

            let heartValue = value;
            root.addProperty('value', () => heartValue, (v) => { heartValue = v; root.el.className = resolveClass(v); });

            return /** @type {FactoryRoot & {value: 'full'|'half'|'none'}} */ (root);
        }

        const heartRoots = Array(5).fill().map(() => createRatingHeart());

        function updateRatingDisplay(newRating) {
            heartRoots.forEach((root, i) => {
                const threshold = (i + 1) * 2;
                if (newRating == 0) {
                    root.hidden = true; // setting root.value override classes so no need to unset
                } else if (newRating >= threshold) {
                    root.value = 'full';
                } else if (newRating >= threshold - 1) {
                    root.value = 'half';
                } else {
                    root.value = 'none';
                }
            });
        }

        updateRatingDisplay(rating);

        root.changeRating = updateRatingDisplay;

        root.append(...heartRoots);

        return /** @type {FactoryRoot & {changeRating: (newRating: int) => void}} */ (root);
    }

    function createNotesField({ textAreaClassName = '', maxLength = null, initialValue = '', onSaveClick = /** @type {(value: string) => string|null} */ (null), viewModePlaceholder = 'None', editModePlaceHolder = 'Enter Note...', hidden = false, elementProperties = {} } = {}) {
        const root = createElement('div', {
            ...(hidden && { hidden }),
            baseClassName: 'nhcb-notes-field',
            ...elementProperties
        });

        let defaultValue = initialValue ?? '';

        const textArea = createElement('textarea', { 
            placeholder: '', //needed for css
            ...(textAreaClassName && { className: textAreaClassName }),
            ...(maxLength && { maxLength }),
        });

        const buttonsWrapper = createElement('div');

        const editButton = createButton({ content: 'Edit Notes', buttonStyle: 'primary', onClick: () => setEditState(true) });
        const confirmButton = createButton({ content: 'Confirm', buttonStyle: 'primary', onClick: handleConfirmClick });
        const cancelButton = createButton({ content: 'Cancel', onClick: () => setEditState(false) });

        function setEditState(isEditMode) {
            textArea.el.value = defaultValue;
            textArea.el.placeholder = isEditMode ? editModePlaceHolder : viewModePlaceholder;
            textArea.el.readOnly = !isEditMode;

            editButton.hidden = isEditMode;
            confirmButton.hidden = !isEditMode;
            cancelButton.hidden = !isEditMode;
        }
        function handleConfirmClick() {
            if (onSaveClick) {
                const newValue = onSaveClick(textArea.el.value);
                if (newValue != null) {
                    defaultValue = newValue;
                    setEditState(false);
                }
            } else {
                defaultValue = textArea.el.value;
                setEditState(false);
            }
        }

        setEditState(false);

        buttonsWrapper.append(editButton, confirmButton, cancelButton);
        root.append(textArea, buttonsWrapper);

        return root;
    }

    function createSettingsField(settingName, { labelContent = /** @type {FactoryContent} */ (''), tooltipInfo = '', options = /** @type {DropdownOptions} */ ([]), optionValueParser = ((v) => v) } = {}) {
        if (!settingsStore.hasField(settingName)) {
            reportIssue('MISSING_SETTING', { settingName, settings: settingsStore.fieldKeys() });
            return null;
        }
        const settingField = settingsStore[settingName];

        const root = createDropdownField({ 
            labelContent,
            tooltipInfo,
            submitButtonContent: 'Save',
            options,
            initialValue: settingField.value,
            useSafetyLock: false,
            lockSubmitIfUnchanged: true,
            onCommit: handleSubmit,
        });

        function handleSubmit(value) {
            const newValue = optionValueParser(value);
            if (newValue == null) {
                return false;
            }
            // no need to load the setting before saving because all settings that use this should be literals
            settingField.value = newValue;
            settingField.save();
            logger.storeUpdates.log(`Setting '${settingName}' was changed to ${newValue}`);
        }

        return root;
    }
    function createBinarySettingsField(settingName, { labelContent = /** @type {FactoryContent} */ (''), tooltipInfo = '', binaryOptionType = /** @type {'yes/no'|'on/off'|'enabled/disabled'} */ ('yes/no') } = {}) {
        const resolveBinaryOptions = (type) => {
            switch (type) {
                case 'on/off':
                    return [[true, 'On'], [false, 'Off']];
                case 'enabled/disabled':
                    return [[true, 'Enabled'], [false, 'Disabled']];
                case 'yes/no':
                default:
                    return [[true, 'Yes'], [false, 'No']];
            }            
        }
        return createSettingsField(settingName, { labelContent, tooltipInfo, options: resolveBinaryOptions(binaryOptionType), optionValueParser: parseBool });
    }
    function createTextSettingsField(settingName, { labelContent = /** @type {FactoryContent} */ (''), tooltipInfo = '', valueParser = ((v) => v), valueFormatter = ((v) => v), placeholder = 'Enter value...' } = {}) {
        if (!settingsStore.hasField(settingName)) {
            reportIssue('MISSING_SETTING', { settingName, settings: settingsStore.fieldKeys() });
            return null;
        }
        const settingField = settingsStore[settingName];

        const root = createInputField({ 
            labelContent,
            tooltipInfo,
            submitButtonContent: 'Save',
            initialValue: valueFormatter(settingField.value),
            placeholder,
            useSafetyLock: false,
            lockSubmitIfUnchanged: true,
            onCommit: handleCommit,
            onInputChange: handleInputChange,
        });

        function handleCommit(value) {
            const newValue = valueParser(value);
            if (newValue == null) {
                return false;
            }
            // no need to load the setting before saving because all settings that use this should be literals
            settingField.value = newValue;
            settingField.save();
            logger.storeUpdates.log(`Setting '${settingName}' was changed to ${newValue}`);
        }

        function handleInputChange(value) {
            const newValue = valueParser(value);
            if (newValue == null) {
                return false;
            }
            return true;
        }

        return root;
    }
    /**
     * 
     * @param {string} name Name for the header of the panel
     * @param {string} tooltipInfo Tooltip for the panel
     * @param {Array<{storeKey: string, label: FactoryContent, tooltip: string} & ({type: 'options', options: DropdownOptions, valueParser?: (v: string) => string|null, valueFormatter?: (v: any) => string} | {type: 'binary', binaryOptionType?: 'yes/no'|'on/off'|'enabled/disabled'} | {type: 'text', placeholder?: string, valueParser?: (v: string) => string|null, valueFormatter?: (v: any) => string})>} settingsInfo Config object that defines the settings
     * @returns {FactoryRoot}
     */
    function createSettingsPanel(name, tooltip, settingsInfo) {
        const root = createElement('div', {}, createElement('h2', {}, name, createTooltip({ content: tooltip, width: '200px' })));

        root.append(...settingsInfo.map(config => {
            switch (config.type) {
                case 'options':
                    return createSettingsField(config.storeKey, { labelContent: config.label, tooltipInfo: config.tooltip, options: config.options, optionValueParser: config.valueParser });
                case 'binary':
                    return createBinarySettingsField(config.storeKey, { labelContent: config.label, tooltipInfo: config.tooltip, binaryOptionType: config.binaryOptionType });
                case 'text':
                    return createTextSettingsField(config.storeKey, { labelContent: config.label, tooltipInfo: config.tooltip, valueParser: config.valueParser, valueFormatter: config.valueFormatter, placeholder: config.placeholder });
                default:
                    throw new Error(`Setting config has invalid type "${config.type}"`);
            }
        }))

        return root;
    }
    //#endregion

    //#region Special Elements
    function createNotifier({ defaultDuration = 10 } = {}) {
        const root = createElement('div', { id: 'nhcb-notifier' });

        const noticeLevels = {
            info: { className: 'nhcb-notice-info', label: 'Notice' },
            warn: { className: 'nhcb-notice-warn', label: 'Warning' },
            error: { className: 'nhcb-notice-error', label: 'Error' }
        }

        function handleInjection() {
            injector.injectElement(() => root.el, '#app', '#nhcb-notifier', -1, false);
        }

        function notify({ content, level = 'info', duration = defaultDuration }) {
            const notice = createElement('div', {
                className: `nhcb-notice ${noticeLevels[level].className}`,
                title: 'Click to dismiss',
                innerHTML: `<strong>NH Custom Brew - ${noticeLevels[level].label}</strong>`
            });

            const noticeMessage = createElement('div', {}, ...toArray(content));
            
            const dismiss = () => notice.el.remove();
            notice.el.addEventListener('click', dismiss);

            // if duration is not null, timeout after duration
            // if duration is null, no timeout
            // if duration is undefined and not an error, use defaultDuration
            // if duration is undefined and an error, no timeout (default behaviour for error)
            if (duration || (duration === undefined && level != 'error')) {
                setTimeout(dismiss, (duration ?? defaultDuration) * 1000);
            }

            notice.append(noticeMessage);
            root.append(notice);

            return { 
                el: notice.el,
                dismiss
            };
        }

        return {
            el: root.el,
            reinjectElement: handleInjection,
            info:  (/** @type {FactoryContent} */ content, duration) => notify({ content, level: 'info',  duration }),
            warn:  (/** @type {FactoryContent} */ content, duration) => notify({ content, level: 'warn',  duration }),
            error: (/** @type {FactoryContent} */ content, duration) => notify({ content, level: 'error', duration }),
        };
    }

    function makeModal({/** @type {FactoryContent} */ content, headerContent = /** @type {FactoryContent} */ ('Attention'), closeButtonContent = /** @type {FactoryContent} */ ('Close'), submitButtonContent = /** @type {FactoryContent} */ (null), submitButtonCallback = null, parentSelector = '#app' } = {}) {
        // submitButtonCallback can return false to prevent closing the modal
        const root = createElement('div', { id: 'nhcb-modal', className: 'nhcb-modal-overlay' });

        const modalContainer = createElement('div', { className: 'nhcb-modal-container' });

        if (headerContent) {
            modalContainer.append(createElement('h2', { className: 'nhcb-modal-header' }, ...toArray(headerContent)));
        }
        
        if (content) {
            modalContainer.append(...toArray(content));
        }

        const modalButtons = createElement('div', { className: 'nhcb-modal-buttons' });

        if (closeButtonContent) {
            const closeButton = createButton({ content: closeButtonContent, onClick: () => root.el.remove() });
            modalButtons.append(closeButton);
        }

        if (submitButtonContent) {
            const submitButton = createButton({ content: submitButtonContent, buttonStyle: 'primary', onClick: () => {
                if (submitButtonCallback && submitButtonCallback() !== false) {
                    closeModal();
                }
            }});
            modalButtons.append(submitButton);
        }

        function closeModal() {
            root.el.remove();
        }

        modalContainer.append(modalButtons);
        root.append(modalContainer);

        injector.injectElement(() => root, parentSelector, '#nhcb-modal');

        return closeModal;
    }

    function createGalleryFromData(/** @type {FavoriteData} */ galleryData, { altSourceIndex = 0, forbidAltSource = false, forceAltSource = false, forbidAltCover = false, forceAltCover = false , elementProperties = {} } = {}) {
        // supports FavoriteData or GalleryData but type hinting was being a bitch so marked it as FavoriteData

        const useAltSource = !forbidAltSource && (forceAltSource || galleryData?.alt_source_action == 'force') && galleryData?.alt_sources?.[altSourceIndex];
        const useAltCover = !forbidAltCover && (forceAltCover || true) && galleryData?.alt_cover; // force is default

        const link = getLink();
        const {thumbnail, thumbnail_width, thumbnail_height} = getThumbnailData();

        const gallery = createElement('div', {
            baseClassName: `gallery ${getLanguageClass()}`,
            ...elementProperties
        });

        const cover = createElement('a', { 
            className: 'cover',
            href: link,
            style: `padding: 0px 0px ${(thumbnail_height / thumbnail_width) * 100}%`
        });

        const img = createElement('img', {
            className: 'lazyload',
            loading: 'lazy',
            alt: galleryData.english_title,
            src: thumbnail
        });

        const caption = createElement('div', {
            className: 'caption',
            textContent: galleryData.english_title
        });

        cover.append(img, caption);
        if (useAltSource) {
            cover.append(createAltSourceBadge({ sourceName: galleryData.alt_sources[altSourceIndex].name }));
        }
        if (galleryData.gallery_is_404) {
            cover.append(createElement('div', { className: 'nhcb-404-badge'}, '404'));
        }
        gallery.append(cover);

        function getLink() {
            if (useAltSource) {
                return galleryData.alt_sources[altSourceIndex].link;
            }
            return galleryIdToPath(galleryData.id);
        }
        function getThumbnailData() {
            if (useAltCover) {
                return {
                    thumbnail: galleryData.alt_cover.thumbnail,
                    thumbnail_width: galleryData.alt_cover.thumbnail_width,
                    thumbnail_height: galleryData.alt_cover.thumbnail_height
                }
            }
            if (useAltSource) {
                return {
                    thumbnail: galleryData.alt_sources[altSourceIndex].thumbnail,
                    thumbnail_width: galleryData.alt_sources[altSourceIndex].thumbnail_width,
                    thumbnail_height: galleryData.alt_sources[altSourceIndex].thumbnail_height
                }
            }
            return {
                thumbnail: formatMediaServer(galleryData.thumbnail),
                thumbnail_width: galleryData.thumbnail_width,
                thumbnail_height: galleryData.thumbnail_height
            }
        }
        function getLanguageClass() {
            if (galleryData.tag_ids.includes(DEFINITIONS.COMMON_TAG_IDS.ENLGISH)) {
                return 'lang-gb';
            }
            else if (galleryData.tag_ids.includes(DEFINITIONS.COMMON_TAG_IDS.JAPANESE)) {
                return 'lang-jp';
            }
            else if (galleryData.tag_ids.includes(DEFINITIONS.COMMON_TAG_IDS.CHINESE)) {
                return 'lang-cn';
            }
            return 'lang-gb';
        }

        return gallery;
    }

    function createCustomSearchInput({ debounceMs = 200, elementProperties = {} } = {}) {
        const options = /** @type {{autoCompletion: string, start: int, end: int, root: FactoryRoot, complete: bool?, cursorNudge: int?, executeGoto: bool?}[]} */ ([]);
        let highlightedIndex = -1;
        const highlightClass = 'selected';
        let debounceTimer = null;
        const taskSearch = createAbortableTask(handleTaskSearch);

        // filter constants
        const OPERATORS = [
            ['<=', (a, b) => a <= b],
            ['>=', (a, b) => a >= b],
            ['<',  (a, b) => a < b],
            ['>',  (a, b) => a > b],
            ['=',  (a, b) => a === b],
            ['',   (a, b) => a === b],
        ];
        const DATE_UNIT_SETTERS = {
            d: (date, n) => date.setDate(date.getDate() - n),
            m: (date, n) => date.setMonth(date.getMonth() - n),
            y: (date, n) => date.setFullYear(date.getFullYear() - n),
        };
        // filter helper for >,>=,<,<=,=
        function parseRelationalOperator(str) {
            for (const [token, comparator] of OPERATORS) {
                if (str.startsWith(token)) {
                    return [comparator, str.slice(token.length)];
                }
            }
            return [() => false, str];
        }        
        // basically this holds all the info for non-tag filters
        // filter.value is compared against SearchTerm.value and surrounding quotes are automatically removed from filter.value when comparing
        // filter.label is used to overide filter.value as the example text presented as an option
        // the example text is built from the filter.key and filter.label/value
        // filter.cursorNudge is used to offset the cursor from the end of the completetion for cases where you want it to be inside of surrounding quotes eg: `title:"I"` instead of `title:""I`
        // filter.options is used define completion options for the SearchTerm.value for a given key
        // filter.options.value/label/description have the same behavior as described before
        // filter.options.complete is used to mark a completion as a full completion rather than partial, this appends a space to the end of the completetion `label:"example"I` => `label:"example" I`
        // filter.compileFilter takes in a SearchTerm.value and returns a filter function which takes in GalleryData or something similar and returns a boolean. Any SearchTerm without a key defaults to 'title'
        // probably a better way to organize this as this and arguably gives a bit too much authority to this single component, but it works and is otherwise unobtrusive
        /** @type {Object.<string, {value: string, label: string?, description: string, cursorNudge: int?, options: {value: string, label: string?, description: string, complete: boolean?}[]?, compileFilter: (value: string) => SearchFilter}>} */
        const filterData = {
            title: {
                value: '""',
                label: '"..."',
                description: 'Filter by title',
                cursorNudge: -1,
                compileFilter: (value) => {
                    const valueLower = value.toLowerCase();
                    return (galleryData) => galleryData?.english_title.toLowerCase().includes(value);
                }
            },
            label: {
                value: '""',
                label: '"..."',
                description: 'Filter by labels',
                cursorNudge: -1,
                options: [
                    {
                        value: '"none"',
                        description: 'Has no labels',
                        complete: true,
                    },
                    ...[...settingsStore.labels.value].map(galleryLabel => ({
                        value: `"${galleryLabel.toLowerCase()}"`,
                        label:`"${galleryLabel}"`,
                        description: `Has label "${galleryLabel}"`,
                        complete: true,
                    }))
                ],
                compileFilter: (value) => {
                    const valueLower = value.toLowerCase();
                    return value === 'none' ? 
                        (galleryData) => (galleryData && (galleryData.labels == null || galleryData.labels.length === 0)) :
                        (galleryData) => galleryData?.labels?.find((label) => label.toLowerCase() === valueLower) != null;
                }
            },
            pages: {
                value: '',
                label: 'N',
                description: 'Filter by page count',
                options: [
                    {
                        value: '>',
                        label: '>N',
                        description: 'Greater than N pages'
                    },
                    {
                        value: '>=',
                        label: '>=N',
                        description: 'Greater than or equal to N pages'
                    },
                    {
                        value: '<',
                        label: '<N',
                        description: 'Less than N pages'
                    },
                    {
                        value: 'pages:<=',
                        label: 'pages:<=N',
                        description: 'Less than or equal to N pages'
                    },
                    {
                        value: '=',
                        label: '=N',
                        description: 'Exactly N pages'
                    },
                ],
                compileFilter: (value) => {
                    const [compare, rest] = parseRelationalOperator(value);
                    const pageCount = Number(rest);
                    return (galleryData) => compare(galleryData?.num_pages, pageCount);
                }
            },
            // yea so I completely forgot that upload_date is not part of the basic gallery info and only the detailed gallery info
            // this means that nothing currently stored (as of v6-pre 9/8/26) has the timestamp upload_date
            // the only solution would be to update data store which would involve fetching each individual gallery, which would take 3-6 minutes per 100 galleries
            // for now, its just going to not be included
            /*
            uploaded: {
                value: '',
                label: 'Nd',
                description: 'Filter by upload date',
                options: [
                    {
                        value: '>7d',
                        description: 'Uploaded more than 7 days ago'
                    },
                    {
                        value: '>=7d',
                        description: 'Uploaded at least 7 days ago'
                    },
                    {
                        value: '<7d',
                        description: 'Uploaded less than 7 days ago'
                    },
                    {
                        value: '<=7d',
                        description: 'Uploaded within last 7 days'
                    },
                    {
                        value: '>7m',
                        description: 'Uploaded more than 7 months ago'
                    },
                    {
                        value: '>=7m',
                        description: 'Uploaded at least 7 months ago'
                    },
                    {
                        value: '<7m',
                        description: 'Uploaded less than 7 months ago'
                    },
                    {
                        value: '<=7m',
                        description: 'Uploaded within last 7 months'
                    },
                    {
                        value: '>7y',
                        description: 'Uploaded more than 7 years ago'
                    },
                    {
                        value: '>=7y',
                        description: 'Uploaded at least 7 years ago'
                    },
                    {
                        value: '<7y',
                        description: 'Uploaded less than 7 years ago'
                    },
                    {
                        value: '<=7y',
                        description: 'Uploaded within last 7 years'
                    },
                ],
                compileFilter: (termValue) => {
                    const [compare, rest] = parseRelationalOperator(termValue);
                    const match = /^(\d+(?:\.\d+)?)\s*([dmy])$/i.exec(rest);
                    if (!match) {
                        return () => false;
                    }

                    const [, amount, unit] = match;
                    const cutoffDate = new Date();
                    DATE_UNIT_SETTERS[unit.toLowerCase()](cutoffDate, Number(amount));
                    const cutoff = Math.floor(cutoffDate.getTime() / 1000);

                    return (galleryData) => compare(cutoff, galleryData?.upload_date);
                }
            },
            */
            added: {
                value: '',
                label: 'Nd',
                description: 'Filter by date favorited/marked read later',
                options: [
                    {
                        value: '>7d',
                        description: 'Added more than 7 days ago'
                    },
                    {
                        value: '>=7d',
                        description: 'Added at least 7 days ago'
                    },
                    {
                        value: '<7d',
                        description: 'Added less than 7 days ago'
                    },
                    {
                        value: '<=7d',
                        description: 'Added within last 7 days'
                    },
                    {
                        value: '>7m',
                        description: 'Added more than 7 months ago'
                    },
                    {
                        value: '>=7m',
                        description: 'Added at least 7 months ago'
                    },
                    {
                        value: '<7m',
                        description: 'Added less than 7 months ago'
                    },
                    {
                        value: '<=7m',
                        description: 'Added within last 7 months'
                    },
                    {
                        value: '>7y',
                        description: 'Added more than 7 years ago'
                    },
                    {
                        value: '>=7y',
                        description: 'Added at least 7 years ago'
                    },
                    {
                        value: '<7y',
                        description: 'Added less than 7 years ago'
                    },
                    {
                        value: '<=7y',
                        description: 'Added within last 7 years'
                    },
                ],
                compileFilter: (termValue) => {
                    const [compare, rest] = parseRelationalOperator(termValue);
                    const match = /^(\d+(?:\.\d+)?)\s*([dmy])$/i.exec(rest);
                    if (!match) {
                        return () => false;
                    }

                    const [, amount, unit] = match;
                    const cutoffDate = new Date();
                    DATE_UNIT_SETTERS[unit.toLowerCase()](cutoffDate, Number(amount));
                    const cutoff = Math.floor(cutoffDate.getTime() / 1000);

                    return (galleryData) => compare(cutoff, galleryData?.favorite_at ?? galleryData?.added_at);
                }
            },
            rating: {
                value: '',
                label: 'N',
                description: 'Filter by rating',
                options: [
                    {
                        value: '>',
                        label: '>N',
                        description: 'Rating greater than N'
                    },
                    {
                        value: '>=',
                        label: '>N',
                        description: 'Rating greater than or equal to N'
                    },
                    {
                        value: '<',
                        label: '<N',
                        description: 'Rating less than N'
                    },
                    {
                        value: '<=',
                        label: '<=N',
                        description: 'Rating less than or equal to N'
                    },
                    {
                        value: '=',
                        label: '=N',
                        description: 'Rating equal to N'
                    },
                ],
                compileFilter: (value) => {
                    const [compare, rest] = parseRelationalOperator(value);
                    const rating = settingsStore.useTenPointRating.value ? Number(rest) : Number(rest) * 2;
                    return (galleryData) => compare(galleryData?.rating ?? 0, rating);
                }
            },
            read: {
                value: '""',
                label: '"..."',
                description: 'Filter by read status',
                cursorNudge: -1,
                options: [
                    {
                        value: '"none"',
                        description: 'Has no read status',
                        complete: true,
                    },
                    {
                        value: '"read"',
                        description: 'Has read status',
                        complete: true,
                    },
                    {
                        value: '"liked"',
                        description: 'Has liked status',
                        complete: true,
                    },
                    {
                        value: '"passed"',
                        description: 'Has passed status',
                        complete: true,
                    },
                ],
                compileFilter: (value) => {
                    const valueLower = value.toLowerCase();
                    return (galleryData) => getGalleryReadStatus(galleryIdToPath(galleryData?.id ?? 0))[0] === valueLower;
                }
            },
            /* decided against this
            'show404s': {
                value: '""',
                label: '"..."',
                description: 'Filter by 404',
                cursorNudge: -1,
                options: [
                    {
                        value: '"yes"',
                        description: 'Include 404 galleries (default)',
                        complete: true,
                    },
                    {
                        value: '"no"',
                        description: 'Exclude 404 galleries',
                        complete: true,
                    },
                    {
                        value: '"only"',
                        description: 'Only show 404 galleries',
                        complete: true,
                    },
                    {
                        value: '"raw"',
                        description: 'Only show 404 galleries with original data',
                        complete: true,
                    },
                ],
                compileFilter: (value) => {
                    const valueLower = value.toLowerCase();
                    switch (valueLower) {
                        case 'yes':
                            return () => true;
                        case 'no':
                            return (galleryData) => !galleryData?.gallery_is_404;
                        case 'only':
                            return (galleryData) => galleryData?.gallery_is_404;
                        case 'raw':
                            return (galleryData) => galleryData?.gallery_is_404 === ???; // how do you handle this without turining it into a mountain of spaghetti
                        default:
                            return () => false;
                    }
                    return (galleryData) => galleryData?.gallery_is_404;
                }
            },
            */
            priority: {
                value: '""',
                label: '"..."',
                description: 'Filter by read priority for read later',
                cursorNudge: -1,
                options: [
                    {
                        value: '"any"',
                        description: 'Has any priority (is read later)',
                        complete: true,
                    },
                    {
                        value: '"priority"',
                        description: 'Has priority "priority"',
                        complete: true,
                    },
                    {
                        value: '"highest"',
                        description: 'Has priority "highest"',
                        complete: true,
                    },
                    {
                        value: '"very high"',
                        description: 'Has priority "very high"',
                        complete: true,
                    },
                    {
                        value: '"high"',
                        description: 'Has priority "high"',
                        complete: true,
                    },
                    {
                        value: '"default"',
                        description: 'Has priority "default"',
                        complete: true,
                    },
                    {
                        value: '"low"',
                        description: 'Has priority "low"',
                        complete: true,
                    },
                    {
                        value: '"very low"',
                        description: 'Has priority "very low"',
                        complete: true,
                    },
                ],
                compileFilter: (value) => {
                    const valueLower = value.toLowerCase();

                    if (valueLower === 'any') {
                        return (galleryData) => galleryData.favorite_at > 0 ? 
                            dataStore.readLater.value.get(galleryIdToPath(galleryData.id))?.read_priority != null : // hacky workaround for favorites
                            galleryData?.read_priority != null;
                    }

                    const priority = DEFAULTS.PRIORITY_DROPDOWN_OPTIONS.find(([valueStr, label]) => valueLower === label.toLowerCase());
                    const priorityValue = priority ? Number(priority[0]) : null;
                    
                    return (galleryData) => galleryData.favorite_at > 0 ? 
                        priorityValue === dataStore.readLater.value.get(galleryIdToPath(galleryData.id))?.read_priority : // hacky workaround for favorites
                        priorityValue === galleryData?.read_priority;
                }
            },
            favorites: {
                value: '',
                label: 'N',
                description: 'Filter number of favorites',
                options: [
                    {
                        value: '>',
                        label: '>N',
                        description: 'Greater than N favorites'
                    },
                    {
                        value: '>=',
                        label: '>N',
                        description: 'Greater than or equal to N favorites'
                    },
                    {
                        value: '<',
                        label: '<N',
                        description: 'Less than N favorites'
                    },
                    {
                        value: '<=',
                        label: '<=N',
                        description: 'Less than or equal to  N favorites'
                    },
                    {
                        value: '=',
                        label: '=N',
                        description: 'Exactly N favorites'
                    },
                ],
                compileFilter: (value) => {
                    const [compare, rest] = parseRelationalOperator(value);
                    const favoriteCount = Number(rest);
                    return (galleryData) => compare(galleryData?.num_favorites, favoriteCount);
                }
            },
        }

        const root = createElement('div', {
            baseClassName: 'nhcb-custom-search',
            ...elementProperties
        });
        const label = createElement('label', {}, 'Custom Search');
        const tooltip = createTooltip({ content: 'Search for galleries in your favorites.<br><br>There are a few differences from the normal search aside from the new filter options.<br><br>When searching for tags you have to search using the full tag (eg tag:"tag name") otherwise it won\'t work. This is because tag names are not saved in the data to conserve storage.<br><br>This also means that searching something like "example" will only search the title.<br><br>Also, you cannot search by upload date. This is because that information is not saved due to an oversight with the differences of data you get from different API request types. (Sorting by upload date is done with a workaround that using gallery ids)', width: '320px' })
        const searchInput = createInput({
            placeholder: 'Search...',
            initialValue: pageData.searchParams.get('q') ?? '',
            elementProperties: {
                autocomplete: 'off',
                onfocus: scheduleSearch,
                oninput: scheduleSearch,
                onblur: closeOptionsDisplay,
                onkeydown: searchInputOnKeyDown
            }
        });
        const optionsDisplay = createElement('ul', {
            className: 'nhcb-custom-search-options',
            hidden: true,
            onmousedown: (e) => e.preventDefault(), // keep focus on the input so an option's click fires before blur
        });
        const searchButton = createButton({ content: createIcon('search', { iconStyle: 'none' }), buttonStyle: ['primary', 'square'], onClick: executeGoto, elementProperties: { className: 'nhcb-custom-search-button' } });

        const getQuery = () => searchInput.value;
        const getCaretPos = () => searchInput.el.selectionStart;        

        function scheduleSearch() {
            clearTimeout(debounceTimer);
            debounceTimer = setTimeout(() => {
                if (document.activeElement !== searchInput.el) {
                    return;
                }
                search();
                openOptionsDisplay();
            }, debounceMs);
        }

        function search() {
            taskSearch.abort();
            taskSearch.run();
        }

        function clearSuggestions() {
            options.length = 0;
            optionsDisplay.replaceChildren();
        }
        function addSuggestion(/** @type {SearchTerm?} */ searchTerm, autoCompletion, label, description, { tagType, completionNegated, complete, cursorNudge, executeGoto } = {}) {
            const index = options.length;
            const root = createElement('li', { className: 'nhcb-custom-search-option' }, 
                ...(tagType ? [createSpan(tagType, { className: `nhcb-custom-search-tag-type nhcb-tag-type-${tagType}` })] : []),
                createSpan(label, { className: 'nhcb-custom-search-option-label' }),
                createSpan(description, { className: 'nhcb-custom-search-option-description' })
            );
            root.el.addEventListener('click', () => selectOption(index));
            const negated = completionNegated ?? searchTerm?.negated ?? false;

            options.push({ 
                autoCompletion: (negated ? '-' : '') + autoCompletion,
                start: searchTerm?.start ?? getCaretPos(),
                end: searchTerm?.end ?? getCaretPos(),
                root,
                complete,
                cursorNudge,
                executeGoto
            });
            optionsDisplay.append(root);

            return index;
        }        

        function suggestExecuteSearch() {
            addSuggestion(null, '', `Search for: ${getQuery()}`, '', { executeGoto: true });
        }
        function suggestTagTypes(/** @type {SearchTerm?} */ activeTerm) {
            const valueLower = activeTerm?.value.toLowerCase() ?? '';
            const matchingTypes = TAG_TYPES.values().filter((tagType) => tagType.startsWith(valueLower));
            matchingTypes.forEach((type) => {
                addSuggestion(activeTerm, `${type}:`, `${type}:...`, `Filter by ${type}`);
            })
        }
        function suggestFilter(/** @type {SearchTerm?} */ activeTerm) {
            const valueLower = activeTerm?.value.toLowerCase() ?? '';
            const matchingFilters = Object.keys(filterData).filter((filterName) => filterName.startsWith(valueLower));
            matchingFilters.forEach((filter) => {
                const data = filterData[filter];
                if (data) {
                    const key = `${filter}:`;
                    const value = data.value;
                    const label = data.label ?? value;
                    addSuggestion(activeTerm, key + value, key + label, data.description, { cursorNudge: data.cursorNudge });
                }
            })
        }
        function suggestFilterOptions(/** @type {SearchTerm} */ activeTerm) {
            if (!activeTerm.key) {
                return;
            }
            
            const filter = activeTerm.key.toLowerCase();
            const valueLower = activeTerm.value.toLowerCase();
            const data = filterData[filter];
            if (data && data.options) {
                // in filter, if first char is `"` then the surrrounding quotes are removed (prevented matching since SearchTerm.value cannot contain a quote, they are not included)
                const QUOTE = 34;
                const matchingOptions = data.options.filter((filterOption) => (filterOption.value.charCodeAt(0) === QUOTE ? filterOption.value.slice(1,-1) : filterOption.value).startsWith(valueLower));
                matchingOptions.forEach(filterOption => {
                    const key = `${filter}:`;
                    const value = filterOption.value;
                    const label = filterOption.label ?? value;
                    addSuggestion(activeTerm, key + value, key + label, filterOption.description, { complete: filterOption.complete ?? false });
                });
            }
        }
        function suggestTags(/** @type {SearchTerm?} */ activeTerm, /** @type {TagData[]} */ matchingTags) {
            matchingTags.forEach((tagData) => {
                addSuggestion(activeTerm, `${tagData.type}:"${tagData.name}"`, tagData.name, tagData.description ?? '', { tagType: tagData.type, complete: true });
            });
        }
        function suggestIncludeExclude(/** @type {SearchTerm} */ activeTerm) {
            // suggest remove and include/exclude (negate based on context)
            if (!activeTerm.key && !activeTerm.value) {
                return;
            }
            const currentSubString = searchInput.value.substring(activeTerm.start, activeTerm.end);
            if (activeTerm.negated) {
                const baseTerm = currentSubString.substring(1); // remove leading '-'
                addSuggestion(activeTerm, baseTerm,  '+ Include: '+ baseTerm, 'Include results with this term.', { complete: !activeTerm.open }); 
            } else {
                addSuggestion(activeTerm, currentSubString,  '- Exclude: '+ currentSubString, 'Exclude results with this term.', { completionNegated: true, complete: !activeTerm.open });
            }
            // suggest removal
            addSuggestion(activeTerm, '',  '\u00D7 Remove: ' + currentSubString, 'Remove this term from search.');
        }
        async function handleTaskSearch({ signal, defer }) {
            // parse search terms
            const { terms, activeTerm, activeTermIndex, caretIn } = extractSearchTermsWithCaret(getQuery().toLowerCase(), getCaretPos());

            
            clearSuggestions();

            if (terms.length > 0) {
                suggestExecuteSearch();
            }
            if (activeTerm && activeTerm.colon >= 0) {
                suggestFilterOptions(activeTerm);
            } else {
                suggestFilter(activeTerm);
                suggestTagTypes(activeTerm);
            }

            if (!activeTerm) {
                return;
            }
            
            signal.throwIfAborted();
            // if no key or key exists and is tagType
            if (!activeTerm.key || TAG_TYPES.has(activeTerm.key.toLowerCase())) {
                const data = await apiEndpoints.tagSearch.fetch(activeTerm.key, activeTerm.value); 
                signal.throwIfAborted();

                if (data) {
                    cachedApiData.tags.addData(...data);
                    const normalizedData = data.map(tagData => cachedApiData.tags.get(tagData.url));
                    suggestTags(activeTerm, normalizedData);
                }
            }            
            suggestIncludeExclude(activeTerm);
        }

        function openOptionsDisplay() {
            optionsDisplay.hidden = false;
            resetHighlight();
            highlightNext();
        }
        function closeOptionsDisplay() {
            optionsDisplay.hidden = true;
            clearTimeout(debounceTimer);
        }

        function selectOption(index) {
            const option = options[index];
            if (!option) {
                return;
            }
            if (option.executeGoto) {
                executeGoto();
                return;
            }

            const startSubString = searchInput.value.substring(0, option.start);
            const endSubString = searchInput.value.substring(option.end);
            const cursorPos = startSubString.length + option.autoCompletion.length + (option.cursorNudge ?? 0) + (option.complete ? 1 : 0);
            searchInput.value = startSubString + option.autoCompletion + (endSubString.charAt(0) !== ' ' && option.complete ? ' ' : '') + endSubString;
            searchInput.el.setSelectionRange(cursorPos, cursorPos);

            clearSuggestions();
            scheduleSearch();
        }
        
        // highlight via keyboard for selection
        function selectHighlightedOption() {
            selectOption(highlightedIndex);
        }
        function resetHighlight() {
            options[highlightedIndex]?.root.classList.remove(highlightClass);
            highlightedIndex = -1;
        }
        function highlightIndex(index) {
            highlightedIndex = index;
            options[index]?.root.classList.add(highlightClass);
            options[index]?.root.el.scrollIntoView({ block: 'nearest' });
        }
        function highlightNext(forwards = true) {
            if (options.length <= 0) {
                return;
            }
            const totalOptions = options.length;
            
            let i = highlightedIndex;
            const incrementAmount = forwards ? 1 : -1;
            i += incrementAmount;
            i = i >= totalOptions ? i - totalOptions : (i < 0 ? i + totalOptions : i);
            resetHighlight();
            highlightIndex(i);
        }
        function searchInputOnKeyDown(e) {
            if (optionsDisplay.hidden && (e.key === 'ArrowDown' || e.key === 'ArrowUp')) {
                openOptionsDisplay();
                return;
            }
            switch (e.key) {
                case 'ArrowDown':
                    e.preventDefault();
                    highlightNext(true);
                    break;
                case 'ArrowUp':
                    e.preventDefault();
                    highlightNext(false);
                    break;
                case 'Tab':
                case 'Enter':
                    e.preventDefault();
                    selectHighlightedOption();
                    break;
                case 'Escape':
                    closeOptionsDisplay();
                    break;
                case 'ArrowLeft':
                case 'ArrowRight':
                    scheduleSearch();
                    break;

            }
        }

        function parseTagFilterDataFromParams() {
            const tagsParam = pageData.searchParams.get('tagFilters') ?? '';
            /** @type {[type: string, name: string, id: int][]} */
            let parsedData;
            try {
                parsedData = JSON.parse(tagsParam);
            } catch {
                parsedData = [];
            }
            return parsedData.filter(([ type, name, id ]) => type && name && Number.isFinite(id));
        }
        function compileFilters() {
            const terms = extractSearchTerms(getQuery());
            const tagIds = parseTagFilterDataFromParams().map(([type, name, id]) => id);

            const createTagFilter = (id) => id > 0 ? ((galleryData) => (galleryData && galleryData.tag_ids.includes(id))) : ((galleryData) => (galleryData && !galleryData.tag_ids.includes(id * -1)));
            const negateFilter = (filter, negated) => (filter && negated) ? (v) => !filter(v) : filter;
            const createFilter = (term) => TAG_TYPES.has(term.key) ? null : negateFilter(filterData[term.key ?? 'title'].compileFilter(term.value), term.negated);
            /** @type {SearchFilter[]} */
            const tagFilters = tagIds.map((id) =>  createTagFilter(id));
            /** @type {SearchFilter[]} */
            const otherFilters = terms.map(createFilter).filter((filter) => filter != null);

            return [...tagFilters, ...otherFilters];
        }
        async function executeGoto() {
            const query = getQuery();
            const terms = extractSearchTerms(query);
            const tagTerms = terms.filter(term => TAG_TYPES.has(term.key) && term.value.length > 0);
            const previousTagFilterData = parseTagFilterDataFromParams();
            const encodeToTagPath = (type, name) => `/${type}/${slugify(name)}/`;
            const lookup = new Map(previousTagFilterData.map(([type, name, encodedId]) => ([encodeToTagPath(type, slugify(name)), { type, name, id: Math.abs(encodedId) }])));
            const createTagFilterDataEntry = (type, name, id, negated) => ([type, name, id * (negated ? -1 : 1)]);

            /** @type {[tagFilterData: [type: string, name: string, id: int][], termsMissingIds: SearchTerm[]]} */
            const [tagFilterData, termsMissingIds] = tagTerms.reduce((result, term) => {
                const tagPath = encodeToTagPath(term.key, term.value);
                const tagData = cachedApiData.tags.get(tagPath);
                if (tagData) {
                    result[0].push(createTagFilterDataEntry(tagData.type, tagData.name, tagData.id, term.negated));
                } else {
                    // check exsisting param
                    const lookupData = lookup.get(encodeToTagPath(term.key, term.value));
                    if (lookupData) {
                        result[0].push(createTagFilterDataEntry(lookupData.type, lookupData.name, lookupData.id, term.negated));
                    }
                    // else nothing found, need api call
                    else {
                        result[1].push(term);
                    }
                }
                return result;
            }, [[],[]]);

            if (termsMissingIds.length > 0) {
                for (let i = 0; i < termsMissingIds.length; i++) {
                    const term = termsMissingIds[i];
                    const tagPath = encodeToTagPath(term.key, term.value);

                    let tagData = cachedApiData.tags.get(tagPath);

                    // first check if tagData was found in previous api call
                    if (tagData) {
                        tagFilterData.push(createTagFilterDataEntry(tagData.type, tagData.name, tagData.id, term.negated));
                        continue;
                    }

                    // make api call
                    const fetchData = await apiEndpoints.tagSearch.fetch(term.key, term.value);
                    if (!fetchData) {
                        continue;
                    }
                    // add fetch to cache
                    cachedApiData.tags.addData(...fetchData);
                        
                    // get tagData from cache
                    tagData = cachedApiData.tags.get(tagPath);
                    if (tagData) {
                        tagFilterData.push(createTagFilterDataEntry(tagData.type, tagData.name, tagData.id, term.negated));
                    }
                    // else if still nothing: oh well, ignore tag

                    // if not last loop, delay to prevent rate limit 
                    if (i < (termsMissingIds.length - 2)) {
                        const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
                        await sleep(34); 
                    }
                }
            }

            const searchUrl = buildUrl({ setParams: { ...(query && {q: query}), ...(tagFilterData.length > 0 && {tagFilters: JSON.stringify(tagFilterData)}) }, deleteParams: ['page', 'q', 'tagFilters'] });
            gotoPage(searchUrl);
        }

        root.addProperty('searchInputValue', () => searchInput.value, (v) => { searchInput.value = v; });
        root.clearSearch = () => {
            searchInput.value = '';
            scheduleSearch();
        };
        root.compileFilters = compileFilters;
        root.executeGoto = executeGoto;

        root.append(label, tooltip, searchInput, optionsDisplay, searchButton);

        return /** @type {FactoryRoot & {searchInputValue: string, clearSearch: () => void, compileFilters: () => SearchFilter[], executeGoto: () => void}} */ (root);
    }

    function createTagSearch({ onTagSelect = /** @type {(tagdata: TagData) => void} */ (null), hidden = false, elementProperties = {} } = {}) {
        const tagSearchDropdown = createSearchableDropdown({ placeholder: 'tag:"big ..."', onSearchChange: handleSearchChange, onSelect: handleTagSelect, disableFiltering: true, hidden, elementProperties });
        tagSearchDropdown.classList.add('nhcb-tag-search');
        
        const fetchAndPopulateTagsTask = createAbortableTask(handleTaskFetchAndPopulateTags);

        function clearOptions() {
            tagSearchDropdown.replaceOptions();
        }
        function handleSearchChange(input) {
            const query = parseValidString(input);

            if (!query) {
                clearOptions();
                return;
            }

            const terms = extractSearchTerms(query);
            if (!terms || terms.length == 0 || !terms[0].value) {
                clearOptions();
                return;
            }

            fetchAndPopulateTagsTask.abort();
            fetchAndPopulateTagsTask.run(terms[0].key, terms[0].value);
        }
        function handleTagSelect(selectedName) {
            const tagData = cachedApiData.tags.get(selectedName);
            onTagSelect?.(tagData);
            tagSearchDropdown.clearSearch();
        }

        async function handleTaskFetchAndPopulateTags({ signal, defer }, queryKey, queryValue) {
            const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
            await delay(200);
            signal.throwIfAborted();

            const data = await apiEndpoints.tagSearch.fetch(queryKey, queryValue);
            signal.throwIfAborted();

            if (data) {
                cachedApiData.tags.addData(...data);
                tagSearchDropdown.replaceOptions(data.map(data => data.url));
            } else {
                clearOptions();
            }
        }

        return tagSearchDropdown;
    }
    //#endregion

    //#region Badges
    function createSeenBadge() {
        return createElement('div', { className: 'nhcb-view-system-badge nhcb-seen-badge' }, createIcon('eye', { iconStyle: 'solid' }));
    }
    function createReadBadge() {
        return createElement('div', { className: 'nhcb-view-system-badge nhcb-read-badge' }, createIcon('book', { iconStyle: 'solid' } ));
    }
    function createLikedBadge() {
        return createElement('div', { className: 'nhcb-view-system-badge nhcb-liked-badge' }, createIcon('thumbs-up', { iconStyle: 'solid' } ));
    }
    function createPassedBadge() {
        return createElement('div', { className: 'nhcb-view-system-badge nhcb-passed-badge' }, createIcon('hand-paper', { iconStyle: 'solid' }));
    }
    function createReadLaterBadge() {
        return createElement('div', { className: 'nhcb-view-system-badge nhcb-read-later-badge' }, createIcon('clock', { iconStyle: 'solid' }));
    }
    function createFavoriteBadge(rating = 0) {
        const root = createElement('div', { className: 'nhcb-favorite-badge' }, createIcon('heart', { iconStyle: 'solid' }));
        
        if (settingsStore.showRatingsOnCover.value && rating != null && rating > 0) {
            const rating10Point = settingsStore.useTenPointRating.value;
            const ratingSpan = createElement('span', { className: 'nhcb-favorite-rating' }, rating10Point ? rating : rating * .5);
            root.append(ratingSpan);
        }

        return root;
    }
    function createAltSourceBadge({ sourceName = '', elementProperties = {} } = {}) {
        const root = createElement('div', {
            baseClassName: 'nhcb-alt-source-badge',
            innerHTML: 'Alt Source' + (sourceName ? '<br>' : ''),
            ...elementProperties
        });
        if (sourceName) {
            const nameSpan = createElement('span', {
                className: 'nhcb-alt-source-name-span',
                textContent: sourceName
            });
            root.append(nameSpan);
        }

        return root;
    }
    function createContentWarningBadge(galleryTags) {
        const tagSet = new Set(toArray(galleryTags));

        const rules = settingsStore.contentWarningConfig.value;
        const applicableRules = rules.filter(rule => rule.logic.every(tagRule => tagRule > 0 ? tagSet.has(tagRule) : !tagSet.has(-tagRule)));

        const createWarning = (label) => createElement('span', {}, label)
        const warnings = applicableRules.map(rules => createWarning(rules.label));

        return createElement('div', { className: 'nhcb-content-warning-badge', hidden: warnings.length == 0 }, ...warnings);
    }
    function createInfoBadgeBase(content) {
        const contentArray = toArray(content);
        return createElement('div', { className: 'nhcb-info-badge', hidden: contentArray.length === 0 }, ...contentArray);
    }
    function createPageCountInfoBadge(/** @type {GalleryData} */ galleryData, /** @type {Set<int>} */ tagSet) {
        let adjustedCount = galleryData.num_pages;
        if (settingsStore.adjustPageCountForMultiLang.value) {
            let languageCount = 0;
            DEFINITIONS.LANGUAGE_TAGS.forEach(tagId => {
                languageCount += tagSet.has(tagId) ? 1 : 0;
            })
            if (languageCount > 1) {
                adjustedCount = Math.ceil(adjustedCount / languageCount);
            }
        }

        const root = createElement('div', { className: 'nhcb-gallery-page-count' }, `${adjustedCount} pages`);

        if (settingsStore.enablePageCountBadgeColorIndicator.value) {
            const TIERS = [
                { min: 1,   max: 7,    color: [231, 58, 58]  }, // red
                { min: 8,   max: 16,   color: [255, 149, 37] }, // orange
                { min: 17,  max: 34,   color: [230, 230, 230]}, // neutral
                { min: 35,  max: 74,   color: [74, 222, 128] }, // green
                { min: 75,  max: 150,  color: [27, 197, 249] }, // cyan
                { min: 151, max: 250,  color: [194, 118, 246]}, // violet
            ];
            // 0 = hard tiers, 0.5 = blend across the entire tier.
            // 0.3 means the outer 30% on each side of a tier blends, and the middle 40% stays same
            const blendCutoff = settingsStore.pageCountBadgeColorIndicatorBlendAmount.value * .5; // setting value is 0-1

            const mix = (color, mixColor, mixPercentage) => color.map((colorVal, i) => Math.round(colorVal + (mixColor[i] - colorVal) * mixPercentage));

            let i = TIERS.findIndex(t => adjustedCount <= t.max);
            if (i === -1) {
                i = TIERS.length - 1;
            }

            const tier = TIERS[i];
            const prevTier = TIERS[i - 1];
            const nextTier = TIERS[i + 1];
            const inverseLerp = (a, b, v) => (v - a) / (b - a);
            const positionInTier = clamp(inverseLerp(tier.min - 0.5, tier.max + 0.5, adjustedCount), 0, 1);

            let color = tier.color;
            if (prevTier && positionInTier < blendCutoff) {
                color = mix(prevTier.color, tier.color, inverseLerp(-blendCutoff, blendCutoff, positionInTier));
            } else if (nextTier && positionInTier > 1 - blendCutoff) {
                color = mix(tier.color, nextTier.color, inverseLerp(1-blendCutoff, 1+blendCutoff, positionInTier));
            }
            
            const lengthIndicator = createSpan('', { className: 'nhcb-gallery-page-count-indicator', elementProperties: { style: `background: rgba(${color.join(',')},.8);`} });
            root.append(lengthIndicator);
        }

        return root;
    }
    function createArtistsInfoBadge(/** @type {GalleryData} */ galleryData, /** @type {Set<int>} */ tagSet) {
        const applicableBadges = [];
        const titleLower = galleryData.english_title.toLowerCase();

        // anthology
        if (settingsStore.enableArtistInfoAnthology.value && (tagSet.has(DEFINITIONS.COMMON_TAG_IDS.GOUDOUSHI) || tagSet.has(DEFINITIONS.COMMON_TAG_IDS.ANTHOLOGY) || titleLower.includes('various') || /\[anthology\]/.test(titleLower))) {
            applicableBadges.push(createIcon('users'));
        }

        // browse later
        if (settingsStore.enableArtistInfoBrowseLater.value && galleryData.tag_ids.some(artistId => calculatedData.artistBrowseLater.has(artistId))) {
            applicableBadges.push(createIcon('clock'))
        }

        // liked artist
        if (settingsStore.enableArtistInfoTagSentiment.value && galleryData.tag_ids.some(artistId => calculatedData.artistTagSentiments.get(artistId)?.status === 'liked')) {
            applicableBadges.push(createIcon('thumbs-up'))
        }

        // dubious artist
        if (settingsStore.enableArtistInfoTagSentiment.value && galleryData.tag_ids.some(artistId => calculatedData.artistTagSentiments.get(artistId)?.status === 'dubious')) {
            applicableBadges.push(createIcon('question'))
        }

        // scorned artist
        if (settingsStore.enableArtistInfoTagSentiment.value && galleryData.tag_ids.some(artistId => calculatedData.artistTagSentiments.get(artistId)?.status === 'scorned')) {
            applicableBadges.push(createIcon('exclamation-triangle'))
        }        

        // compilation
        if (settingsStore.enableArtistInfoCompilation.value && (tagSet.has(DEFINITIONS.COMMON_TAG_IDS.COMPILATION) || (galleryData.num_pages > 30 && titleLower.includes('compilation')))) {
            applicableBadges.push(createIcon('archive'));
        }

        if (applicableBadges.length === 0) {
            return null;
        }
        const root = createElement('div', {
            baseClassName: 'nhcb-artists-badge',
          }, ...applicableBadges.reverse(), createIcon('paint-brush'));

        return root;
    }
    function createBadTranslationInfoBadge(/** @type {GalleryData} */ galleryData, /** @type {Set<int>} */ tagSet) {
        let conditionsMet = 0;
        let needMoreConditions = true;
        const minConditions = settingsStore.badTranslationMinConditions.value;

        const conditions = [
            {   // rough translation tag
                enabled: settingsStore.enableBadTranslationRoughTranslationTag.value,
                predicate: () => tagSet.has(DEFINITIONS.COMMON_TAG_IDS.ROUGH_TRANSLATION),
            },
            {   // machine translation tag
                enabled: settingsStore.enableBadTranslationMachineTranslationTag.value,
                predicate: () => tagSet.has(DEFINITIONS.COMMON_TAG_IDS.MACHINE_TRANSLATION),
            },
            {   // MTL title
                enabled: settingsStore.enableBadTranslationMtlTitle.value,
                predicate: () => galleryData.english_title.toLowerCase().includes('mtl'),
            },
            {   // ai translate title
                enabled: settingsStore.enableBadTranslationAiTranslateTitle.value,
                predicate: () => /ai.translat/i.test(galleryData.english_title),
            },
        ].filter(data => data.enabled);

        for (let i = 0; i < conditions.length; i++) {
            if (conditions[i].enabled && conditions[i].predicate()) {
                conditionsMet++;
                if (minConditions >= 0 && conditionsMet >= minConditions) {
                    needMoreConditions = false;
                    break;
                }
            }
        }
        if (needMoreConditions || (minConditions < 0 && conditionsMet === conditions.length)) {
            return null;
        }

        const root = createDiv({ 
            className: 'nhcb-bad-translation-badge',
        }, 'MTL', createIcon('language'));

        return root;
    }
    function createIncompleteInfoBadge(/** @type {GalleryData} */ galleryData, /** @type {Set<int>} */ tagSet) {
        const titleLower = galleryData.english_title.toLowerCase();
        // incomplete tag
        if (! (tagSet.has(DEFINITIONS.COMMON_TAG_IDS.INCOMPLETE)
            || galleryData.english_title.includes('WIP')// caps only
            || titleLower.includes('incomplete')
            || titleLower.includes('ongoing'))) {
            return null;
        }

        const icon = document.createElement('svg');
        const iconHtml = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 384 512" height="14px"><!--!Font Awesome Free v7.3.1 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2026 Fonticons, Inc.--><path fill="currentColor" d="M64 512c-29.8 0-54.8-20.4-61.9-48l61.9 0 0 48zm104 0l-56 0 0-48 56 0 0 48zm104 0l-56 0 0-48 56 0 0 48zm109.9-48c-7.1 27.6-32.1 48-61.9 48l0-48 61.9 0zM48 416l-48 0 0-48 48 0 0 48zm336 0l-48 0 0-48 48 0 0 48zM213.5 0c17 0 33.2 6.8 45.2 18.8L365.3 125.2c12 12 18.7 28.3 18.7 45.2L384 320 0 320 0 64C0 28.7 28.7 0 64 0L213.5 0zM208 152c0 13.3 10.7 24 24 24l93.5 0-117.5-117.5 0 93.5z"/></svg>`;
        const root = createDiv({ 
            className: 'nhcb-incomplete-badge',
        }, 'WIP');

        root.el.insertAdjacentHTML('beforeend', iconHtml);
            
        return root;
    }

    function createBrowsedBadge() {
        return createElement('div', { className: 'nhcb-browse-system-badge nhcb-browsed-badge' }, createIcon('book', { iconStyle: 'solid' }));
    }
    function createBrowseLaterBadge() {
        return createElement('div', { className: 'nhcb-browse-system-badge nhcb-browse-later-badge' }, createIcon('clock', { iconStyle: 'solid' }));
    }
    //#endregion

    //#region Gallery Buttons
    function createViewSystemButtons(forcedGalleryPath = null) {
        const readStatus = ['read', 'liked', 'passed'];

        const galleryPath = forcedGalleryPath ?? pageData.path;
        const initialStatus = getGalleryReadStatus(galleryPath)[0]; // only used for initialization
        let hasStatus = initialStatus !== 'none';
        let statusTarget = hasStatus ? initialStatus : 'read';
        let isSeen = dataStore.seenGalleries.value.has(pageData.path);
        let isReadLater = dataStore.readLater.value.has(pageData.path);
        const statusMenuAvailable = Object.fromEntries([...readStatus.map(status => [status, true]), ['seen', isSeen], ['notSeen', !isSeen]]);
        
        const root = createElement('div', {
            id: 'nhcb-view-system-buttons',
        });

        function createStatusContent(statusName, hasStatus) {
            const statusLabel = ` ${hasStatus ? '' : 'Mark '}${firstLetterUpper(statusName)}`;
            switch(statusName) {
                case 'passed':
                    return [createIcon('hand-paper', { iconStyle: hasStatus ? 'solid' : 'regular' }), statusLabel];
                case 'liked':
                    return [createIcon('thumbs-up', { iconStyle: hasStatus ? 'solid' : 'regular' }), statusLabel];
                case 'read':
                default:
                    return [createIcon(hasStatus ? 'book' : 'book-open'), statusLabel];
            }
        }

        const readStatusButton = createSplitButton({
            id: 'nhcb-read-status-edit',
            items: [
                ...readStatus.map(status => { 
                    return { key: status, className: `nhcb-read-status-${status}`, content: createStatusContent(status, false), onClick: () => setReadStatus(status) } 
                }),
                { key: 'seen', className: 'nhcb-seen-status', content: [createIcon('eye-slash', { iconStyle: 'regular' }), ' Unmark Seen'], onClick: () => toggleSeen() },
                { key: 'notSeen', className: 'nhcb-seen-status', content: [createIcon('eye', { iconStyle: 'regular' }), ' Mark Seen'], onClick: () => toggleSeen() },
            ],
            onClick: () => {
                if (hasStatus) {
                    removeReadStatus();
                } else {
                    setReadStatus(statusTarget);
                }
            },
        });

        const readLaterButton = createButton({
            buttonStyle: 'toggle', 
            content: [createIcon('clock', { iconStyle: 'regular' }), ' Read Later'], 
            altContent: [createIcon('clock', { iconStyle: 'solid' }), ' Edit'], 
            onClick: handleReadLaterClick
        });

        async function handleReadLaterClick() {
            if (!isReadLater) {
                await toggleReadLater(true);
            }
            showEditReadLaterModal(pageData.path, () => {
                isReadLater = false;
                updateDisplay();
            });
        }

        function removeReadStatus() {
            if (hasStatus) {
                const result = opSetGalleryReadStatus(galleryPath, 'none');
                if (result.ok) {
                    hasStatus = false;
                    updateDisplay();
                }
            }
        }
        function setReadStatus(status) {
            const result = opSetGalleryReadStatus(galleryPath, status);
            if (result.ok) {
                hasStatus = true;
                statusTarget = status;

                if (settingsStore.autoSeenIfRead.value === true) {
                    toggleSeen(true);
                }
                if (settingsStore.autoRemoveReadLaterIfRead.value === true) {
                    toggleReadLater(false);
                }

                updateDisplay();
            }
        }   

        function toggleSeen(forceIsSeen = null) {
            if (forceIsSeen != null && forceIsSeen == isSeen) {
                return;
            }
            dataStore.readGalleries.load();
                
            // determine operation using button state
            if (isSeen) {
                // mark unseen
                isSeen = false;
                dataStore.seenGalleries.value.delete(pageData.path);
                logger.storeUpdates.log(`Gallery ${pageData.path} removed from seen list.`);
                pruneSeenExclude();
                addSeenExclude(pageData.path);
            }
            else {
                // mark seen
                isSeen = true;
                dataStore.seenGalleries.value.add(pageData.path);
                logger.storeUpdates.log(`Gallery ${pageData.path} added to seen list.`);
                pruneSeenExclude();
            }
            
            dataStore.seenGalleries.save();
            updateDisplay();
            updateDisplay();
        }

        async function toggleReadLater(forceReadLater = null) {
            if (forceReadLater != null && forceReadLater == isReadLater) {
                return;
            }
            dataStore.readLater.load();
                
            // determine operation using button state
            if (isReadLater) {
                // remove from read later
                isReadLater = false;
                dataStore.readLater.value.delete(pageData.path);
                logger.storeUpdates.log(`Gallery ${pageData.path} removed from read later list.`);
            }
            else {
                // add to read later
                isReadLater = true;

                let galleryData = await getOrPullGalleryCacheData(pageData.path);
                // if data needed not in cache, pull data
                if (!galleryData) {
                    reportIssue('CANNOT_READ_LATER_API_FAIL', { galleryPath: pageData.path });
                    return;
                }

                const readLaterData = objectDeepCopy(galleryData);
                readLaterData.added_at = getUnixTimestamp();
                readLaterData.read_priority = DEFAULTS.PRIORITY;

                dataStore.readLater.value.set(pageData.path, readLaterData);
                logger.storeUpdates.log(`Gallery ${pageData.path} added to read later list.`);
            }
            
            dataStore.readLater.save();
            updateDisplay();
        }

        function updateDisplay() {
            readStatus.forEach(status => {
                statusMenuAvailable[status] = status !== statusTarget;
                root.classList.toggle(`nhcb-${status}`, status === statusTarget);
            });

            readStatusButton.classList.toggle('nhcb-seen', isSeen);
            statusMenuAvailable.seen = isSeen;
            statusMenuAvailable.notSeen = !isSeen;

            readStatusButton.classList.toggle('nhcb-has-status', hasStatus);
            readStatusButton.setAvailable(statusMenuAvailable);
            readStatusButton.replaceChildren(...createStatusContent(statusTarget, hasStatus));

            readLaterButton.showAltContent(isReadLater);
            readLaterButton.hidden = hasStatus && !isReadLater; 
            readLaterButton.classList.toggle('nhcb-is-read-later', isReadLater);
        }

        updateDisplay();

        root.append(readStatusButton, readLaterButton);

        return root;
    }

    function createTryAnotherSiteButton(galleryMediaId = null) {
        const root = createButton({ id: 'nhcb-try-another-site', content: 'Try Another Site', onClick: async () => {
            const modalContent = createElement('div', { className: 'nhcb-alt-site-suggestions'}, 'Awaiting API Data...');
            makeModal({ headerContent: 'Try Another Site', content: modalContent });

            let mediaId = galleryMediaId;
            if (!mediaId) {
                let galleryData = await getOrPullGalleryCacheData(pageData.path);
                mediaId = galleryData?.media_id;
            }


            if (mediaId) {
                modalContent.replaceChildren(
                    createLinkButton({content: 'Try E-Hentai', href: `https://e-hentai.org/?f_search=gid%3A${mediaId}`}),
                    createLinkButton({content: 'Try Sad Panda', href: `https://exhentai.org/?f_search=gid%3A${mediaId}`})
                );
            }
            else {
                modalContent.replaceChildren('API request failed. Try again later.');
            }
        }});

        return root;
    }
    //#endregion

    //#region Browse buttons
    function createAddTagSentimentsButton(forcedTagPath = null) {
        const statuses = ['liked', 'dubious', 'scorned'];

        const tagPath = forcedTagPath ?? pageData.path; 
        let hasSentiment = dataStore.tagSentiments.value.has(tagPath);
        let statusTarget = dataStore.tagSentiments.value.get(tagPath)?.status ?? statuses[0];

        const statusMenuAvailable = Object.fromEntries(statuses.map(status => [status, true]));

        function createStatusContent(statusName, hasStatus) {
            const statusLabel = ` ${hasSentiment ? '' : 'Mark '}${firstLetterUpper(statusName)}`;
            switch(statusName) {
                case 'liked':
                    return [createIcon('thumbs-up', { iconStyle: hasStatus ? 'solid' : 'regular' }), statusLabel];
                case 'dubious':
                    return [createIcon('question', { iconStyle: 'solid' }), statusLabel];
                case 'scorned':
                default:
                    return [createIcon('exclamation-triangle', { iconStyle: 'solid' }), statusLabel];
            }
        }

        const root = createSplitButton({
            id: 'nhcb-tag-sentiment-edit',
            items: statuses.map(status => { 
                return { key: status, className: `nhcb-tag-sentiment-edit-${status}`, content: createStatusContent(status, true), onClick: () => setSentiment(status) } 
            }),
            onClick: async () => {
                if (hasSentiment) {
                    removeSentiment();
                } else {
                    await setSentiment(statusTarget);
                }
            },
        });

        function removeSentiment() {
            if (hasSentiment) {
                hasSentiment = false;
                    
                dataStore.tagSentiments.load();
                dataStore.tagSentiments.value.delete(tagPath);
                dataStore.tagSentiments.save();

                logger.storeUpdates.log(`Tag ${tagPath} unmarked ${statusTarget}.`);
                updateDisplay();
            }
        }
        async function setSentiment(setimentStatus) {
            const result = await opSetTagSentiment(tagPath, setimentStatus);
            if (result.ok) {
                hasSentiment = true;
                statusTarget = setimentStatus;
                updateDisplay();
            } else {
                reportPatchFail(result);
            }
        }

        function updateDisplay() {
            statuses.forEach(status => {
                statusMenuAvailable[status] = status !== statusTarget;
                root.classList.toggle(`nhcb-${status}`, status === statusTarget);
            });
            root.classList.toggle('nhcb-has-status', hasSentiment);
            root.setAvailable(statusMenuAvailable);
            root.replaceChildren(...createStatusContent(statusTarget, hasSentiment));
        }

        updateDisplay();

        return root;
    }

    function createBrowseSystemButtons(forcedPageId = null) {
        const root = createElement('div', {
            id: 'nhcb-browse-system-buttons',
        });

        const pageId = forcedPageId ?? pageData.id;
        let isBrowsed = dataStore.browsedPages.value.has(pageId);
        let isBrowseLater = dataStore.browseLater.value.has(pageId);

        const browsedButton = createButton({
            buttonStyle: 'toggle',
            content: [createIcon('book-open'), ' Mark Browsed'],
            altContent: [createIcon('book'), ' Browsed'],
            onClick: () => toggleBrowsed(),
            elementProperties: { className: 'nhcb-browsed-button' },
        });
        const browseLaterButton = createButton({
            buttonStyle: 'toggle',
            content: [createIcon('clock', { iconStyle: 'regular' }), ' Browse Later'],
            altContent: [createIcon('clock', { iconStyle: 'solid' }), ' Edit'],
            onClick: handleBrowseLaterClick,
            elementProperties: { className: 'nhcb-browse-later-button' },
        });

        async function handleBrowseLaterClick() {
            if (!isBrowseLater) {
                await toggleBrowseLater(true);
            }
            showEditBrowseLaterModal(pageId, handleBrowseLaterModalRemove);
        }
        function handleBrowseLaterModalRemove() {
            isBrowseLater = false;
            updateVisibility();
        }

        function toggleBrowsed(forceIsBrowsed = null) {
            if (forceIsBrowsed != null && forceIsBrowsed == isBrowsed) {
                return;
            }
            dataStore.browsedPages.load();
                
            if (isBrowsed) {
                // mark not browsed
                isBrowsed = false;
                dataStore.browsedPages.value.delete(pageId);
                logger.storeUpdates.log(`Page ${pageId} removed from browsed list.`);
            }
            else {
                // mark browsed
                isBrowsed = true;
                dataStore.browsedPages.value.set(pageId, getUnixTimestamp());
                logger.storeUpdates.log(`Page ${pageId} added to browsed list.`);
            }
            
            dataStore.browsedPages.save();
            if (isBrowsed) {
                if (settingsStore.autoRemoveBrowseLaterIfBrowsed.value === true) {
                    toggleBrowseLater(false);
                }
            }
            updateVisibility();
        }

        async function toggleBrowseLater(forceBrowseLater = null) {
            if (forceBrowseLater != null && forceBrowseLater == isBrowseLater) {
                return;
            }
                
             // determine operation using button state
            if (isBrowseLater) {
                // remove browse later
                isBrowseLater = false;
                dataStore.browseLater.load();
                dataStore.browseLater.value.delete(pageId);
                dataStore.browseLater.save();

                logger.storeUpdates.log(`Page ${pageId} removed browse later.`);
            }
            else {
                // add browse later
                const tagInfo = tagInfoFromPath(pageId);
                
                // tag
                if (TAG_TYPES.has(tagInfo.type)) {
                    browseLaterButton.disabled = true;
                    const tagData = await getOrPullTagCacheData(pageId);
                    browseLaterButton.disabled = false;

                    if (tagData) {
                        isBrowseLater = true;

                        /** @type {BrowseLaterData} */
                        const browseLaterData = {
                            page_key: pageId,
                            added_at: getUnixTimestamp(),
                            browse_priority: DEFAULTS.PRIORITY,
                            name: tagData.name,
                            tag_id: tagData.id
                        };

                        dataStore.browseLater.load();
                        dataStore.browseLater.value.set(pageId, browseLaterData);
                        dataStore.browseLater.save();
                        logger.storeUpdates.log(`Tag ${pageId} added to browse later.`);
                    }
                }
                // page
                else {
                    isBrowseLater = true;

                    /** @type {BrowseLaterData} */
                    const browseLaterData = {
                        page_key: pageId,
                        added_at: getUnixTimestamp(),
                        browse_priority: DEFAULTS.PRIORITY,
                    };

                    dataStore.browseLater.load();
                    dataStore.browseLater.value.set(pageId, browseLaterData);
                    dataStore.browseLater.save();
                    logger.storeUpdates.log(`Page ${pageId} added to browse later.`);
                }
            }
            
            updateVisibility();
        }

        function updateVisibility() {
            browsedButton.showAltContent(isBrowsed);
            browsedButton.classList.toggle('nhcb-is-browsed', isBrowsed);

            browseLaterButton.showAltContent(isBrowseLater);
            browseLaterButton.hidden = isBrowsed && !isBrowseLater;
            browseLaterButton.classList.toggle('nhcb-is-browse-later', isBrowseLater);
        }

        updateVisibility();

        root.append(browsedButton, browseLaterButton);

        return root;
    }
    
    function createEnglishOnlyButton() {
        function buildEnglishOnlySearch() {
            if (pageData.isNamespacePage()) {
                return `language:"english" ${pageData.tagInfo.type}:"${pageData.tagInfo.name.replaceAll('-', ' ')}"`;
            }
            else if (pageData.isSearchPage()){
                return `language:"english" ${pageData.query}`;
            }
        }

        if (pageData.path === '/language/english/' || /english/i.test(pageData.query)) {
            return null;
        }

        const englishSearch = buildEnglishOnlySearch();

        if (!englishSearch) {
            return null;
        }

        const root = createSortTypeGroup({ id: 'nhcb-english-only', links: [
            { label: 'English Only', href: buildUrl({ setParams: {q: englishSearch}, deleteParams: 'page', newPath: '/search' }) }
        ]});

        return root;
    }

    function createFixPipeButton(){
        // for tags that have the '|' in them
        const tagText = document.querySelector('h1 .tagchip .name')?.textContent;

        if (!tagText || !tagText.includes('|')) {
            return null;
        }

        const tagType = pageData.tagInfo.type;
        const tagName = tagText.split(' | ')[0].replaceAll(' ', '-');

        const root = createSortTypeGroup({ id: 'nhcb-fix-pipe', links: [{ label: 'Fix Pipe', href: buildUrl({ newPath: `/${tagType}/${tagName}/`, deleteParams: 'page' })}] });
        
        return root;
    }

    function createSortPopularMonthButton() {
        const popularMonthLink = buildUrl({ setParams: {sort: 'popular-month'}, deleteParams: 'page' });
        const isCurrent = pageData.searchParams.get('sort') === 'popular-month';

        const root = createSortTypeLink({ content: 'month', href: popularMonthLink, isCurrent, elementProperties: { id: 'nhcb-popular-month' } });
        
        return root;
    }
    //#endregion

    //#region Favorite customization
    function createCustomizeFavoriteButton() {
        const root = createButton({ id: 'nhcb-customize-favorites-button', content: 'Customize Favorite', hidden: !dataStore.favoriteGalleries.value.has(pageData.path), onClick: () => {
            makeModal({ headerContent: 'Favorite Customization', content: createCustomizeFavoritePanel() });
        }});

        function updateVisibility() {
            root.hidden = !dataStore.favoriteGalleries.value.has(pageData.path);
        }

        updateVisibility();
        const unsubcribe = dataStore.favoriteGalleries.subscribe(updateVisibility);
        cleaner.addTaskNoFail(unsubcribe);
        
        return root;
    }
    function createCustomizeFavoritePanel() {
        const initialFavoriteData = dataStore.favoriteGalleries.load().get(pageData.path);
        if (!initialFavoriteData) {
            reportIssue('FAVORITE_MISSING', { galleryPath: pageData.path });
            return null;
        }

        const root = createElement('div', { id: 'nhcb-customize-favorite-panel' });

        root.append(createMigrationPanel());
        root.append(createFavoriteAtPanel(initialFavoriteData.favorite_at));
        root.append(createCustomTitlePanel(initialFavoriteData));
        root.append(createRatingPanel(initialFavoriteData.rating));
        root.append(createNotesPanel(initialFavoriteData.note));
        root.append(createLabelsPanel(initialFavoriteData.labels));
        root.append(createAltCoverPanel(initialFavoriteData.alt_cover));
        root.append(createAltSourcePanel(initialFavoriteData));
                
        return root;
    }
    function createMigrationPanel() {
        const root = createElement('div', { className: 'nhcb-favorite-migration-panel' });

        const header = createElement('h3', {}, 
            'Migrate Favorite',
            createTooltip({ 
                content: 'Migrate favorite from one gallery to another. Keeps customizations but uses new gallery as the favorite.<br><br>'
                + 'Useful if customizations were made to a favorite but a new decensored version was posted.<br><br>'
                + '<strong>New favorite must not already be a favorite or 404.</strong>',
                width: '200px'
            })
        );

        const field = createFieldLayout({ className: 'nhcb-favorite-migration-field' });
        
        const safetyLock = createSafetyLock({ onChange: handleSafetyLockToggle });
        const submitButton = createButton({ content: 'Migrate', disabled: true, buttonStyle: 'primary', onClick: handleMigration});
        const input = createInput({ disabled: true, placeholder: 'Link to gallery (1234, /g/1234/, or full link)' });

        function handleSafetyLockToggle(isLocked) {
            submitButton.disabled = isLocked;
            input.disabled = isLocked;
        }

        async function handleMigration() {
            // validate input
            const galleryId = parseGalleryId(input.value);

            if (!galleryId) {
                reportInputInvalidIssue('Input does not contain a valid gallery code.', input.value);
                return;
            }

            // migrate customizations
            const migrationTargetPath = galleryIdToPath(galleryId);
            const result = await opMigrateFavorite(pageData.path, migrationTargetPath);

            if (result.ok) {
                logger.storeUpdates.success(`Successfully migrated customizations for (${pageData.path}) to (${migrationTargetPath})`);
                gotoPage(migrationTargetPath, 1); // potential issue that data can be changed since modal is still open. keep number low, until proper fix
                notifier.info('Favorite migrated. Switching to new page.');
            } else {
                reportPatchFail(result);
            }
        }

        field.append(safetyLock, input, submitButton);
        root.append(header, field);     

        return root;
    }
    function createFavoriteAtPanel(unixTimestamp) {
        let defaultTimestamp = unixTimestamp;

        const root = createElement('div', { className: 'nhcb-favorite-at-panel' });

        const header = createElement('h3', {},
            'Favorited At',
            createTooltip({ 
                content: 'If you really want to edit this, you can, but I am not going add UI for it.<br><br>'
                + 'The number you edit is a UNIX timestamp, google what it is. Use unixtimestamp.com to make one.',
                width: '200px'
            })
        );

        const field = createFieldLayout({ className: 'nhcb-favorite-at-field' });

        const timeDisplay = createTimeAgoDisplay(unixTimestamp, { className: 'nhcb-favorited-at-display' });

        const input = createInput({ id: 'nhcb-favorited-at-input', placeholder: 'Enter unix timestamp', initialValue: unixTimestamp });
        const editButton = createButton({ content: 'Edit Timestamp', buttonStyle: 'primary', onClick: () => setEditState(true)});
        const confirmButton = createButton({ content: 'Confirm', buttonStyle: 'primary', onClick: saveFavoriteAt });
        const cancelButton = createButton({ content: 'Cancel', onClick: () => setEditState(false) });

        function setEditState(isEditMode) {
            input.value = defaultTimestamp;

            timeDisplay.hidden = isEditMode;
            editButton.hidden = isEditMode;
            input.hidden = !isEditMode;
            confirmButton.hidden = !isEditMode;
            cancelButton.hidden = !isEditMode;
        }

        function saveFavoriteAt() {
            const newTimestamp = parseValidIntInRange(input.value, 1);

            if (!newTimestamp) {
                reportInputInvalidIssue('Input does not contain a valid timestamp.', input.value);
                return;
            }

            const result = patchFavorite(pageData.path, { favorite_at: newTimestamp });

            if (result.ok) {
                defaultTimestamp = newTimestamp;
                timeDisplay.changeTimestamp(unixTimestamp);
                setEditState(false);
            } else {
                reportPatchFail(result);
            }
        }

        setEditState(false);

        field.append(timeDisplay, input, editButton, confirmButton, cancelButton);
        root.append(header, field);

        return root;
    }
    function createRatingPanel(initialRating) {
        let defaultValue = initialRating ?? 0;
        let value = defaultValue;

        const root = createElement('div', { className: 'nhcb-favorite-rating-panel' });

        const header = createElement('h3', {},
            'Rating',
            createTooltip({ content: 'Give a rating to remember how good it is.' })
        );

        const field = createFieldLayout({ className: 'nhcb-rating-field' });
        
        const noRatingDisplay = createElement('span', { className: 'nhcb-rating-none' }, 'No Rating');
        const ratingDisplay = createRatingDisplay({});
        const heartsContainer = createElement('div', { className: 'nhcb-rating-hearts-container'}, noRatingDisplay, ratingDisplay);
        const decrementButton = createElement('button', { className: 'nhcb-rating-decrement', onclick: () => incrementRating(-1) }, createIcon('minus-circle', { iconStyle: 'solid' }));
        const incrementButton = createElement('button', { className: 'nhcb-rating-increment', onclick: () => incrementRating(1) }, createIcon('plus-circle', { iconStyle: 'solid' }));

        const editButton = createButton({ content: 'Change Rating', buttonStyle: 'primary', onClick: () => { setEditState(true); } });
        const confirmButton = createButton({ content: 'Confirm', buttonStyle: 'primary', onClick: saveRating });
        const cancelButton = createButton({ content: 'Cancel', onClick: () => { setEditState(false); } });

        function incrementRating(ammount) {
            const allowHalfHeart = settingsStore.allowRatingHalf.value;
            if (settingsStore.allowRatingHalf.value == false) {
                value = isOdd(value) ? value + ammount : value + (ammount * 2);
            } else {
                value += ammount;
            }
            value = clamp(value, 0, 10);
            setRating(value);
        }
        function setRating(newValue) {
            noRatingDisplay.hidden = value !== 0;
            ratingDisplay.changeRating(value);
        }

        function setEditState(isEditMode) {
            value = defaultValue;
            setRating(value);

            decrementButton.hidden = !isEditMode;
            incrementButton.hidden = !isEditMode;
            editButton.hidden = isEditMode;
            confirmButton.hidden = !isEditMode;
            cancelButton.hidden = !isEditMode;
        }

        function saveRating() {
            const newRating = clamp(Math.round(value), 0, 10);

            const result = patchFavorite(pageData.path, { rating: newRating });

            if (result.ok) {
                defaultValue = newRating;
                setEditState(false);
            } else {
                reportPatchFail(result);
            }
        }

        setEditState(false);

        field.append(decrementButton, heartsContainer, incrementButton, editButton, confirmButton, cancelButton);
        root.append(header, field);

        return root;
    }
    function createCustomTitlePanel(/** @type {FavoriteData} */ favoriteData) {
        const originalTitle = favoriteData.english_title ?? '';
        let currentValue = favoriteData.custom_title ?? '';
   
        const root = createElement('div', { className: 'nhcb-favorite-custom-title-panel' });
 
        const header = createElement('h3', {},
            'Custom Title',
            createTooltip({
                content: 'Change the title of the gallery. Usefully if it doesn\'t have an English title for some reason.',
                width: '200px'
            })
        );
        
        const display = createElement('div', { className: 'nhcb-custom-title-display' });
        const input = createInput({ placeholder: 'Enter custom title...', elementProperties: { maxLength: DEFINITIONS.FAVORITE_CUSTOM_TITLE_MAX_LENGTH } });

        const buttons = createElement('div');

        const editButton = createButton({ content: 'Edit Custom Title', buttonStyle: 'primary', onClick: () => setEditState(true) });
        const confirmButton = createButton({ content: 'Confirm', buttonStyle: 'primary', onClick: handleSaveTitle });
        const cancelButton = createButton({ content: 'Cancel', onClick: () => setEditState(false) });

        function setEditState(isEditMode) {
            input.el.value = currentValue;
            
            //display.hidden = isEditMode;
            input.hidden = !isEditMode;
            editButton.hidden = isEditMode;
            confirmButton.hidden = !isEditMode;
            cancelButton.hidden = !isEditMode;

            if (!isEditMode) {
                if (currentValue) {
                    const {before, pretty, after} = parseTitleSections(currentValue);
                    display.replaceChildren(
                        createElement('span', { className: 'nhcb-before '}, before),
                        createElement('span', { className: 'nhcb-pretty '}, pretty),
                        createElement('span', { className: 'nhcb-after '}, after),
                    );
                } else {
                    display.replaceChildren(createElement('span', { className: 'nhcb-empty' }, 'None'));
                }
            } else {
                const {before, pretty, after} = parseTitleSections(originalTitle);
                display.replaceChildren(
                    createElement('span', { className: 'nhcb-before '}, before),
                    createElement('span', { className: 'nhcb-pretty '}, pretty),
                    createElement('span', { className: 'nhcb-after '}, after),
                );
            }
        }

        function handleSaveTitle() {
            const newCustomTitle = parseValidString(input.el.value, { maxLengthInclusive: DEFINITIONS.FAVORITE_CUSTOM_TITLE_MAX_LENGTH, cuttoffAfterMax: true, trim: true });

            if (newCustomTitle == null) {
                reportInputInvalidIssue('Umm, somehow you mananged to enter an invalid custom title. Probably a bug.', input.el.value);
                return;
            }

            const result = patchFavorite(pageData.path, { custom_title: newCustomTitle });

            if (result.ok) {
                currentValue = newCustomTitle;
                setEditState(false);
            } else {
                reportPatchFail(result);
            }
        }

        setEditState(false);

        buttons.append(editButton, confirmButton, cancelButton);
        root.append(header, display, input, buttons);

        return root;
    }
    function createNotesPanel(initialText) {
        let defaultValue = initialText ?? '';
   
        const root = createElement('div', { className: 'nhcb-favorite-notes-panel' });
 
        const header = createElement('h3', {},
            'Notes',
            createTooltip({
                content: 'Notes.<br><br>The notes header looked so lonely without a tooltip buddy 🥺',
                width: '200px'
            })
        );
        
        const textArea = createElement('textarea', { 
            className: 'nhcb-favorite-notes-text',
            placeholder: '', //needed for css
            maxLength: DEFINITIONS.FAVORITE_NOTES_MAX_LENGTH
        });

        const buttons = createElement('div');

        const editButton = createButton({ content: 'Edit Notes', buttonStyle: 'primary', onClick: () => setEditState(true) });
        const confirmButton = createButton({ content: 'Confirm', buttonStyle: 'primary', onClick: handleSaveNote });
        const cancelButton = createButton({ content: 'Cancel', onClick: () => setEditState(false) });

        function setEditState(isEditMode) {
            textArea.el.value = defaultValue;
            textArea.el.placeholder = isEditMode ? 'Enter note...' : 'None';
            textArea.el.readOnly = !isEditMode;

            editButton.hidden = isEditMode;
            confirmButton.hidden = !isEditMode;
            cancelButton.hidden = !isEditMode;
        }

        function handleSaveNote() {
            const newNotesValue = parseValidString(textArea.el.value, { maxLengthInclusive: DEFINITIONS.FAVORITE_NOTES_MAX_LENGTH, cuttoffAfterMax: true, trim: true, onlyTrimIfAllWhitespace: true });

            if (newNotesValue == null) {
                reportInputInvalidIssue('Umm, somehow you mananged to enter an invalid note. Probably a bug.', textArea.el.value);
                return;
            }

            const result = patchFavorite(pageData.path, { note: newNotesValue });

            if (result.ok) {
                defaultValue = newNotesValue;
                setEditState(false);
            } else {
                reportPatchFail(result);
            }
        }

        setEditState(false);

        buttons.append(editButton, confirmButton, cancelButton);
        root.append(header, textArea, buttons);

        return root;
    }

    function createAltCoverPanel(initialAltCoverData) {
        let currentAltCover = initialAltCoverData;

        const taskSaveAltCover = createAbortableTask(handleTaskSaveAltCover);

        const root = createElement('div', { className: 'nhcb-alt-cover-panel' });

        const header = createElement('h3', {},
            'Alt Cover',
            createTooltip({
                content: 'Alt cover replaces the default gallery cover with one you choose.'
                + '<br><br>Great in situations when the gallery has an untranslated cover or a bad crop.',
                width:'200px'
            })
        );

        const altCoverForm = createElement('div', { className: 'nhcb-form'});
        const thumbnailInput = createInput({ placeholder: 'Cover Image Link', initialValue: currentAltCover?.thumbnail });
        
        const buttons = createElement('div');
        const editButton = createButton({ content: 'Add Alt Cover', buttonStyle: 'primary', altContent: 'Edit Alt Cover', onClick: () => setEditState(true) });
        const submitButton = createButton({ content: 'Confirm', buttonStyle: 'primary', onClick: () => taskSaveAltCover.run() });
        const cancelButton = createButton({ content: 'Cancel', onClick: () => { taskSaveAltCover.abort(); setEditState(false); } });

        const deleteButtonWrapper = createElement('div');
        const deleteButtonLock = createSafetyLock({ onChange: (isLocked) =>  { deleteButton.disabled = isLocked; } });
        const deleteButton = createButton({ content: 'Remove Alt Cover', disabled: true, buttonStyle: 'primary', onClick: removeAltCover });

        function setEditState(isEditMode) {
            thumbnailInput.value = currentAltCover?.thumbnail ?? '';
            
            editButton.hidden = isEditMode;
            submitButton.hidden = !isEditMode;
            cancelButton.hidden = !isEditMode;
            
            altCoverForm.hidden = !isEditMode;

            // not technically the same state but fuck it
            deleteButtonLock.isLocked = true;
            deleteButtonWrapper.hidden = !currentAltCover;
            editButton.showAltContent(currentAltCover != null);
        }

        function removeAltCover() {
            const result = patchFavorite(pageData.path, { alt_cover: null });

            if (result.ok) {
                currentAltCover = result.data.alt_cover;
                setEditState(false);
            } else {
                reportPatchFail(result);
            }
        }

        async function handleTaskSaveAltCover({ signal, defer }) {
            submitButton.disabled = true;
            defer(() => submitButton.disabled = false);

            const formData = { 
                thumbnail: parseFullUrlStr(thumbnailInput.value),
                thumbnail_width: null,
                thumbnail_height: null
            };

            if (currentAltCover?.thumbnail && currentAltCover.thumbnail == formData.thumbnail) {
                return;
            }
            if (!formData.thumbnail) {
                reportInputInvalidIssue('Alt cover was not set. The thumbnail must be a url to an image.', formData);
                return;
            }
            const thumbnailSize = await getImageSize(formData.thumbnail, 10000);
            signal.throwIfAborted();
            if (thumbnailSize == null) {
                reportInputInvalidIssue('Alt cover was not set. Could not retrieve image size. Can be caused by bad link, slow connection, or image is protected by login (exhentai).', formData);
                return;
            }
            formData.thumbnail_width = parseValidFloatInRange(thumbnailSize.width, 1);
            formData.thumbnail_height = parseValidFloatInRange(thumbnailSize.height, 1);
            
            if (anyObjectPropertyNull(formData)) {
                reportInputInvalidIssue('Alt cover was not set. The thumbnail must be a url to an image.', formData);
                return;
            }

            const result = patchFavorite(pageData.path, { alt_cover: formData });

            if (!result.ok) {
                reportPatchFail(result);
            }

            currentAltCover = result.data.alt_cover;
            setEditState(false);
        }

        setEditState(false);

        deleteButtonWrapper.append(deleteButtonLock, deleteButton);
        altCoverForm.append(thumbnailInput, deleteButtonWrapper);
        buttons.append(editButton, submitButton, cancelButton);
        root.append(header, altCoverForm, buttons);

        return root;
    }
  
    function createAltSourcePanel(/** @type {FavoriteData} */ initialFavoriteData) {
        // ☠️ a factory so fucked it makes you rethink your entire code structure ☠️
        // Edit: And so the austism consumed me and I rewrote the enitre code structure...

        const taskAddAltSource = createAbortableTask(handleTaskAddAltSource);

        const root = createElement('div', { className: 'nhcb-alt-source-panel' });
   
        const header = createElement('h3', {},
            'Alt Sources',
            createTooltip({ content: 'Add an alternative offsite source. This could either be a backup or a better source.', width: '200px' })
        );

        const displayContainer = createContainerGeneric();

        const addButton = createButton({ content: 'Add Alt Source', buttonStyle: 'primary', onClick: () => setFormDisplayState(true) });
        const formButtonWrapper = createElement('div');
        const submitButton = createButton({ content: 'Submit', buttonStyle: 'primary', onClick: () => taskAddAltSource.run() });
        const cancelButton = createButton({ content: 'Cancel', onClick: () => { taskAddAltSource.abort(); setFormDisplayState(false); } });

        const translationField = createDropdownField({
            labelContent: 'Alt Source is Translation',
            submitButtonContent: 'Update Translation',
            tooltipInfo: 'Set if the alt source should override the language on the gallery.<br>Exists mainly for to prevent darkening of non-english galleries.',
            options: [['true', 'Yes'], ['false', 'No']],
            initialValue: initialFavoriteData?.primary_alt_source_is_translation ?? false,
            onCommit: handleTranslationChange,
        });
        const actionField = createDropdownField({
            labelContent: 'Alt Source Action',
            submitButtonContent: 'Update Action',
            tooltipInfo: 'Changes how alt source should be treated.<br><br>'
            + 'Nudge remides you that you should use the alt source if you go to the page.<br><br>'
            + 'Force replaces gallery links with the alt source link.<br><br>'
            + 'If you use Force, you can get back to this page to change it by either using a direct link or by using the raw display on the custom favorites page.',
            options: [['none', 'Do Nothing'], ['nudge', 'Nudge Towards'], ['force', 'Force Replace Links']],
            initialValue: initialFavoriteData?.alt_source_action,
            onCommit: handleActionChange,
        });
        const removeField = createDropdownField({
            labelContent: 'Remove Alt Source',
            submitButtonContent: 'Delete Alt Source',
            tooltipInfo: 'Removes alt source specified by the link.',
            onCommit: handleLinkRemove,
        });
        const makePrimaryField = createDropdownField({
            labelContent: 'Make Alt Source Primary',
            submitButtonContent: 'Make Primary',
            tooltipInfo: 'Makes the alt source specified by the link the primary alt source.<br><br>'
            + 'This is the first one shown below. It is also the one that is used for actions like nudge or force.',
            onCommit: handleMakePrimary,
        });

        const form = createElement('div', { className: 'nhcb-form', hidden: true });

        const nameInput = createInput({ placeholder: 'Source Name' });
        const linkInput = createInput({ placeholder: 'Source Link'});
        const thumbnailInput = createInput({ placeholder: 'Cover Image Direct Link' });
        
        function setFormDisplayState(showForm) {
            addButton.hidden = showForm;
            form.hidden = !showForm;

            nameInput.value = '';
            linkInput.value = '';
            thumbnailInput.value = '';
        }
        function updateDropdownDisplay(favoriteData) {
            const altSourceOptions = favoriteData?.alt_sources?.map(altSource => [altSource.link, `${altSource.name} - ${altSource.link}`]) ?? [];

            // update options in selects
            actionField.value = favoriteData?.alt_source_action ?? 'none';
            translationField.value = favoriteData?.primary_alt_source_is_translation ?? false;
            removeField.replaceOptions(altSourceOptions);
            makePrimaryField.replaceOptions(altSourceOptions);

            // update visibility
            const hasNoAltSources = altSourceOptions.length == 0;
            const hasMultipleAltSources = altSourceOptions.length > 1;

            displayContainer.hidden = hasNoAltSources;
            translationField.hidden = hasNoAltSources;
            actionField.hidden = hasNoAltSources;
            removeField.hidden = hasNoAltSources;
            makePrimaryField.hidden = !hasMultipleAltSources;
        }
        function repopulateDisplayContainer(favoriteData) {
            const newAltSourcesGalleries = [];

            favoriteData?.alt_sources?.forEach((altSourceData, index) => {
                const gallery = createGalleryFromData(favoriteData, {
                    forbidAltCover: true,
                    forceAltSource: true,
                    altSourceIndex: index
                });
                newAltSourcesGalleries.push(gallery);
            });

            displayContainer.replaceChildren(...newAltSourcesGalleries);
        }

        async function handleTaskAddAltSource({ signal, defer }) {
            submitButton.disabled = true;
            defer(() => submitButton.disabled = false);

            const formData = { 
                name: parseValidString(nameInput.value, { trim: true, allowEmpty: false }),
                link: parseFullUrlStr(linkInput.value),
                thumbnail: parseFullUrlStr(thumbnailInput.value),
                thumbnail_width: null,
                thumbnail_height: null
            };

            if (!formData.thumbnail) {
                reportInputInvalidIssue('Alt source not added, data is not valid. You must give a name, the link and thumbnail must be a full url.', formData);
                return;
            }
            const thumbnailSize = await getImageSize(formData.thumbnail, 10000);
            signal.throwIfAborted();
            if (thumbnailSize == null) {
                reportInputInvalidIssue('Alt source not added. Could not retrieve image size. Can be caused by bad link, slow connection, or image is protected by login (exhentai).', formData);
                return;
            }
            formData.thumbnail_width = parseValidFloatInRange(thumbnailSize.width, 1);
            formData.thumbnail_height = parseValidFloatInRange(thumbnailSize.height, 1);
            

            if (anyObjectPropertyNull(formData)) {
                reportInputInvalidIssue('Alt source not added, data is not valid. You must give a name, the link and thumbnail must be a full url.', formData);
                return;
            }

            const result = patchFavorite(pageData.path, { alt_sources: { op: 'pushObj', value: formData, unique: true, idKey: 'link' } });

            if (!result.ok) {
                reportPatchFail(result);
                return;
            }

            const favoriteData = result.data;

            updateDropdownDisplay(favoriteData);
            repopulateDisplayContainer(favoriteData);
            setFormDisplayState(false);
        }
        function handleTranslationChange(newValue) {
            const parsedValue = parseBool(newValue);
            if (parsedValue == null) {
                reportInputInvalidIssue('Is Translation is invalid! How did you manage that?', newValue);
                return;
            }

            const result = patchFavorite(pageData.path, { primary_alt_source_is_translation: parsedValue });

            if (!result.ok) {
                reportPatchFail(result);
                return;
            }

            translationField.isLocked = true;
        }
        function handleActionChange(newAction) {
            if (newAction == '') {
                reportInputInvalidIssue('Alt source action is invalid! How did you manage that?', newAction);
                return;
            }

            const result = patchFavorite(pageData.path, { alt_source_action: newAction });

            if (!result.ok) {
                reportPatchFail(result);
                return;
            }

            actionField.isLocked = true;
        }
        function handleLinkRemove(targetLink) {
            let result = patchFavorite(pageData.path, { alt_sources: { op: 'removeObj', idKey: 'link', id: targetLink } });

            if (!result.ok) {
                reportPatchFail(result);
                return;
            }

            if (result.data.alt_sources.length == 0 && result.data.alt_source_action !== 'none') {
                result = patchFavorite(pageData.path, { alt_source_action: 'none', primary_alt_source_is_translation: false });

                if (!result.ok) {
                    reportPatchFail(result);
                    return;
                }
            }

            const favoriteData = result.data;

            updateDropdownDisplay(favoriteData);
            repopulateDisplayContainer(favoriteData);
            removeField.isLocked = true;
        }
        function handleMakePrimary(targetLink) {
            const result = patchFavorite(pageData.path, { alt_sources: { op: 'promote', idKey: 'link', id: targetLink } });

            if (result.issue === 'PATCH_ARRAY_PROMOTION_FAIL') {
                reportIssue('ALT_SOURCE_MISSING', { galleryPath: pageData.path, altSourceLink: targetLink });
                // fall through
            } else if (!result.ok) {
                reportPatchFail(result);
                return;
            }

            const favoriteData = result.ok ? result.data : dataStore.favoriteGalleries.value.get(pageData.path);

            updateDropdownDisplay(favoriteData);
            repopulateDisplayContainer(favoriteData);
            makePrimaryField.isLocked = true;
        }

        // initialize display
        updateDropdownDisplay(initialFavoriteData);
        repopulateDisplayContainer(initialFavoriteData);


        formButtonWrapper.append(submitButton, cancelButton);
        form.append(nameInput, linkInput, thumbnailInput, formButtonWrapper);
        root.append(header, translationField, actionField, removeField, makePrimaryField, displayContainer, form, addButton);

        return root;
    }

    function createLabelsPanel(/** @type {Label[]} */ initialLabels) {
        const root = createElement('div', { className: 'nhcb-favorite-label-panel' });
 
        const header = createElement('h3', {},
            'Labels',
            createTooltip({
                content: 'Add labels to make it easier to find types of galleries.<br>Simialr to a tag.',
                width: '200px'
            })
        );        
        const labelsField = createLabelsField({ availableLabels: [...settingsStore.labels.value], initialLabels: toArray(initialLabels), onLabelAdd: addLabel, onLabelRemove: removeLabel });

        function addLabel(labelName) {
            const result = patchFavorite(pageData.path, {
                labels: { op: 'push', value: labelName, unique: true }
            });

            if (!result.ok) {
                reportPatchFail(result);
            }
        }
        function removeLabel(labelName) {
            const result = patchFavorite(pageData.path, {
                labels: { op: 'remove', id: labelName }
            });

            if (!result.ok) {
                reportPatchFail(result);
            }
        }

        root.append(header, labelsField);

        return root;
    }
    //#endregion

    //#region Settings
    function createApiKeySettingsPanel() {
        const root = createElement('div', {
            className: 'nhcb-api-key-settings'
        }, createElement('h2', {}, 'API Key', createTooltip({ content: 'You can add an API key to increase your rate limits. Doesn\'t help in every case and is not needed for normal operation, but it can help reduce rate limits. To get an API key, you need to log into your account and and create one on your profile. You can put whatever, but I recommend using "Custom Brew" for the name and "Tampermonkey script" for the description. It can fail randomly due to server load.', width: '200px' })));

        const valueParser = (value) => parseValidString(value, { trim: true, allowEmpty: true, minLengthInclusive: 10 });

        let keyHidden = true;

        const keyField = createInputField({ 
            labelContent: 'API Key',
            submitButtonContent: 'Save',
            initialValue: secretStore.apiKey.value,
            placeholder: 'nhk_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
            useSafetyLock: false,
            lockSubmitIfUnchanged: true,
            onCommit: handleCommit,
            onInputChange: handleInputChange,
        });

        const toggleButton = createButton({ content: 'Show', buttonStyle: 'primary', onClick: () => { handleDisplayToggle() }, elementProperties: {style :'margin-top: 6px;'} });

        function handleDisplayToggle(force = null) {
            if (force != null) {
                keyHidden = force;
            } else {
                keyHidden = !keyHidden;
            }
            toggleButton.replaceChildren(keyHidden ? 'Show Key' : ' Hide Key');
            keyField.hidden = keyHidden;
        }

        function handleCommit(value) {
            const newValue = valueParser(value);
            if (newValue == null) {
                return false;
            }
            // no need to load the setting before saving because all settings that use this should be literals
            secretStore.apiKey.value = newValue;
            secretStore.apiKey.save();
            logger.storeUpdates.log(`Setting 'apikey' was changed.`);
        }

        function handleInputChange(value) {
            const newValue = valueParser(value);
            if (newValue == null) {
                return false;
            }
            return true;
        }

        handleDisplayToggle(true);

        root.append(keyField, toggleButton);

        return root;
    }
    function createAutoLoginSettingsPanel() {
        const root = createElement('div', {
            className: 'nhcb-auto-login-settings'
        }, createElement('h2', {}, 'Auto Login', createTooltip({ content: 'Save your login info to auto login or make it easier to login. Remember, if you plan on using this script while logged in, you should enable "Separate Custom Favorite Button" under the "Custom Favorites" section to prevent weird behavior.', width: '200px' })));

        const valueParser = (value) => parseValidString(value, { trim: true, allowEmpty: true, minLengthInclusive: 4 });

        let infoHidden = true;

        const usernameField = createInputField({ 
            labelContent: 'Username',
            submitButtonContent: 'Save',
            initialValue: secretStore.username.value,
            placeholder: 'username or email used to login',
            useSafetyLock: false,
            lockSubmitIfUnchanged: true,
            onCommit: handleCommitUsername,
            onInputChange: handleInputChange,
        });
        const passwordField = createInputField({ 
            labelContent: 'Password',
            submitButtonContent: 'Save',
            initialValue: secretStore.password.value,
            placeholder: 'password used to login',
            useSafetyLock: false,
            lockSubmitIfUnchanged: true,
            onCommit: handleCommitPassword,
            onInputChange: handleInputChange,
        });
        passwordField.type = 'password';

        const toggleButton = createButton({ content: 'Show', buttonStyle: 'primary', onClick: () => { handleDisplayToggle() }, elementProperties: {style :'margin-top: 6px;'} });

        const autoLoginSettings = [
            createBinarySettingsField('enableAutoLogin',            { labelContent: 'Auto Login',                   tooltipInfo: 'If enabled, will automatcially navigate to the login page to allow for auto fill and auto submit. Can create a problem where you are forced to go to login until it is completed or if something breaks. If this happens, go back to the settings. You will not be forced to other pages if you are on the settings page.', binaryOptionType: 'enabled/disabled' }),
            createBinarySettingsField('enableAutoFillForLogin',     { labelContent: 'Auto Fill Login',              tooltipInfo: 'If enabled, login info will automatically be fileld out using the supplied username and password. If they are not given, then this does nothing.', binaryOptionType: 'enabled/disabled' }),
            createBinarySettingsField('autoSubmitAfterAutoFill',    { labelContent: 'Auto Submit After Auto Fill',  tooltipInfo: 'If enabled, login info will automatically be submitted after the captcha is completed. There is nothing I can do to bypass the captcha but it usally auto completes without having to do anything.', binaryOptionType: 'enabled/disabled' }),
        ]

        function handleDisplayToggle(force = null) {
            if (force != null) {
                infoHidden = force;
            } else {
                infoHidden = !infoHidden;
            }
            toggleButton.replaceChildren(infoHidden ? 'Show login info' : ' Hide login info');
            usernameField.hidden = infoHidden;
            passwordField.hidden = infoHidden;
        }

        function handleCommitUsername(value) {
            const newValue = valueParser(value);
            if (newValue == null) {
                return false;
            }
            // no need to load the setting before saving because all settings that use this should be literals
            secretStore.username.value = newValue;
            secretStore.username.save();
            logger.storeUpdates.log(`Setting 'username' was changed.`);
        }

        function handleCommitPassword(value) {
            const newValue = valueParser(value);
            if (newValue == null) {
                return false;
            }
            // no need to load the setting before saving because all settings that use this should be literals
            secretStore.password.value = newValue;
            secretStore.password.save();
            logger.storeUpdates.log(`Setting 'password' was changed.`);
        }

        function handleInputChange(value) {
            const newValue = valueParser(value);
            if (newValue == null) {
                return false;
            }
            return true;
        }

        handleDisplayToggle(true);

        root.append(usernameField, passwordField, toggleButton, ...autoLoginSettings);

        return root;
    }
    function createBackupSettingsPanel() {
        const root = createElement('div', {
            className: 'nhcb-backup-settings'
        }, createElement('h2', {}, 'Import/Export Data', createTooltip({ content: 'Backup data and settings for safe keeping or transfer.', width: '200px' })));

        let includeSecrets = false;

        const backupHeader = createElement('h3', {}, 'Backup Data');
        const lastBackupText = createElement('p', {}, 'Last Backup: ', dataStore.lastBackupAt.value ? createTimeAgoDisplay(getUnixTimestampFromDate(dataStore.lastBackupAt.value)) : 'Never');
        const checkbox = createElement('input', { type: 'checkbox', checked: includeSecrets });
        const backupButton = createButton({ content: ['Backup NHCB Data'], buttonStyle: 'primary', onClick: () => { handleExportClick(); }});
        const importButton = createButton({ content: ['Import NHCB Data'], buttonStyle: 'primary', onClick: () => { importFromFile(); }});
        const safetyLock = createSafetyLock({ onChange: handleLockChange });
        const importButtonWrapper = createElement('div', {}, safetyLock, importButton);

        checkbox.el.addEventListener('change', (e) => {
            includeSecrets = e.currentTarget.checked;
        });

        const checkboxWrapper = createElement('div', {}, createElement('label', { style: 'display: inline-block; font-weight: 700; margin: 0.5em;' }, 'Include api key and login info?'), checkbox);

        function handleLockChange(isLocked) {
            importButton.disabled = isLocked;
        }
        handleLockChange(true);

        function handleExportClick() {
            exportDataToFile(includeSecrets);
        }

        function importFromFile() {
            let input = createElement('input', { type: 'file', accept: '.json', onchange: async (e) => {
                const file = e.target.files[0];
                if (!file) {
                    return;
                }
                try {
                    const text = await file.text();
                    const result = await opImportDataFromJson(text);
                    if (result.ok) {
                        safetyLock.isLocked = true;
                        notifier.info('Import successful.');
                    } else {
                        reportPatchFail(result);
                    }
                    
                } catch (err) {
                }
            }});
            input.el.click();            
        }

        root.append(lastBackupText, checkboxWrapper, backupButton, importButtonWrapper);

        return root;
    }
    function createLabelSettingsPanel() {
        const root = createElement('div', {
            className: 'nhcb-label-settings'
        }, createElement('h2', {}, 'Labels', createTooltip({ content: 'Labels are similar to tags except only you can add them.<br>Use them to help categorize them without relying on tags.', width: '200px' })));

        const labelBox = createLabelBox({ className: 'nhcb-label-settings-display', readOnly: true })
        const addLabelLayout = createFieldLayout({ className: 'nhcb-label-settings-add' });
        const deleteLabelLayout = createFieldLayout({ className: 'nhcb-label-settings-delete' });
        const renameLabelLayout = createFieldLayout({ className: 'nhcb-label-settings-rename' });

        const addLabelSearchableDropdown = createSearchableDropdown({ placeholder: 'Add new label...', onSearchChange: handleAddSearchChange }); // availableOptions === disabledOptions
        const deleteLabelSearchableDropdown = createSearchableDropdown({ placeholder: 'Delete label...', onSearchChange: handleDeleteSearchChange});
        const labelRanameSelect = createSearchableDropdown({ placeholder: 'Label to rename...', onSearchChange: handleRenameSelectSearchChange });
        const labelRenameNewName = createSearchableDropdown({ placeholder: 'New label name...', onSearchChange: handleRenameNewNameSearchChange });
        const addLabelButton = createButton({ content: 'Add Label', buttonStyle: 'primary', onClick: handleAddLabelClick, disabled: true });
        const deleteLabelButton = createButton({ content: 'Delete', buttonStyle: 'primary', onClick: handleDeleteLabelClick, disabled: true });
        const renameLabelButton = createButton({ content: 'Rename', buttonStyle: 'primary', onClick: handleRenameLabelClick, disabled: true });

        const reorderLabelsField = createInputField({ submitButtonContent: 'Reorder', onInputChange: handleReorderLabelsChange, onCommit: handleReorderLabelsClick, lockSubmitIfUnchanged: true, tooltipInfo: 'Change the order in which labels appear. You must include all existing labels with exact spelling and punctuation. Seperate labels by commas.' })

        const normalizedLabelSet = new Set();
        const labelAlreadyExists = (label) => normalizedLabelSet.has(label?.trim().toLowerCase());

        const renameDisabled = {
            select: true,
            new: true,
        };


        function handleAddSearchChange(search) {
            const label = parseLabel(search);
            addLabelButton.disabled = (!label || labelAlreadyExists(label) || label === 'none');
        }
        function handleDeleteSearchChange(search) {
            const label = parseLabel(search);
            deleteLabelButton.disabled = (!label || !labelAlreadyExists(label));
        }
        function handleRenameSelectSearchChange(search) {
            const label = parseLabel(search);
            renameDisabled.select = (!label || !labelAlreadyExists(label));
            renameLabelButton.disabled = (renameDisabled.select || renameDisabled.new);
        }
        function handleRenameNewNameSearchChange(search) {
            const label = parseLabel(search);
            renameDisabled.new = (!label || labelAlreadyExists(label) || label === 'none');
            renameLabelButton.disabled = (renameDisabled.select || renameDisabled.new);
        }
        function handleReorderLabelsChange(input) {
            if (!input) {
                return false;
            }
            const inputLabelsSet = new Set(input.split(','));
            const setsMatch = inputLabelsSet.symmetricDifference(settingsStore.labels.value).size === 0; 
            return setsMatch;
        }
        
        function handleAddLabelClick() {
            const label = parseLabel(addLabelSearchableDropdown.searchInputValue);
            if (label && label != 'none') {
                addLabel(label);
                addLabelSearchableDropdown.clearSearch();
            }
            addLabelButton.disabled = true;
        }
        function handleDeleteLabelClick(){
            const label = parseLabel(deleteLabelSearchableDropdown.searchInputValue);
            const matchedLabel = [...settingsStore.labels.value].find(storedLabel => storedLabel.toLowerCase() === label.toLowerCase());
            if (matchedLabel) {
                makeModal({
                    headerContent: 'Are you sure you want to delete label?',
                    content: [createElement('p', {}, `Attempting to delete label:`, createGalleryLabel(matchedLabel, { elementProperties: { style: 'margin-left:5px;margin-top:-3px;'} })), 'Deleting a label will remove the label from all galleries.'],
                    submitButtonContent: 'Delete',
                    closeButtonContent: 'Cancel',
                    submitButtonCallback: () => {
                        deleteLabelButton.disabled = true;
                        deleteLabel(matchedLabel);
                        deleteLabelSearchableDropdown.clearSearch();
                    }
                })
            } else {
                deleteLabelButton.disabled = true;
            }
        }
        function handleRenameLabelClick() {
            const label = parseLabel(labelRanameSelect.searchInputValue);
            const matchedLabel = [...settingsStore.labels.value].find(storedLabel => storedLabel.toLowerCase() === label.toLowerCase());
            const newLabel = parseLabel(labelRenameNewName.searchInputValue);
            if (matchedLabel && newLabel && newLabel != 'none') {
                makeModal({
                    headerContent: 'Are you sure you want to rename label?',
                    content: [createElement('p', {}, `Attempting to rename label`, createGalleryLabel(matchedLabel, { elementProperties: { style: 'margin-left:5px;margin-right:5px;margin-top:-3px;'} }), 'to', createGalleryLabel(newLabel, { elementProperties: { style: 'margin-left:5px;margin-top:-3px;'} })), 'Renaming a label will replace the label on all galleries.'],
                    submitButtonContent: 'Rename',
                    closeButtonContent: 'Cancel',
                    submitButtonCallback: () => {
                        renameLabelButton.disabled = true;
                        renameLabel(matchedLabel, newLabel);
                        labelRanameSelect.clearSearch();
                        labelRenameNewName.clearSearch();
                    }
                })
            } else {
                renameLabelButton.disabled = true;
            }
        }
        function handleReorderLabelsClick() {
            const inputLabelsSet = new Set(reorderLabelsField.value.split(','));
            const setsMatch = inputLabelsSet.symmetricDifference(settingsStore.labels.value).size === 0;
            if (setsMatch) {
                reorderLabels([...inputLabelsSet]);
                return true;
            } else {
                return false
            }
        }

        function addLabel(label) {
            settingsStore.labels.load();
            // confirm label is new
            if (labelAlreadyExists(label)) {
                return;
            }
            settingsStore.labels.value.add(label);
            settingsStore.labels.save();
            logger.storeUpdates.log('Added new label:', label);
            refreshLabels();
        }
        function deleteLabel(label) {
            settingsStore.labels.load();
            // confirm label exists
            if (!labelAlreadyExists(label)) {
                return;
            }
            // mass remove
            const result = opRemoveLabelFromAll(label);
            if (!result.ok) {
                reportPatchFail(result);
            }
            // remove backing data
            settingsStore.labels.value.delete(label);
            settingsStore.labels.save();
            logger.storeUpdates.log('Deleted existing label:', label);
            refreshLabels();
        }
        function renameLabel(originalLabel, newLabel) {
            settingsStore.labels.load();
            // confirm label exists
            if (!labelAlreadyExists(originalLabel)) {
                return;
            }
            const result = opRenameLabel(originalLabel, newLabel);
            if (!result.ok) {
                reportPatchFail(result);
            }
            refreshLabels();
        }
        function reorderLabels(labels) {
            settingsStore.labels.value = new Set(labels);
            settingsStore.labels.save();
            logger.storeUpdates.log('Reordered labesl:', labels);
            refreshLabels();
        }

        function refreshLabels() {
            const labels = [...settingsStore.labels.value];
            labelBox.replaceLabels(labels);
            addLabelSearchableDropdown.replaceOptions([...(new Set([...DEFAULTS.LABEL_OPTIONS, ...DEFINITIONS.RESERVED_LABELS, ...labels]))], [...DEFINITIONS.RESERVED_LABELS, ...labels]);
            deleteLabelSearchableDropdown.replaceOptions(labels);
            labelRanameSelect.replaceOptions(labels);
            labelRenameNewName.replaceOptions(labels, [...DEFINITIONS.RESERVED_LABELS, ...labels]);
            reorderLabelsField.value = labels.join(',');
            normalizedLabelSet.clear();
            labels.forEach(label => normalizedLabelSet.add(label.toLowerCase()));
        }

        refreshLabels();

        addLabelLayout.append(addLabelSearchableDropdown, addLabelButton);
        deleteLabelLayout.append(deleteLabelSearchableDropdown, deleteLabelButton);
        renameLabelLayout.append(labelRanameSelect, labelRenameNewName, renameLabelButton);
        root.append(labelBox, addLabelLayout, deleteLabelLayout, renameLabelLayout, reorderLabelsField);

        return root;
    }
    function createContentWarningSettingsPanel() {
        const root = createElement('div', {
            className: 'nhcb-content-warning-settings'
        }, createElement('h2', {}, 'Content Warning', createTooltip({ content: 'Content warning is a badge for warning you of nefarious content that a gallery may have.<br><br>This is experimental and quickly thrown together so there may be bugs.', width: '200px' })));

        const enableContentWarningBadge = createBinarySettingsField('enableContentWarningBadge', {
            labelContent: 'Content Warning Badge',
            tooltipInfo: 'If enabled, it adds a badge to galleries with a content warning.',
            binaryOptionType: 'enabled/disabled'
        });

        const editContentWarningButton = createButton({ content: 'Show Content Warning Rules', buttonStyle: 'primary', onClick: () => setEditState(true) });
        const hideContentWarningButton = createButton({ content: 'Hide Content Warning Rules', buttonStyle: 'secondary', onClick: () => setEditState(false) });

        const addRuleButton = createButton({ content: 'New Rule', buttonStyle: 'primary',  onClick: addNewRule, elementProperties: { style: 'margin: 12px 0;' } });
        const rulesList = createDiv({ className: 'nhcb-cw-rules-list' });
        const rulesDisplay = createDiv({ className: 'nhcb-cw-rules' }, rulesList, createDiv({}, addRuleButton));

        const editAreaContainer = createDiv({ hidden: true }, rulesDisplay );

        let nextId = 0;
        const rules = /** @type {{config: ContentWarningRule, root: {label: FacoryRoot, display: factoryRoot} & FactoryRoot, id: int}[]} */ ([]);
        const getDefaultRule = () => ({ label: 'NEW', input: '', logic: []});

        function repopulateRuleListConditions(/** @type {FactoryRoot} */ display, /** @type {ContentWarningRule} */ rule) {
            const conditions = rule.input.split(',').filter((text) => text).map((text, index) => ({ tag: text.replace('!', ''), negated: rule.logic[index] < 0 }));
            const conditionRoots = conditions.map(({tag, negated}) => createDiv({ className: 'nhcb-cw-rule-condition' }, createIcon(negated ? 'times' :'check', { iconStyle: 'solid' }), createElement('span', {}, tag)));
            display.replaceChildren(...conditionRoots);
        }

        function createRuleListItem(/** @type {ContentWarningRule} */ rule, id) {
            const root = createDiv({ className: 'nhcb-cw-rule' });
            const label = createSpan(rule.label, { className: 'nhcb-cw-rule-label' });
            const display = createDiv({ className: 'nhcb-cw-rule-conditions-display' });
            const moveUpButton = createButton({ content: createIcon('arrow-up', { iconStyle: 'solid' }), elementProperties: { className: 'nhcb-cw-rule-order-button' }, onClick: () => moveRuleUp(id) });
            const moveDownButton = createButton({ content: createIcon('arrow-down', { iconStyle: 'solid' }), elementProperties: { className: 'nhcb-cw-rule-order-button' }, onClick: () => moveRuleDown(id) });
            const editButton = createButton({ content: 'Edit', buttonStyle: 'primary', onClick: () => showEditRuleModal(id) });

            repopulateRuleListConditions(display, rule);
            root.append(label, display, moveUpButton, moveDownButton, editButton);
            
            root.label = label;
            root.display = display;

            return root;
        }

        function addRuleListItem(/** @type {ContentWarningRule} */ rule) {
            const data = {
                config: rule,
                root: createRuleListItem(rule, nextId),
                id: nextId,
            };
            nextId++;
            rules.push(data);
            rulesList.append(data.root);

            return data.id;
        }

        function addNewRule() {
            const newRule = getDefaultRule()
            const id = addRuleListItem(newRule);
            saveConfig();
            showEditRuleModal(id);
        }
        function moveRuleUp(id) {
            const i = rules.findIndex((rule) => rule.id === id);
            if (i > 0) {
                const el = rules[i].root.el;
                const parent = el.parentElement;
                const previousSibling = el.previousElementSibling;
                parent.insertBefore(el, previousSibling);

                const tmp = rules[i];
                rules[i] = rules[i-1];
                rules[i-1] = tmp;
                saveConfig();
            }
        }
        function moveRuleDown(id) {
            const i = rules.findIndex((rule) => rule.id === id);
            if (i < rules.length - 1) {
                const el = rules[i].root.el;
                const nextSibling = el.nextElementSibling;
                el.nextElementSibling.after(el);

                const tmp = rules[i];
                rules[i] = rules[i+1];
                rules[i+1] = tmp;
                saveConfig();
            }
        }

        function showEditRuleModal(id) {
            const ruleConfig = rules.find((rule) => rule.id === id)?.config;
            if (!ruleConfig) {
                logger.error("It broke, but didn't make issue");
                return;
            }
            const input = createInput({ initialValue: ruleConfig.label, });
            const inputField = createFieldLayout({ content: [createElement('label', {}, 'Label'), input] });
            const tagList = createDiv({ className: 'nhcb-cw-edit-tag-list' });
            const tags = ruleConfig.input.split(',').filter((text) => text).map((text, index) => ({ tag: text.replace('!', ''), id: Math.abs(ruleConfig.logic[index]), negated: ruleConfig.logic[index] < 0, root: null }));
            const tagSearch = createTagSearch({ elementProperties: { style: 'margin-left: 9px;' }, onTagSelect: (tagData) => {
                const index = tags.findIndex((tag) => tag.id === tagData.id );
                if (index < 0) {
                    const newTagRoot = createTagDisplay(tagData.url, tagData.id, false);
                    tags.push({
                        tag: tagData.url,
                        id: tagData.id,
                        negated: false,
                        root: newTagRoot
                    });
                    tagList.append(newTagRoot);
                }
            }});
            const addTagField = createFieldLayout({ content: [createElement('label', {}, 'Add Tag'),  createTooltip({ content: `Search for a tag using search format (tag:"...") then click it to add it.<br><br>Search sometimes breaks so retype it if it doesn't show results.`, width: '250px' }), tagSearch], elementProperties: { style: 'margin: 12px 0; width: 350px;' } });
            const deleteButton = createButton({ content: 'Delete Rule', disabled: true, buttonStyle: 'primary', onClick: deleteAndSave });
            const deleteteButtonLock = createSafetyLock({ onChange: (isLocked) =>  { deleteButton.disabled = isLocked; } });
            const deleteButtonWrapper = createDiv({}, deleteteButtonLock, deleteButton);
            
            function createTagDisplay(tag, id, negated) {
                const root = createDiv({ className: 'nhcb-cw-edit-tag' });
                const span = createSpan(tag);
                const negateToggle = createElement('input', { type: 'checkbox', checked: !negated });
                const deleteButton = createButton({ content: 'Remove', buttonStyle: 'primary', onClick: () => {
                    const index = tags.findIndex((tagData) => tagData.id === id);
                    tags.splice(index, 1);
                    root.el.remove();
                }});
                
                negateToggle.el.addEventListener('change', (e) => {
                    const index = tags.findIndex((tagData) => tagData.id === id);
                    tags[index].negated = !e.target.checked;
                });

                root.append(negateToggle, span, deleteButton);

                return root;
            }

            tags.forEach((tag) => {
                const tagRoot = createTagDisplay(tag.tag, tag.id, tag.negated);
                tag.root = tagRoot;
                tagList.append(tagRoot);
            });

            function deleteAndSave() {
                const i = rules.findIndex((rule) => rule.id === id);
                rules[i].root.el.remove();
                rules.splice(i, 1);
                saveConfig();
                closeModal();
            }
            function validateAndSave() {
                const updatedConfig = {
                    label: parseValidString(input.value, { trim: true, allowEmpty: false, maxLengthInclusive: 16 }),
                    input: tags.map((tag) => (tag.negated ? '!' : '') + tag.tag).join(','),
                    logic: tags.map((tag) => tag.id * (tag.negated ? -1 : 1)),
                }

                const i = rules.findIndex((rule) => rule.id === id);
                rules[i].config = updatedConfig;
                saveConfig();
                const root = rules[i].root;
                root.label.replaceChildren(updatedConfig.label);
                repopulateRuleListConditions(root.display, updatedConfig);

                return true;
            }
            
            const closeModal = makeModal({ content: [inputField, tagList, addTagField, deleteButtonWrapper], headerContent: 'Edit Content Warning Rule', closeButtonContent: 'Cancel', submitButtonContent: 'Save', submitButtonCallback: validateAndSave });
        }

        function saveConfig() {
            const previousConfig = settingsStore.contentWarningConfig.value;
            const newConfig = rules.map(({config}) => config);
            settingsStore.contentWarningConfig.value = newConfig;
            settingsStore.contentWarningConfig.save();
            logger.storeUpdates.log(`Content Warning Config was updated.`, '\nBefore:', previousConfig, '\nAfter:', newConfig);
        }

        function setEditState(isEditMode) {
            editAreaContainer.hidden = !isEditMode;
            editContentWarningButton.hidden = isEditMode;
            hideContentWarningButton.hidden = !isEditMode;
        }

        setEditState(false);
        settingsStore.contentWarningConfig.value.forEach(rule => addRuleListItem(rule));

        root.append(enableContentWarningBadge, editContentWarningButton, editAreaContainer, hideContentWarningButton);

        return root;
    }
    //#endregion

    //#region Other
    function showEditReadLaterModal(galleryPath, onRemove = null) {
        const initialReadLaterData = dataStore.readLater.value.get(galleryPath);
        if (!initialReadLaterData) {
            return null;
        }
 
        const root = createElement('div', { className: 'nhcb-read-later-modal' });

        const migrationField = createFieldLayout({ className: 'nhcb-read-later-migration-field' });
        const safetyLock = createSafetyLock({ onChange: handleSafetyLockToggle });
        const submitButton = createButton({ content: 'Migrate', disabled: true, buttonStyle: 'primary', onClick: handleMigration});
        const input = createInput({ disabled: true, placeholder: 'Link to gallery (1234, /g/1234/, or full link)' });

        const priorityField = createDropdownField({
            labelContent: 'Read Priority',
            submitButtonContent: 'Save',
            tooltipInfo: 'Set a priority to order what should be read first.',
            options: DEFAULTS.PRIORITY_DROPDOWN_OPTIONS,
            initialValue: initialReadLaterData.read_priority,
            useSafetyLock: false,
            lockSubmitIfUnchanged: true,
            useSubmitButton: false,
            onCommit: savePriority,
        })
        const labelsField = createLabelsField({ availableLabels: [...settingsStore.labels.value], initialLabels: initialReadLaterData.labels, onLabelAdd: addLabel, onLabelRemove: removeLabel });
        const removeButtonWrapper = createElement('div', { style: 'margin-top: 12px;' });
        const removeButtonLock = createSafetyLock({ onChange: (isLocked) =>  { removeButton.disabled = isLocked; } });
        const removeButton = createButton({ content: 'Remove Read Later', disabled: true, buttonStyle: 'primary', onClick: handleRemoveClick });
        removeButtonWrapper.append(removeButtonLock, removeButton);
        let closeModal;

        function handleSafetyLockToggle(isLocked) {
            submitButton.disabled = isLocked;
            input.disabled = isLocked;
        }
        async function handleMigration() {
            // validate input
            const galleryId = parseGalleryId(input.value);

            if (!galleryId) {
                reportInputInvalidIssue('Input does not contain a valid gallery code.', input.value);
                return;
            }

            // migrate read later
            const migrationTargetPath = galleryIdToPath(galleryId);
            const result = await opMigrateReadLater(galleryPath, migrationTargetPath);

            if (result.ok) {
                logger.storeUpdates.success(`Successfully migrated read later for (${galleryPath}) to (${migrationTargetPath})`);
                gotoPage(migrationTargetPath, 1); // potential issue that data can be changed since modal is still open. keep number low, until proper fix
                notifier.info('Read Later migrated. Switching to new page.');
            } else {
                reportPatchFail(result);
            }
        }

        function savePriority() {
            const newPriority = parsePriority(priorityField.value);
            if (newPriority == null) {
                reportInputInvalidIssue('Read priority is invalid! How did you manage that?', newPriority);
                return;
            }

            const result = patchReadLater(galleryPath, { 
                read_priority: newPriority,
            });

            if (!result.ok) {
                reportPatchFail(result);
            }
        }

        function addLabel(labelName) {
            const label = parseLabel(labelName);
            if (!label) {
                return;
            }

            const result = patchReadLater(galleryPath, { 
                labels: { op: 'push', value: label, unique: true },
            });

            if (!result.ok) {
                reportPatchFail(result);
            }
        }

        function removeLabel(labelName) {
            const label = parseLabel(labelName);
            if (!label) {
                return;
            }

            const result = patchReadLater(galleryPath, { 
                labels: { op: 'remove', id: label },
            });

            if (!result.ok) {
                reportPatchFail(result);
            }
        }

        function handleRemoveClick() {
            // remove from read later
            dataStore.readLater.load();
            dataStore.readLater.value.delete(galleryPath);
            logger.storeUpdates.log(`Gallery ${galleryPath} removed from read later list.`);
            dataStore.readLater.save();
            closeModal?.();
            onRemove?.();
        }

        migrationField.append(safetyLock, input, submitButton);
        root.append(migrationField, priorityField, labelsField, removeButtonWrapper);

        closeModal = makeModal({
            headerContent: 'Read Later',
            content: root,
        });
    }
    function showEditBrowseLaterModal(pageId, onRemove = null) {
        const initialBrowseLaterData = dataStore.browseLater.value.get(pageId);
        if (!initialBrowseLaterData) {
            return null;
        }

        const root = createElement('div', { className: 'nhcb-browse-later-modal' });
 
        //const nameField = createFieldLayout();
        const priorityField = createDropdownField({
            labelContent: 'Browse Priority',
            tooltipInfo: 'Set a priority to order what should be browsed first.',
            options: DEFAULTS.PRIORITY_DROPDOWN_OPTIONS,
            initialValue: initialBrowseLaterData.browse_priority,
            useSafetyLock: false,
            lockSubmitIfUnchanged: true,
            useSubmitButton: false,
            onCommit: savePriority,
        })
        const labelsField = createLabelsField({ availableLabels: [...settingsStore.labels.value], initialLabels: initialBrowseLaterData.labels, onLabelAdd: addLabel, onLabelRemove: removeLabel });
        const notesField = createNotesField({ textAreaClassName: 'nhcb-browse-later-note-field', maxLength: DEFINITIONS.BROWSE_LATER_NOTES_MAX_LENGTH, initialValue: initialBrowseLaterData.note, viewModePlaceholder: 'No Note', onSaveClick: handeleNotesSave });
        const removeButtonWrapper = createElement('div', { style: 'margin-top: 12px;' });
        const removeButtonLock = createSafetyLock({ onChange: (isLocked) =>  { removeButton.disabled = isLocked; } });
        const removeButton = createButton({ content: 'Remove Browse Later', disabled: true, buttonStyle: 'primary', onClick: handleRemoveClick });
        removeButtonWrapper.append(removeButtonLock, removeButton);
        let closeModal;

        function savePriority() {
            const newPriority = parsePriority(priorityField.value);
            if (newPriority == null) {
                reportInputInvalidIssue('Browse priority is invalid! How did you manage that?', newPriority);
                return;
            }

            const result = patchBrowseLater(pageId, { 
                browse_priority: newPriority,
            });

            if (!result.ok) {
                reportPatchFail(result);
            }
        }

        function addLabel(labelName) {
            const label = parseLabel(labelName);
            if (!label) {
                return;
            }

            const result = patchBrowseLater(pageId, { 
                labels: { op: 'push', value: label, unique: true },
            });

            if (!result.ok) {
                reportPatchFail(result);
            }
        }

        function removeLabel(labelName) {
            const label = parseLabel(labelName);
            if (!label) {
                return;
            }

            const result = patchBrowseLater(pageId, { 
                labels: { op: 'remove', id: label },
            });

            if (!result.ok) {
                reportPatchFail(result);
            }
        }

        function handeleNotesSave(input) {
            const newNotesValue = parseValidString(input, { maxLengthInclusive: DEFINITIONS.BROWSE_LATER_NOTES_MAX_LENGTH, cuttoffAfterMax: true, trim: true, onlyTrimIfAllWhitespace: true });

            if (newNotesValue == null) {
                reportInputInvalidIssue('Umm, somehow you mananged to enter an invalid note. Probably a bug.', input);
                return;
            }

            const result = patchBrowseLater(pageId, { note: newNotesValue });

            if (result.ok) {
                return newNotesValue;
            } else {
                reportPatchFail(result);
            }
        }

        function handleRemoveClick() {
            // remove from browse later
            dataStore.browseLater.load();
            dataStore.browseLater.value.delete(pageId);
            logger.storeUpdates.log(`Page ${pageId} removed from browse later list.`);
            dataStore.browseLater.save();
            closeModal?.();
            onRemove?.();
        }

        root.append(priorityField, labelsField, notesField, removeButtonWrapper)

        closeModal = makeModal({
            headerContent: 'Browse Later',
            content: root,
        });
    }
    //#endregion
    //#endregion

    //#region -- Control Loop -----------------------------------------
    //#region Apply
    // All changes should check if the changes it is going to make are allready there
    function applyChanges() {
        logger.controlLoop.debug('Control Loop: Applying changes');

        callIfSettingEnabled(settingsStore.bypassAgeGate,                                 bypassAgeGate);

        // apply to nav bar
        callIfSettingEnabled(settingsStore.addNavBarToErrorPages,                         addNavBarToErrorPage);
        applyCustomNavLinks(); // missing setting but how do setting without acidentally foot shooting
        callIfSettingEnabled(settingsStore.groupTagNavLinks,                              moveTagLinksIntoMenu);
        callIfSettingEnabled(settingsStore.enableNavDropdownFix,                          applyNavDropdownNotClosingFix);

        // apply to all galleries on page
        if (cachedPageEls.galleries.size > 0) {
            callIfSettingEnabled(settingsStore.enableViewSystemBadge,                     applyViewSystemBadge);
            callIfSettingEnabled(settingsStore.enableFavoriteGalleryBadge,                applyFavoriteGalleryBadge);
            applyAltSourceBadge(); // doesn't need setting
            applyThumbnailAltCoverReplacement(); // doesn't need setting
            callIfSettingEnabled(settingsStore.displayCustomTitles,                       applyCustomGalleryTitleToLists);
            callIfSettingEnabled(settingsStore.enablePrettyTitleLists,                    applyGalleryListsPrettyTitles);
        }

        // apply to all tag lists on page
        if (cachedPageEls.tags.size > 1) {
            callIfSettingEnabled(settingsStore.enableBrowseSystemBadges,                  applyTagBrowseBadges);
            callIfSettingEnabled(settingsStore.enableAutoPipeFix,                         applyTagPipeFix);
        }

        // apply to all non-custom pages
        if (!pageData.isCustomPage()) {
            callIfSettingEnabled(settingsStore.enableAutoLogin,                           autoNavToLogin);
            callIfSettingEnabled(settingsStore.enableAutoRefreshRateLimitGallery,         rateLimitAutoRefresh);
            callIfSettingEnabled(settingsStore.enableAutoRefreshCloudflareGallery,        cloudflareAutoRefresh); // could be problematic
        }

        switch (pageData.type) {
            case PAGE_TYPES.HOME: {
                callIfSettingEnabled(settingsStore.enableJumpToPageOnElipsis,             addJumpToPagePagination);
                callIfSettingEnabled(settingsStore.enableArrowKeyNavigationForPagination, addArrowKeyNavigationForPagination);
                break;
            }
            case PAGE_TYPES.TAG_LIST: {
                callIfSettingEnabled(settingsStore.enableJumpToPageOnElipsis,             addJumpToPagePagination);
                callIfSettingEnabled(settingsStore.enableArrowKeyNavigationForPagination, addArrowKeyNavigationForPagination);
                break;
            }
            case PAGE_TYPES.GALLERY: {
                callIfSettingEnabled(settingsStore.autoSeenIfVisited,                     applyAutoMarkCurrentGalleryAsSeen); // before seen button
                callIfSettingEnabled(settingsStore.enableCustomFavoritesButton,           applyCustomFavoriteButton); // although uses api, not dependent for creation
                callIfSettingEnabled(settingsStore.enableTryAnotherSiteButton,      () => injector.injectElement(createTryAnotherSiteButton, '.buttons', '#nhcb-try-another-site'));
                callIfSettingEnabled(settingsStore.enableCustomFavoritesButton,     () => injector.injectElement(createCustomizeFavoriteButton, '.buttons', '#nhcb-customize-favorites-button'));
                callIfSettingEnabled(settingsStore.enableViewSystemButtons,         () => injector.injectElement(createViewSystemButtons, '.buttons', '#nhcb-view-system-buttons'));
                applyPreviewAltCoverReplacement();  // probably doesn't need setting
                callIfSettingEnabled(settingsStore.enableTagSentimentHighlights,          applyTagSentimentHightlight);
                callIfSettingEnabled(settingsStore.enableGalleryCustomInfo,               applyCustomGalleryInfo);
                callIfSettingEnabled(settingsStore.displayCustomTitles,                   applyCustomGalleryTitleToGalleryPage);
                applyAltSourceNudge();              // probably doesn't need seting
                bypassTaxonomyAgreement();          // setting logic handled in function
                break;
            }
            case PAGE_TYPES.READER: {
                callIfSettingEnabled(settingsStore.readerEnableImprovedZoom,              applyReaderImprovedZoom);
                callIfSettingEnabled(settingsStore.readerEnableFullscreen,                applyFullScreenChanges);
                callIfSettingEnabled(settingsStore.readerDontExitOnArrowNav,              applyGalleryReaderKeyNavPreventExit);
                callIfSettingEnabled(settingsStore.enableReaderAutoPlayer,                applyAutoPlayer);
                break;
            }
            case PAGE_TYPES.NAMESPACE: {
                callIfSettingEnabled(settingsStore.enableJumpToPageOnElipsis,             addJumpToPagePagination);
                callIfSettingEnabled(settingsStore.enableArrowKeyNavigationForPagination, addArrowKeyNavigationForPagination);
                callIfSettingEnabled(settingsStore.copyTagOnClick,                        applyCopyTagSearchTermOnClick);
                callIfSettingEnabled(settingsStore.enableTagSentimentButtons,       () => injector.injectElement(createAddTagSentimentsButton, 'h1:has(.tagchip)', '#nhcb-tag-sentiment-edit'));
                callIfSettingEnabled(settingsStore.enableBrowseSystemButtons,       () => injector.injectElement(createBrowseSystemButtons, 'h1:has(.tagchip)', '#nhcb-browse-system-buttons'));
                callIfSettingEnabled(settingsStore.enableSortPopularMonthButton,    () => injector.injectElement(createSortPopularMonthButton, '.sort-type:has(.sort-name)', '#nhcb-popular-month', -2));
                callIfSettingEnabled(settingsStore.enableEnglishOnlyButton,         () => injector.injectElement(createEnglishOnlyButton, '.sort', '#nhcb-english-only'));
                callIfSettingEnabled(settingsStore.enableFixPipeButton,             () => injector.injectElement(createFixPipeButton, '.sort', '#nhcb-fix-pipe'));
                callIfSettingEnabled(settingsStore.hideGtsDescriptionIfNone,              applyHideEmptyGtsDescription);
                //callIfSettingEnabled(settingsStore.enableBrowseSystemBadges, applyTagBrowseBadges);
                break;
            }
            case PAGE_TYPES.SEARCH: {
                callIfSettingEnabled(settingsStore.enableJumpToPageOnElipsis,             addJumpToPagePagination);
                callIfSettingEnabled(settingsStore.enableArrowKeyNavigationForPagination, addArrowKeyNavigationForPagination);
                callIfSettingEnabled(settingsStore.enableSortPopularMonthButton,    () => injector.injectElement(createSortPopularMonthButton, '.sort-type:has(.sort-name)', '#nhcb-popular-month', -2));
                callIfSettingEnabled(settingsStore.enableEnglishOnlyButton,         () => injector.injectElement(createEnglishOnlyButton, '.sort', '#nhcb-english-only'));
                callIfSettingEnabled(settingsStore.addTagChipFromSearch,                  applyAddTagChipIfOnlyOneTerm);
                if (cachedPageEls.tags.size > 0) {
                    callIfSettingEnabled(settingsStore.enableBrowseSystemBadges,          applyTagBrowseBadges);
                    callIfSettingEnabled(settingsStore.copyTagOnClick,                    applyCopyTagSearchTermOnClick);
                }
                break;
            }
            case PAGE_TYPES.CUSTOM: {
                // do not apply custom pages here
                // they basically create the page so they need to be ran separately
                applyCustomPageNavHighlight();
                callIfSettingEnabled(settingsStore.enableJumpToPageOnElipsis,             addJumpToPagePagination);
                callIfSettingEnabled(settingsStore.enableArrowKeyNavigationForPagination, addArrowKeyNavigationForPagination);
                break;
            }
            case PAGE_TYPES.LOGIN: {
                callIfSettingEnabled(settingsStore.enableAutoFillForLogin,                autoFillLogin);
                break;
            }
            case PAGE_TYPES.USER_FAVORITES: {
                callIfSettingEnabled(settingsStore.enableJumpToPageOnElipsis,             addJumpToPagePagination);
                callIfSettingEnabled(settingsStore.enableArrowKeyNavigationForPagination, addArrowKeyNavigationForPagination);
                break;
            }
            case PAGE_TYPES.UNKNOWN:
            default:
                break;
        }
    }
    // changes that depend on api are done separately to make it more responsive
    function applyApiDependentChanges() {
        logger.controlLoop.debug('Control Loop: Applying api dependent changes');
        
        // apply to all galleries on page
        if (cachedPageEls.galleries.size > 0) {
            callIfSettingEnabled(settingsStore.enableContentWarningBadge, applyContentWarningBadge);
            applyInfoBadge(); // visbility controlled by sub elements
            applyMultiLanguageEnglishFlag(); // fixMultiLanguageGalleries setting, logic handled in function
        }

        switch (pageData.type) {
            case PAGE_TYPES.GALLERY:
                callIfSettingEnabled(settingsStore.enableBadgesOnBigCover, applyGalleryCoverBadges);
                break;
            default:
                break;
        }
    }
    async function applyCustomPages() {
        if (pageData.isCustomPage()) {
            logger.controlLoop.debug('Control Loop: Applying custom page');
            removeError404();
            addPageBase();

            const customPage = CUSTOM_PAGES.get(pageData.path);

            if (customPage) {
                setCutomPageTitle(customPage.title);
                customPage.handler();
            } else {
                // need to use changeId workflow because notifier was causing infinite loops
                // had to target something outside of app because the changeId would get wiped depending on injection timing
                injector.injectChange('nhcb-missing-custom-page', 'div', (target) => {
                    reportIssue('MISSING_CUSTOM_PAGE_ROUTE', { pagePath: pageData.path }, null);
                })
            }
        } else if (pageData.isGalleryPage()) {
            await CUSTOM_PAGES.SPECIAL_PAGES.RECOVERY_404.asyncHandler()
        }
    }
    //#endregion

    //#region Context Menu
    function registerContextMenuCommands() {
        // goto settings
        GM_registerMenuCommand('Download Backup', exportDataToFile);
        GM_registerMenuCommand("Clear Cached Api Requests For Page", commandClearRequestCacheForPage);
        GM_registerMenuCommand("Clear All Cached Api Requests", commandClearRequestCache);
    }
    function commandClearRequestCache() {
        const count = localStore.cachedApiRequests.value.size;
        localStore.cachedApiRequests.value = new Map();
        localStore.cachedApiRequests.save();
        logger.storeUpdates.success(`Cleared ${count} item${count != 1 ? 's' : ''} in request cache.`);
    }
    function commandClearRequestCacheForPage() {
        let count = 0;
        const pageNumber = pageData.searchParams.get('page') ?? undefined;
        const sort = pageData.searchParams.get('sort') ?? undefined;

        localStore.cachedApiRequests.load();
        
        switch (pageData.type) {
            case PAGE_TYPES.HOME: {
                if (pageNumber == 1) {
                    count += localStore.cachedApiRequests.value.delete(apiEndpoints.popularGalleries.buildUrl());
                }
                count += localStore.cachedApiRequests.value.delete(apiEndpoints.galleries.buildUrl(pageNumber));
                break;
            }
            case PAGE_TYPES.GALLERY: {
                count += localStore.cachedApiRequests.value.delete(apiEndpoints.gallery.buildUrl(pageData.galleryId));
                break;
            }
            case PAGE_TYPES.NAMESPACE: {
                const tagId = cachedApiData.tags.get(pageData.path).id;
                if (tagId) {
                    count += localStore.cachedApiRequests.value.delete(apiEndpoints.taggedGalleries.buildUrl(tagId, pageNumber, sort));
                }
                count += localStore.cachedApiRequests.value.delete(apiEndpoints.tag.buildUrl(pageData.tagInfo.type, pageData.tagInfo.name));
                break;
            }
            case PAGE_TYPES.SEARCH: {
                count += localStore.cachedApiRequests.value.delete(apiEndpoints.searchGalleries.buildUrl(pageData.query, pageNumber, sort));
                break;
            }
            default:
                break;
        }

        localStore.cachedApiRequests.save();
        logger.storeUpdates.success(`Cleared ${count} item${count != 1 ? 's' : ''} in request cache.`);
    }
    //#endregion

    //#region Debug Commands
    function registerDebugComannds() {
        unsafeWindow.__nhcbStoreValue = debugLogStoreValue;
        unsafeWindow.__nhcbLoggerModuleLevel = debugChangeLoggerModuleLevel;
    }
    function debugLogStoreValue(/** @type {string} */ storeKey, /** @type {string} */ fieldName, /** @type {string} */ key = null) {
        const stores = {
            secret: secretStore,
            data: dataStore,
            local: localStore,
            session: sessionStore,
            tmpData: tmpDataStore
        };
        const store = stores[storeKey];
        if (!store) {
            logger.debug(`Store ${storeKey} doesn't exist.`)
            return;
        }
        if (!store.hasField(fieldName)) {
            logger.debug(`Store ${storeKey} has no field ${fieldName}.`);
            return;
        } 
        const field = store[fieldName];

        if (key == null) {
            field.logValue();
        } else {
            if (field.value instanceof Map) {
                logger.debug(`Map ${fieldName} entry ${key}:`, field.value.get(key));
            }
            if (field.value instanceof Set) {
                logger.debug(`Set ${fieldName} key ${key}:`, field.value.has(key) ? key : undefined);
            } else {
                logger.debug(`Object ${fieldName} key ${key}:`, field.value[key]);
            }
        }
    }
    function debugChangeLoggerModuleLevel(/** @type {string} */ moduleName = null, /** @type {string} */ levelName = null) {
        const logLevelValueToName = (value) => Object.keys(logger.LEVELS).find(key => logger.LEVELS[key] === value);
        if (moduleName == null) {
            // map log level value to name
            const formattedModules = Object.fromEntries(Object.entries(logger.MODULES).map(([name, value]) => [name, logLevelValueToName(value)]));
            logger.info(formattedModules);
            return;
        }
        if (!Object.hasOwn(logger.MODULES, moduleName)) {
            logger.error(`Module "${moduleName}" is not a valid module.`);
            return;
        }
        if (levelName == null) {
            const levelValue = logger.MODULES[moduleName];
            const levelName = logLevelValueToName(levelValue);
            logger.info(`${moduleName}: ${levelName}`);
            return;
        }
        if (levelName === 'CLEAR') {
            const loggerOverrides = GM_getValue('DEBUG_ModuleLevels', {});
            loggerOverrides[moduleName] = null;
            GM_setValue('DEBUG_ModuleLevels', loggerOverrides);
            logger.info(`Cleared ${moduleName}`);
            return;
        } else if (!Object.hasOwn(logger.LEVELS, levelName)) {
            logger.error(`Level "${levelName}" is not a valid log level.`);
            return;
        }
        const loggerOverrides = GM_getValue('DEBUG_ModuleLevels', {});
        loggerOverrides[moduleName] = logger.LEVELS[levelName];
        GM_setValue('DEBUG_ModuleLevels', loggerOverrides);
        logger.info(`Set ${moduleName} to ${levelName}`);
    }
    //#endregion

    //#region Update
    async function update() {
        if (pageData.key != pageData.createKey()) {
            logger.controlLoop.info('Control Loop: Navigated to new page:', prettyUrl(pageData.createKey()));
            logger.controlLoop.verbose('Control Loop: Cleanup Task Count:', cleaner.count);
            cleaner.cleanup();
            pageData.refresh();
            await userData.refreshData();
            logger.controlLoop.verbose('Control Loop: Page Data Refreshed.', pageData);
            loadData();
            calculatedData.recalculate();
            await applyCustomPages();
            cachedPageEls.cacheElementsOnPage();
            notifier.reinjectElement();
            if (!pageData.isNonStandardLayout()) {
                makeApiCallsForPage().then(() => applyApiDependentChanges());
                pageData.layoutDepenenciesInitialized = true;
            }
            await applyChanges();
        }
        else {
            logger.controlLoop.debug('Control Loop: Update');
            await applyCustomPages();
            cachedPageEls.cacheElementsOnPage();
            notifier.reinjectElement();
            // this check was added to fix some optimizations breaking on non standard layouts
            // non standard layouts being error pages, cloudflare, or age gate
            // basically it wouldn't find any galleries on page, so it wouldn't make api calls
            // it wouldn't fix itself once cleared because script thinks its still the same page bc its based on url
            // couldn't change that method because there is other stuff that makes changes to those pages
            // more of a hacky solution but better than having to revalidate all changes after fixing loop logic
            if (!pageData.layoutDepenenciesInitialized && !pageData.isNonStandardLayout()) {
                makeApiCallsForPage().then(() => applyApiDependentChanges());
                pageData.layoutDepenenciesInitialized = true;
            }
            await applyChanges();
            applyApiDependentChanges();
        }
    }
    //#endregion

    //#region On Immediate
    // runs as soon as possible, similar to tamper monkey's run-at docuemnt-start (which is what this script runs at)
    async function onDocumentImmediate() {
        logger.controlLoop.debug('Control Loop: onDocumentImmediate');
        secretStore.apiKey.load();
        applyMonkeypatch();
        addInitialPageRequestToCache();
        logger.controlLoop.success('NHCB is active');
    }
    //#endregion

    //#region On Load
    // equivalent to tamper monkey's run-at docuemnt-idle
    async function onDocumentLoad() {
        logger.controlLoop.debug('Control Loop: onDocumentLoad');
        registerDebugComannds();
        registerContextMenuCommands();
        addStyles();
        await checkDataVersion();

        await update();
        new MutationObserver(async () => {
            await update();
        }).observe(document.body, { childList: true, subtree: true });
    }
    //#endregion
    
    //#region Data Updates
    async function checkDataVersion() {
        const storedVersion = metaStore.dataVersion.load();
        switch (storedVersion) {            
            // case version latest
            case APP_INFO.DATA_VERSION:
                break;
            // I forgot to call the save function, this is a special case for the original default
            // Since it was never saved, there is no refence for past installs. Meaning that data could be a fresh install or an old one.
            // For now the way its going to be handled is that the old default will be used until you can reasonably assume that the all previous installs are patched. (1 year from now, Oct 2027. currently ~20 installs)
            // After that time, the new default will be used
            case '':
                await initiateDataUpdate('1.0');
                break;
            // case needs updates
            case '1.0':
                await initiateDataUpdate(storedVersion);
                break;
            // case uninitialized (first run)
            case 'default':
            default:
                metaStore.dataVersion.value = APP_INFO.DATA_VERSION;
                metaStore.dataVersion.save();
                break;
        }
    }
    async function initiateDataUpdate(oldDataVersion) {
        /** @type {{ background: boolean, nextVersion: string, run: () => Promise<boolean> }} */
        const migrationConfig = MIGRATION_CONFIGS[oldDataVersion];

        if (!migrationConfig) {
            notifier.reinjectElement();
            notifier.error(`Cannot update stored data, missing migration config. If you messed with the data version, don't! Otherwise, something has gone wrong. No migration config for "${oldDataVersion}", current data version is "${metaStore.dataVersion.value}".`);
            return;
        }
        
        if (metaStore.migrationLock.value > Date.now()) {
            if (!migrationConfig.background) {
                // ehh Ill do this later when I actually need it
            }
            return;
        }
        const lockTtl = 16000;
        const lockRefresh = 5000;
        const refeshMigrationLock = () => { metaStore.migrationLock.value = Date.now() + lockTtl; metaStore.migrationLock.save(); }
        refeshMigrationLock();
        const hb = setInterval(refeshMigrationLock, lockRefresh);
        const clearHeartBeatInterval = () => clearInterval(hb);
        function handleMigrationResolve(successful) {
            if (successful) {
                metaStore.dataVersion.value = migrationConfig.nextVersion;
                metaStore.dataVersion.save();
                notifier.info(`Update for data from "${oldDataVersion}" to "${migrationConfig.nextVersion}" has completed successfully.`);

            } else {
                notifier.error(`Update for data from "${oldDataVersion}" to "${migrationConfig.nextVersion}" has failed. This means that there is a bug. Either report the issue or see if it can fix itself by refreshing the page and trying again.`);
            }
        }
        if (migrationConfig.background) {
            migrationConfig.run().then(handleMigrationResolve).finally(clearHeartBeatInterval);
        } else {
            try {
                const successful = await migrationConfig.run();
                handleMigrationResolve(successful);
            } finally {
                clearHeartBeatInterval();
            }
        }
    }
    const MIGRATION_CONFIGS = {
        '1.0': {
            background: true,
            nextVersion: '1.1',
            async run() {
                dataStore.browseLater.load();
                const browseLaterNeedingUpdates = [...dataStore.browseLater.value.entries()].filter(([pageId, browseLaterData]) => !(browseLaterData.not_tag === true || browseLaterData.tag_id != undefined)).map(([pageId, browseLaterData]) => pageId);
                let progress = 0;
                let end = browseLaterNeedingUpdates.length;
                if (end === 0) {
                    return true;
                }

                notifier.info('Some stored data needs to be updated to support new features. API calls will be made in the background to add missing info for Browse Later. You can use the script as normal but you should try to keep this tab open. You may encounter rate limits for searches and tags.', 60);

                const reportDelaySeconds = 10;
                const reportProgress = () => notifier.info(`Update Progress: ${Math.round((progress / end) * 100)}% (${progress}/${end})`, reportDelaySeconds);
                const reportingInterval = setInterval(reportProgress, reportDelaySeconds * 1000);
                reportProgress();

                try {
                    while (browseLaterNeedingUpdates.length > 0) {
                        const pageId = browseLaterNeedingUpdates.splice(0, 1)[0];
                        if (!dataStore.browseLater.load().has(pageId)) {
                            progress++;
                            continue;
                        }
                        await sleep(3000);
                        const tagData = await getOrPullTagCacheData(pageId);
                        if (!tagData) {
                            browseLaterNeedingUpdates.push(pageId);
                            logger.info('Update for 1.0. No tag data for:', pageId, tagData)
                            continue;
                        }
                        const result = patchBrowseLater(pageId, { name: tagData.name, tag_id: tagData.id });
                        if (!result.ok && result.issue !== 'BROWSE_LATER_MISSING') {
                            browseLaterNeedingUpdates.push(pageId);
                            reportPatchFail(result);
                            continue;
                        }
                        progress++;
                    }
                } finally {
                    clearInterval(reportingInterval);
                }
                return true;
            }
        },
        '1.1': {
            background: true,
            nextVersion: '1.1',
            async run() {
                return true;
            }
        }
    }
    //#endregion
    //#endregion


    //#region -- Helpers --------------------------------------------
    // todo clean this
    // ask about opts vs { myOption = false } = {}
    // maybe just js doc
    function applyChange(target, id, fn, opts = {}) {
        const el = typeof target === 'string' ? document.querySelector(target) : target;
        if (!el) return false;

        // "already applied?" — class marker by default, or a custom check
        const done = opts.isApplied ? opts.isApplied(el) : (id && el.classList.contains(id));
        if (done) return false;

        // extra elements that must also exist for the change to make sense
        let deps;
        if (opts.require) {
            deps = opts.require.map(s => typeof s === 'string' ? document.querySelector(s) : s);
            if (deps.some(d => !d)) return false;
        }

        if (id) el.classList.add(id);
        const extra = fn?.(el, deps);          // fn may return its own undo fn

        if (!opts.noCleanup) {
            cleaner.addTask(el, (t) => {           // t is your target, existence already checked
            if (id) t.classList.remove(id);
                extra?.(t);
            });
        }
        return true;
    }
    function applyClass() {

    }

    //#region Other
    /**
     * @param {FactoryChild} target 
     * @param {(e: FocusEvent) => void} callback 
     */
    function addClickOutsideEvent(target, callback) {
        const targetEl = factoryUnwrapEl(target);
        targetEl.addEventListener('focusout', (e) => {
            if (!targetEl.contains(e.relatedTarget)) {
                callback?.(e);
            }
        });
    }
    /**
     * Extracts search terms from a string.
     * ```
     * "key:info"           -> [{ key: "key", info: "info" }]
     * "info"               -> [{ key: null,  info: "info" }]
     * 'key: "a b" c key:d' -> [{ key: "key", info: "a b" },
     *                          { key: null,  info: "c" },
     *                          { key: "key", info: "d" }]
     * "-key:info"          -> [{ key: "key", info: "info", negated: true }]
     * '-k:"foo-bar"'       -> [{ key: "k", info: "foo-bar", negated: true }]
     * ```
     * @param {string} input
     * @returns {SearchTerm[]}
     */
    function extractSearchTerms(input) {
        const SPACE = 32;
        const TAB = 9;
        const NL = 10;
        const CR = 13;
        const QUOTE = 34;
        const COLON = 58;
        const DASH = 45;
        function isSpace(c) {
            return c === SPACE || c === TAB || c === NL || c === CR || c === DASH;
        }
        function isValidDashPredecessor(c) {
            return c === SPACE || c === TAB || c === NL || c === CR || Number.isNaN(c);
        }


        const output = [];
        const end = input.length;
        let i = 0;
        
        // loop: look for key, look for value, repeat
        while (i < end) {
            // Skip leading whitespace.
            while (i < end && isSpace(input.charCodeAt(i))) {
                i++;
            }
            // if end reached, stop
            if (i >= end) {
                break;
            }
        
            let termStart = i;
            let negated = false;
            let key = null;
            let colonIndex = -1;
            let open = false;

            if (input.charCodeAt(i-1) === DASH && isValidDashPredecessor(input.charCodeAt(i-2))) {
                negated = true;
            }
        
            // Look for a key (some look ahead)
            // if first char is quote, skip
            if (input.charCodeAt(i) !== QUOTE) {
                let probe = i; // use probe to look for (colon) or (space or quote)
                while (probe < end) {
                    const charCode = input.charCodeAt(probe);
                    // if colon found, extract key
                    if (charCode === COLON) {
                        if (probe > termStart) {
                            key = input.slice(termStart, probe);
                            colonIndex = probe;
                            i = probe + 1;
                            // Allow whitespace between the colon and the value.
                            while (i < end && isSpace(input.charCodeAt(i))) {
                                i++;
                            }
                        }
                        break;
                    }
                    // if space or quote found (and colon not found), abandon search for key
                    if (isSpace(charCode) || charCode === QUOTE) {
                        break;
                    }
                    probe++;
                }
            }
        
            // Look for value
            let value;
            // if quote opened
            if (i < end && input.charCodeAt(i) === QUOTE) {
                i++;
                const valueStart = i;
                // look ahead for closing quote
                while (i < end && input.charCodeAt(i) !== QUOTE) {
                    i++;
                }
                // if reached this point, quote found or end reached
                value = input.slice(valueStart, i);
                // if end not reached, consume closing quote
                if (i < end) {
                    i++;
                // else, stop search and treat it as unfinished (open)
                } else {
                    open = true;
                }
            // else if no quote
            } else {
                const valueStart = i;
                // look ahead of space or stop at end
                while (i < end && !isSpace(input.charCodeAt(i))) {
                    i++;
                }
                value = input.slice(valueStart, i);
            }
        
            // push results to output
            if (value !== "" || key !== null) {
                output.push({ key, value, negated, start: termStart + (negated ? -1 : 0), end: i, colon: colonIndex, open });
            }
        }
    
        return output;
    }
    /**
     * Extracts search terms from a string while also finding the term currently selected by the caret.
     * @param {string} input 
     * @param {int?} caret
     * @returns {{ terms: SearchTerm[], activeTerm: SearchTerm?, activeTermIndex: int | -1, caretIn: "key"|"info"|null }}
     */
    function extractSearchTermsWithCaret(input, caret = input.length) {
        const caretIndex = clamp(caret, 0, input.length);
        const terms = extractSearchTerms(input);
        
        let activeTermIndex = -1;
        for (let i = 0; i < terms.length; i++) {
            // this is for special case where there are multiple spaces that encose the caret
            // "foo | bar"
            // it technically doesn't correspond to either. could make an arbitrary tie breaker, but chosen to leave as is
            if (terms[i].start > caretIndex) {
                break;
            }
            // terms are ordered sequetially, so end eventually will come after and enclose the caret
            if (caretIndex <= terms[i].end) {
                activeTermIndex = i;
                break;
            }
        }
        
        const activeTerm = activeTermIndex === -1 ? null : terms[activeTermIndex];
        const caretIn = !activeTerm
            ? null
            : activeTerm.colon !== -1 && caretIndex <= activeTerm.colon
            ? "key"
            : "info";
        
        return { terms, activeTerm, activeIndex: activeTermIndex, caretIn };
    }

    function timeIt(label, fn, runs = 1000) {
        const start = performance.now();
        for (let i = 0; i < runs; i++) {
            const result = fn();
        };
        const elapsed = (performance.now() - start) / runs;
        console.log(`${label} took ${elapsed.toFixed(3)}ms`);
    }
    /**
     * 
     * @param {StoreField<boolean>} settingField 
     * @param {()=>{}} func 
     */
    function callIfSettingEnabled(settingField, func) {
        if (settingField.value) {
            func();
        }
    }
    /**
     * 
     * @param {string} url
     * @param {int} timeoutMs
     * @returns {Promise<{width: number, height: number}|null>}
     */
    function getImageSize(url, timeoutMs = 15000) {
        return new Promise((resolve) => {
            const img = new Image();
            const timer = setTimeout(() => resolve(null), timeoutMs);
            const done = (value) => { clearTimeout(timer); resolve(value); };
            img.onload = () => done({ width: img.naturalWidth, height: img.naturalHeight });
            img.onerror = () => done(null);
            img.src = url;
        });
    }

    /**
     * Use `signal.throwIfAborted();` to exit early if aborted.
     * 
     * Use `defer(() => action)` to do stuff after the task finishes or is aborted.
     * 
     * @param {(ctx: {signal: AbortSignal, defer: () => void | Promise<void>}, ...args) => Promise} task
     */
    function createAbortableTask(task) {
        let controller = null;
        let inflight = null;

        function run(...args) {
            if (inflight) {
                return inflight;
            }

            controller = new AbortController();
            const { signal } = controller;
            const cleanups = [];
            const ctx = { signal, defer: (fn) => cleanups.push(fn) };

            inflight = (async () => {
            try {
                return await task(ctx, ...args);
            } finally {
                for (const cleanup of cleanups.reverse()) {
                    await cleanup();
                }
                inflight = null;
                controller = null;
            }
            })();

            inflight.catch(() => {});
            return inflight;
        }

        return {
            run,
            abort: (reason) => controller?.abort(reason),
            get running() { return inflight !== null; },
        };
    }
    function sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }
    //#endregion

    //#region Math
    /**
     * @param {number} number
     * @param {number} min
     * @param {number} max
     * @returns {number} Returns a the number clamped between the min and max values.
     */
    function clamp(number, min, max) {
        return Math.max(min, Math.min(number, max));
    }
    /**
     * @param {int} min 
     * @param {int} max 
     * @returns {int} Returns random int between min and max (inclusive).
     */
    function getRandomInt(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }
    /**
     * @param {int} min 
     * @param {int} max 
     * @returns {int} Returns random float between min and max (inclusive).
     */
    function getRandomFloat(min, max) {
        return Math.random() * (max - min) + min;
    }
    /**
     * @param {int} number 
     * @returns {boolean|null} Returns true if odd, false if even, or null if not an integer.
     */
    function isOdd(number) {
        return Number.isInteger(number) ? (number % 2 !== 0) : null;
    }
    //#endregion

    //#region Timestamps
    /**
     * @returns {UnixSeconds} Returns a timestamp in unix seconds of the current time.
     */
    function getUnixTimestamp() {
        return Math.floor(Date.now() / 1000);
    }
    /**
     * @param {Date} date 
     * @returns {UnixSeconds} Returns a timestamp in unix seconds of the current time.
     */
    function getUnixTimestampFromDate(date) {
        return Math.floor(date.getTime() / 1000);
    }
    /**
     * @param {UnixSeconds} unixTimestamp Timestamp to convert.
     * @returns {Date}
     */
    function getDateFromUnixTimestamp(unixTimestamp) {
        return new Date(unixTimestamp * 1000);
    }
    //#endregion

    //#region Objects and Arrays
    /**
     * Takes in a value and makes it into an array if it isn't already one.
     * @template V
     * @param {V} val 
     * @returns {V[]|V} If `val` is null or undefined, an empty array is returned.
     */
    function toArray(val) {
        // holy gigachad
        // even if it doesn't correctly unpack iterators, this is a fantastic helper
        if (Array.isArray(val)) {
            return val;
        }
        if (val == null) {
            return [];
        }
        return [val];
    }
    /**
     * Creates a deep copy of any JSON serializable object.
     * @param {object} obj
     * @returns {object} Returns a deepy copy of the object.
     * @throws {SyntaxError|TypeError} If `obj` is not JSON serializable.
     */
    function objectDeepCopy(obj) {
        if (!obj) return null;
        return JSON.parse(JSON.stringify(obj));
    }
    function anyObjectPropertyNull(obj) {
        return Object.values(obj).some(val => val == null);
    }
    /**
     * Checks if two objects with primitive values are equal. This will not work for objects with nested objects or arrays.
     * @param {object} a 
     * @param {object} b 
     * @returns {boolean} Returns true if both objects have the same keys and values.
     */
    function objectsBasicEqual(a, b) {
        const keysA = Object.keys(a);
        const keysB = Object.keys(b);

        if (keysA.length !== keysB.length) {
            return false;
        }

        return keysA.every(k => a[k] === b[k]);
    }
    //#endregion

    //#region Navigation
    /**
     * Navigates to the page after a given amount of seconds.
     * @param {string} pagePath Path to go to
     * @param {number} delaySeconds Seconds, can be float,
     */
    function gotoPage(pagePath, delaySeconds = 0) {
        if (!pagePath) {
            return;
        }

        // done this way to prevent html requests and for isntead for svelte to handle the data fetching (reduce api calls)
        function executeGoto(pagePath) {
            const a = document.createElement('a');
            a.href = pagePath;
            document.body.appendChild(a); // must be in the DOM
            a.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: unsafeWindow }));
            a.remove();
        }

        if (delaySeconds > 0) {
            const initialPagePath = pageData.path;
            setTimeout(() => {
                if (initialPagePath === pageData.path) {
                    executeGoto(pagePath);
                }
            }, Math.ceil(delaySeconds * 1000));
        } else {
            executeGoto(pagePath);
        }
    }
    /**
     * Refreshes the page after the given amount of seconds.
     * @param {number} delaySeconds Seconds, can be float.
     */
    function refreshPage(delaySeconds = 0) {
        gotoPage(pageData.path, delaySeconds);
    }
    //#endregion

    //#region Urls
    /**
     * Builds a relative link with the updated params and returns a string.
     * @example
     * buildLink({ setParams: { sort: 'date' } })                                  // set sort=date
     * buildLink({ setParams: { sort: 'date' }, deleteParams: 'page' })            // remove page
     * buildLink({ setParams: { sort: 'date' }, deleteParams: ['page', 'other'] }) // remove multiple
     * @param {Object} options
     * @param {Record<string, string|number>} options.setParams Params to set on the URL.
     * @param {string | string[] | null} options.deleteParams Params to remove from the URL. Removed before additions.
     * @param {string | null} [options.newPath=null] Changes the path for the url.
     * @param {Boolean} [options.deleteAllParams=false] Removes all params before making changes.
     * @returns {string} The updated pathname + search string.
     */
    function buildUrl({ setParams = {}, deleteParams = [], newPath = null, deleteAllParams = false } = {}) {
        const url = new URL(location.href);
        // remove params
        if (deleteAllParams) {
            url.search = '';
        } else {
            toArray(deleteParams).forEach(excludeParam => url.searchParams.delete(excludeParam));
        }
        // add params
        Object.entries(setParams).forEach(([key, value]) => url.searchParams.set(key, value));
        // sort params
        if (url.searchParams.size > 1) {
            const sorted = new URLSearchParams();
            DEFINITIONS.NORMALIZED_SEARCH_PARAMS_ORDER.forEach(key => {
                if (url.searchParams.has(key)) {
                    sorted.set(key, url.searchParams.get(key));
                    url.searchParams.delete(key);
                }
            });
            for (const [key, value] of url.searchParams) {
                sorted.set(key, value);
            }
            url.search = sorted.toString();
        }
        // set path
        if (newPath) {
            url.pathname = newPath;
        }
        
        return url.pathname + url.search;
    }
    function normalizeUrl(urlStr) {
        const url = new URL(urlStr, location.origin);
        url.hash = '';

        if (!url.search) {
            return url.href;
        }

        if (url.searchParams.has('include')) {
            const sorted = url.searchParams
                .get('include')
                .split(',')
                .map(s => s.trim())
                .filter(Boolean)
                .sort()
                .join(',');
            url.searchParams.set('include', sorted);
        }

        // honestly don't remember why i did this for the params but it works so don't touch it
        const params = Array.from(url.searchParams.entries());
        const search = params
            .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
            .join('&');
        const normalized = url.origin + url.pathname + '?' + search;
        return normalized;
    }
    function prettyUrl(href) {
        let url;
        try {
            url = new URL(href, location.origin);
        } catch {
            return href; // Not a valid URL, return as-is
        }

        let pretty = url.pathname;
        if (url.search) {
            const decodedParams = [];
            for (const [key, value] of url.searchParams) {
                decodedParams.push(`${key}=${value}`);
            }
            pretty += '?' + decodedParams.join('&');
        }

        // Show full URL only if it's a different origin
        if (url.origin !== location.origin) {
            pretty = url.origin + pretty;
        }

        return pretty;
    }
    function prettyNormalUrl(urlStr) {
        // for real tho, I don't see whats so special about this url
        return prettyUrl(normalizeUrl(urlStr));
    }

    /**
     * Helper for making link data for SortTypeGroups. Mainly helps with marking the link as current and automating the url build config.
     * @param {string} label
     * @param {string} sortParamKey
     * @param {string} sortParamValue
     * @param {string} currentParamValue
     * @returns 
     */
    function makeSortTypeLink(label, sortParamKey, sortParamValue, currentParamValue) {
        return {
            label,
            href: buildUrl({ setParams: {[sortParamKey]: sortParamValue}, deleteParams: 'page' }),
            isCurrent: currentParamValue === sortParamValue
        }
    }
    //#endregion

    //#region Formatting
    /**
     * @param {string} path
     * @returns {string|null}
     */
    function pathToGalleryId(path) {
        return path.split('/')[2] ?? null;
    }
    /**
     * @param {number|string} id
     * @returns {string}
     */
    function galleryIdToPath(id) {
        return `/g/${id}/`;
    }
    /**
     * NOTE: THIS WILL NOT TRIM HYPHENS, YOU NEED TO DO THAT MANUALLY FOR NAME `.replaceAll('-', ' ')`
     * @param {string} path
     * @returns {{type: TagType|null, name: string|null}}
     */
    function tagInfoFromPath(path) {
        const pathSplit = path.split('/');
        const type = pathSplit[1];
        const name = pathSplit[2];
        return { type, name };
    }
    function firstLetterUpper(str) {
        if (!str) {
            return str;
        }
        return str.charAt(0).toUpperCase() + str.slice(1);
    }
    function formatMediaServer(locationStr) {
        return `https://t${getRandomInt(1, 4)}.nhentai.net/${locationStr}`;
    }

    function formatTagSearchTerm(tagType, tagName) {
        return `${tagType}:"${tagName.replaceAll('-', ' ')}"`;
    }
    function slugify(/** @type {string} */ str) {
        return str
            .toString()
            .normalize('NFKD')              // split accented chars into base + diacritic
            .replace(/[\u0300-\u036f]/g, '') // strip the diacritics
            .toLowerCase()
            .trim()
            .replace(/[^a-z0-9\s-]/g, '')   // remove non-alphanumeric chars
            .replace(/[\s_-]+/g, '-')       // collapse whitespace/underscores/hyphens into one -
            .replace(/^-+|-+$/g, '');       // trim leading/trailing hyphens
    }
    function formatJsonToDepth(obj, maxDepth, indent = 2, currentDepth = 0, currentIndent = '') {
        const nextIndent = currentIndent + ' '.repeat(indent);

        if (obj === null || typeof obj !== 'object') {
            return JSON.stringify(obj);
        }

        const isArray = Array.isArray(obj);
        const entries = isArray ? obj : Object.entries(obj);
        const items = isArray ? obj.map(v => v) : Object.entries(obj);

        if (items.length === 0) {
            return isArray ? '[]' : '{}';
        }

        // Beyond maxDepth: collapse to single-line JSON
        if (currentDepth >= maxDepth) {
            return JSON.stringify(obj);
        }

        const open = isArray ? '[' : '{';
        const close = isArray ? ']' : '}';

        const formattedItems = items.map(item => {
            if (isArray) {
                const formattedValue = formatJsonToDepth(item, maxDepth, indent, currentDepth + 1, nextIndent);
                return `${nextIndent}${formattedValue}`;
            } else {
                const [key, value] = item;
                const formattedValue = formatJsonToDepth(value, maxDepth, indent, currentDepth + 1, nextIndent);
                return `${nextIndent}${JSON.stringify(key)}: ${formattedValue}`;
            }
        });

        return `${open}\n${formattedItems.join(',\n')}\n${currentIndent}${close}`;
    }
    /**
     * @param {number} value
     * @returns {string} Retruns a string that is a numerical representation of the number from 0-1, up to 3 decimal places.
     */
    function formatOpacity(value) {
        if (typeof value !== "number" || Number.isNaN(value)) {
            return "1";
        }
        const clamped = Math.min(1, Math.max(0, value));
        return String(Math.round(clamped * 1000) / 1000);
    }
    //#endregion

    //#region Parsing
    function parseGalleryId(input) {
        // accepts nhentai gallery/reader url or a string of numbers. max 6 digits

        const trimmed = input.trim();
        let galleryId = '';

        const url = parseFullUrl(input, true);

        if (url) {
            // if not a gallery or reader page
            if (/^\/g\/\d+/.test(url.pathname) === false) {
                return null
            }

            // if gallery page or reader page
            galleryId = url.pathname.split('/')[2];
        } else {
            // else partial path, use first string of numbers
            galleryId = trimmed.split("/").find(segment => /^\d+$/.test(segment));
        }

        // fuck it, when we reach 7 digits in like 2030, ill come back and fix this line
        if (!galleryId || galleryId.length >= 7) {
            return null;
        }

        return galleryId;
    }
    function parseValidString(/** @type {string} */ input, { trim = true, allowEmpty = true, onlyTrimIfAllWhitespace = false, minLengthInclusive = 0, maxLengthInclusive = null, cuttoffAfterMax = false } = {}) {
        if (input == null) {
            return null;
        }
        
        let processedInput = input;

        if (trim && (!onlyTrimIfAllWhitespace || processedInput.trim() === '')) {
            processedInput = processedInput.trim();
        }

        if ((!allowEmpty && processedInput === '')
            || (minLengthInclusive != null && processedInput.length < minLengthInclusive && (!allowEmpty || processedInput.length !== 0)) // if empty allowed, allow length == 0 to bypass min length
            || (!cuttoffAfterMax && maxLengthInclusive != null && processedInput.length > maxLengthInclusive)) {
            return null;
        }

        if (cuttoffAfterMax && maxLengthInclusive != null) {
            processedInput = processedInput.slice(0, maxLengthInclusive);
        }

        return processedInput;
    }
    function parseValidInt(input) {
        return parseValidIntInRange(input);
    }
    function parseValidIntInRange(input, minValueInclusive = null, maxValueInclusive = null) {
        const int = parseInt(input);

        if (!Number.isFinite(int) || (minValueInclusive != null && int < minValueInclusive) || (maxValueInclusive != null && int > maxValueInclusive)) {
            return null;
        }

        return int;
    }
    function parseValidFloat(input) {
        return parseValidFloatInRange(input);
    }
    function parseValidFloatInRange(input, minValueInclusive = null, maxValueInclusive = null) {
        const float = parseFloat(input);

        if (!Number.isFinite(float) || (minValueInclusive != null && float < minValueInclusive) || (maxValueInclusive != null && float > maxValueInclusive)) {
            return null;
        }

        return float;
    }
    function parseBool(input) {
        const normalizedInput = input?.toLowerCase?.();
        if (normalizedInput === 'true') {
            return true;
        } else if (normalizedInput === 'false') {
            return false;
        }
        return null;
    }
    function parseFullUrl(input, sameOrigin = false) {
        try {
            const url = new URL(input.trim());

            if (sameOrigin && url.origin !== location.origin) {
                return null;
            }

            return url;            
        } catch {
            return null;
        }
    }
    function parseFullUrlStr(input, sameOrigin = false) {
        const url = parseFullUrl(input, sameOrigin);
        if (url) {
            return url.href;
        }
        return null;
    }
    function parseLabel(input) {
        const parsed = parseValidString(input, { trim: true, allowEmpty: false, maxLengthInclusive: 24 });
        return parsed?.includes(',') ? null : parsed;
    }
    function parsePriority(input) {
        return parseValidIntInRange(input, -2, 4 );
    }
    function parseTitleSections(customTitle) {
        // bless you claude for making functional regex on first try
        // edit: 2nd try
        const GROUP = String.raw`[\[(](?:[^\[\]()]|[\[(][^\[\]()]*[\])])*[\])]`;
        const RUN = String.raw`(?:${GROUP})(?:[^\S\n]*(?:${GROUP}))*`;
        const PARTS = new RegExp(String.raw`^(\s*(?:${RUN}))?([\s\S]*?)((?:${RUN})\s*)?$`);
        const [, before = '', pretty = '', after = ''] = customTitle.match(PARTS);
        return { before, pretty, after };
    }
    //#endregion
    //#endregion

    //#region -- Custom Pages -------------------------------------
    //#region Page Base
    function removeError404() {
        const errorPage = document.querySelector('.error-page');
        if (!errorPage.classList.contains('nhcb-custom-page-error')) {
            injector.injectClass(errorPage, 'nhcb-custom-page-error');
        }
    }
    function setCutomPageTitle(title) {
        const newTitle = title + ' - nhentai'
        if (document.title !== newTitle) {
            document.title = newTitle;
        }
    }
    function addPageBase() {
        injector.injectElement(createPageNavBar, '#app', 'nav');
        injector.injectElement(createPageContent, '#app', '#content');
    }
    //#endregion

    //#region Read Later Page
    function addCustomReadLaterPage() {
        const content = makeFactoryRoot(document.querySelector('#content'));
        const pageId = 'nhcb-read-later-page';

        if (!content || content.classList.contains(pageId)) {
            return;
        }
        content.classList.add(pageId);
        const container = createContainerGeneric({ className: 'index-container' });

        const defaultSortOption = 'priority-highest';

        const sortOption = pageData.searchParams.get('sort') ?? defaultSortOption;
        const currentPage = parseValidInt(pageData.searchParams.get('page')) ?? 1;

        const header = createElement('h1', {}, 'Read Later');

        //const counts = createElement('h2', {}, `${dataStore.readLater.value.size} Galleries`);

        const customSearch = createCustomSearchInput({});
        
        const sortOptionsRoot = createSortContainer({ content: [
            createSortTypeGroup({ groupName: 'By Priority:', links: [
                makeSortTypeLink('Highest', 'sort', 'priority-highest', sortOption),
                makeSortTypeLink('Lowest', 'sort', 'priority-lowest', sortOption),
            ]}),
            createSortTypeGroup({ groupName: 'Date Added:', links: [
                makeSortTypeLink('Newest', 'sort', 'add-date', sortOption),
                makeSortTypeLink('Oldest', 'sort', 'add-date-reverse', sortOption),
            ]}),
            createSortTypeGroup({ groupName: 'Date Posted:', links: [
                makeSortTypeLink('Newest', 'sort', 'date', sortOption),
                makeSortTypeLink('Oldest', 'sort', 'date-reverse', sortOption),
            ]}),
        ]});

        const sortOptionComparators = {
            'date': ([, a], [, b]) => b.id - a.id,
            'date-reverse': ([, a], [, b]) => a.id - b.id,
            'add-date': ([, a], [, b]) => b.added_at - a.added_at,
            'add-date-reverse': ([, a], [, b]) => a.added_at - b.added_at,
            'priority-highest': ([, a], [, b]) => b.read_priority - a.read_priority,
            'priority-lowest': ([, a], [, b]) => a.read_priority - b.read_priority,
        };


        const getWithDefault = (obj, key, defaultKey) => obj[key] ?? obj[defaultKey];
        const seletedSortComparator = getWithDefault(sortOptionComparators, sortOption, defaultSortOption);
        const searchFilters = customSearch.compileFilters();

        const filteredReadLater = [...dataStore.readLater.value.entries()].filter(([galleryPath, favoriteData]) => searchFilters.every(searchFilter => searchFilter(favoriteData)));

        const pageSize = 100;
        const pageCount = Math.ceil(filteredReadLater.length / pageSize);
        const paginationNav = createPaginationNav({ currentPage, totalPages: pageCount });

        const pagedReadLater = filteredReadLater.sort(seletedSortComparator).slice(pageSize * (currentPage - 1), pageSize * currentPage);

        container.append(createSearchResultsHeader({ resultCount: filteredReadLater.length }));

        pagedReadLater.forEach(([key, galleryData]) => {
            // fill cache
            cachedApiData.galleries.addData(galleryData);
            // create gallery
            container.append(createGalleryFromData(galleryData));
        });
         
        content.append(header, sortOptionsRoot, customSearch, container);
        factoryAppendSkipNull(content, paginationNav);
    }
    //#endregion

    //#region Browse Later Page
    function addCustomBrowseLaterPage() {
        const content = makeFactoryRoot(document.querySelector('#content'));
        const pageId = 'nhcb-browse-later-page';

        if (!content || content.classList.contains(pageId)) {
            return;
        }
        content.classList.add(pageId);
        const container = createContainerGeneric({ className: 'nhcb-tag-container' });

        const defaultSortOption = 'priority-highest';

        const sortOption = pageData.searchParams.get('sort') ?? defaultSortOption;
        const mustIncludeLabels = pageData.searchParams.get('labels')?.split(',')?.filter(label => label && label != 'none') ?? [];
        const mustNotHaveALabel = pageData.searchParams.get('labels')?.split(',')?.some(label => label == 'none') ?? false;
        const currentPage = parseValidInt(pageData.searchParams.get('page')) ?? 1;

        const header = createElement('h1', {}, 'Browse Later');

        const counts = createElement('h2', {}, `${dataStore.browseLater.value.size} Pages`);
        
        const sortOptions = createSortContainer({ content: [
            createSortTypeGroup({ groupName: 'By Priority:', links: [
                makeSortTypeLink('Highest', 'sort', 'priority-highest', sortOption),
                makeSortTypeLink('Lowest', 'sort', 'priority-lowest', sortOption),
            ]}),
            createSortTypeGroup({ groupName: 'Date Added:', links: [
                makeSortTypeLink('Newest', 'sort', 'add-date', sortOption),
                makeSortTypeLink('Oldest', 'sort', 'add-date-reverse', sortOption),
            ]}),
        ]});

        const labelFilterRoot = createSortContainer({ content: [
            createElement('div', { className: 'sort-type' }, 
                createElement('span', { className: 'sort-name' }, 'Must Include Label:'),
                createDropdownSelect({ 
                    id: 'nhcb-label-filter',
                    options: ['', ['none', '(no labels)'], ...settingsStore.labels.value],
                    initialValue: mustNotHaveALabel ? 'none' : mustIncludeLabels[0] ?? '',
                    elementProperties: { style: 'margin-right: 6px; vertical-align: center;' },
                    onSelectedChange: (value, index) => {
                    if (value) {
                        gotoPage(buildUrl({ setParams: {labels: value}, deleteParams: 'page' })) ;
                    } else {
                        gotoPage(buildUrl({ deleteParams: ['page', 'labels'] }));
                    }
                }}),
            ),
        ]});

        const sortOptionComparators = {
            'add-date': ([, a], [, b]) => b.added_at - a.added_at,
            'add-date-reverse': ([, a], [, b]) => a.added_at - b.added_at,
            'priority-highest': ([, a], [, b]) => b.browse_priority - a.browse_priority,
            'priority-lowest': ([, a], [, b]) => a.browse_priority - b.browse_priority,
        };


        const getWithDefault = (obj, key, defaultKey) => obj[key] ?? obj[defaultKey];
        const seletedSortComparator = getWithDefault(sortOptionComparators, sortOption, defaultSortOption);
        const labelFilter = ([, v]) => mustNotHaveALabel ? (v.labels?.length ?? 0) === 0 : (mustIncludeLabels.length === 0 ? true : mustIncludeLabels.every(label => v.labels?.includes(label)));
        const filteredBrowseLater = [...dataStore.browseLater.value.entries()].filter(labelFilter);

        const pageSize = 100;
        const pageCount = Math.ceil(filteredBrowseLater.length / pageSize);
        const paginationNav = createPaginationNav({ currentPage, totalPages: pageCount });

        const pagedBrowseLater = filteredBrowseLater.sort(seletedSortComparator).slice(pageSize * (currentPage - 1), pageSize * currentPage);

        // maybe do if tags
        pagedBrowseLater.forEach(([key, browseLaterData]) => {
            const tagInfo = tagInfoFromPath(key);
            container.append(createElement('div', {}, 
                createTagChip(browseLaterData.name ?? 'suitable page name', { href: key, tagType: tagInfo.type }),
                (browseLaterData.note /*|| browseLaterData.labels?.length > 0*/
                    ? createElement('div', { className: 'nhcb-browse-later-info-block' }, 
                        (browseLaterData.note ? createElement('div', { className: 'nhcb-browse-later-info-section' }, 'Note: ', createElement('span', { className: 'nhcb-browse-later-info' }, browseLaterData.note)) : ''),
                        //(browseLaterData.labels?.length > 0 ? createElement('div', { className: 'nhcb-browse-later-info-section' }, 'Labels: ', createElement('span', { className: 'nhcb-browse-later-info' }, browseLaterData.labels.join(', '))) : '')
                ) : ''),
            ));
        });
         
        content.append(header, counts, sortOptions, labelFilterRoot, container);
        factoryAppendSkipNull(content, paginationNav);
    }
    //#endregion

    //#region Favorites Page
    function addCustomFavoritesPage() {
        const content = makeFactoryRoot(document.querySelector('#content'));
        const pageId = 'nhcb-favorite-galleries-page';

        if (!content || content.classList.contains(pageId)) {
            return;
        }
        content.classList.add(pageId);
        const container = createContainerGeneric({ className: 'index-container' });

        const defaultDisplayRemoved = 'yes';
        const defaultSortOption = 'fav-date';

        const displayRemoved = pageData.searchParams.get('display-removed') ?? defaultDisplayRemoved;
        const sortOption = pageData.searchParams.get('sort') ?? defaultSortOption;
        const currentPage = parseValidInt(pageData.searchParams.get('page')) ?? 1;

        const header = createElement('h1', {}, 'Favorite Galleries');

        //const gallery404Count = [...dataStore.favoriteGalleries.value.values()].filter(f => f.gallery_is_404).length; // temp, this isn't ideal, should probably store counts for these
        //const counts = createElement('h2', {}, `${dataStore.favoriteGalleries.value.size - gallery404Count} Favorites + ${gallery404Count} 404s`);

        const customSearch = createCustomSearchInput({});
        
        const displayRemovedOptionsRoot = createSortContainer({ content: [
            createSortTypeGroup({ groupName: 'Display 404s:', links: [
                makeSortTypeLink('Mixed', 'display-removed', 'yes', displayRemoved),
                makeSortTypeLink('No 404s', 'display-removed', 'no', displayRemoved),
                makeSortTypeLink('Only 404s', 'display-removed', 'only', displayRemoved),
                makeSortTypeLink('Only 404s Raw', 'display-removed', 'raw', displayRemoved),
            ]}),
        ]});
        
        const sortOptionsRoot = createSortContainer({ content: [
            createSortTypeGroup({ groupName: 'Date Favorited:', links: [
                makeSortTypeLink('Newest', 'sort', 'fav-date', sortOption),
                makeSortTypeLink('Oldest', 'sort', 'fav-date-reverse', sortOption),
            ]}),
            createSortTypeGroup({ groupName: 'Date Posted:', links: [
                makeSortTypeLink('Newest', 'sort', 'date', sortOption),
                makeSortTypeLink('Oldest', 'sort', 'date-reverse', sortOption),
            ]}),
        ]});

        const sortOptionComparators = {
            'date': ([, a], [, b]) => b.id - a.id,
            'date-reverse': ([, a], [, b]) => a.id - b.id,
            'fav-date': ([, a], [, b]) => b.favorite_at - a.favorite_at,
            'fav-date-reverse': ([, a], [, b]) => a.favorite_at - b.favorite_at,
        };

        const displayRemovedFilters = {
            'yes': () => true,
            'no': ([, v]) => !v.gallery_is_404,
            'only': ([, v]) => v.gallery_is_404,
            'raw': ([, v]) => v.gallery_is_404,
        };


        const getWithDefault = (obj, key, defaultKey) => obj[key] ?? obj[defaultKey];
        const selectedDisplayRemovedFilter = getWithDefault(displayRemovedFilters, displayRemoved, defaultDisplayRemoved);
        const seletedSortComparator = getWithDefault(sortOptionComparators, sortOption, defaultSortOption);
        const searchFilters = customSearch.compileFilters();

        const filteredFavorites = [...dataStore.favoriteGalleries.value.entries()].filter(selectedDisplayRemovedFilter).filter(([galleryPath, favoriteData]) => searchFilters.every(searchFilter => searchFilter(favoriteData)));

        const pageSize = 100;
        const pageCount = Math.ceil(filteredFavorites.length / pageSize);
        const paginationNav = createPaginationNav({ currentPage, totalPages: pageCount });

        const pagedFavorites = filteredFavorites.sort(seletedSortComparator).slice(pageSize * (currentPage - 1), pageSize * currentPage);

        container.append(createSearchResultsHeader({ resultCount: filteredFavorites.length }));

        const altSourcesAllowed = displayRemoved != 'raw';
        pagedFavorites.forEach(([key, galleryData]) => {
            // fill cache
            cachedApiData.galleries.addData(galleryData);
            // create gallery
            container.append(createGalleryFromData(galleryData, { forbidAltSource: !altSourcesAllowed }));
        });
         
        content.append(header, displayRemovedOptionsRoot, sortOptionsRoot, customSearch, container);
        factoryAppendSkipNull(content, paginationNav);
    }
    //#endregion

    //#region Tags Page
    function addCustomTagsPage() {
        const content = makeFactoryRoot(document.querySelector('#content'));
        const pageId = 'nhcb-liked-tags-page';

        if (!content || content.classList.contains(pageId)) {
            return; 
        }
        content.classList.add(pageId);

        content.append(createElement('h1', {}, 'Liked Tags'));

        /** @type {Map<string, [{el: HTMLElement, sortName: string}]>} */
        const tagGroupings = new Map();

        dataStore.tagSentiments.value.forEach((tagSentiment, tagPath) => {
            if (tagSentiment.status != 'liked') {
                return;
            }
            const tagInfo = tagInfoFromPath(tagPath);
            const tagchip = createTagChip(tagInfo.name, { href: tagPath, count: Math.floor(Math.random() * 36) + 12 });
            if (!tagGroupings.has(tagInfo.type)) {
                tagGroupings.set(tagInfo.type, []);
            }
            tagGroupings.get(tagInfo.type).push({ el: tagchip.el, sortName: tagInfo.name});
        });

        tagGroupings.forEach((tagArray, tagType) => {
            const groupHeader = createElement('h2', {}, firstLetterUpper(TAG_TYPES.plural(tagType)));
            const tagContainer = createContainerGeneric({ className: 'nhcb-tag-container' });

            tagArray.sort((a, b) => a.sortName > b.sortName ? 1 : -1);
            tagContainer.append(...tagArray.map((tag) =>  createElement('div', {}, tag.el)));

            content.append(groupHeader, tagContainer);
        });
    }
    //#endregion

    //#region 404 Page
    async function apply404RecoveryPage() {
        // check if 404
        const is404 = document.querySelector(DEFINITIONS.SPECIAL_SELECTORS.ERROR_PAGE_IMAGE)?.alt === 'Error 404';
        const app = document.querySelector('#app');
        const changeId = 'nhcb-404';
        if (!is404 || !app || app.classList.contains(changeId)) {
            return;
        }
        injector.injectClass(app, changeId);

        // check if recovery data exists
        const recoveredGallery = dataStore.favoriteGalleries.value.get(pageData.path) ?? dataStore.readLater.value.get(pageData.path);
        if (!recoveredGallery) {
            return;
        }

        const galleryTitle = recoveredGallery.english_title ?? recoveredGallery.japanese_title ?? 'Recovery';

        // add recovery data as gallery cache
        cachedApiData.galleries.addData(recoveredGallery);

        // do api calls for tag info
        const tagsIds = recoveredGallery.tag_ids;
        if (tagsIds && tagsIds.length > 0) {
            const tagsMissingInCache = tagsIds.filter((id => !cachedApiData.tags.has(id)))
            const batches = [];
            const batchSize = 100;
            for (let i = 0; i < tagsMissingInCache.length; i += batchSize) {
                batches.push(tagsMissingInCache.slice(i, i + batchSize));
            }
            for (let i = 0; i < batches.length; i++) {
                const responseData = await apiEndpoints.multipleTags.fetch(batches[i]);
                if (responseData && responseData.length > 0) {
                    cachedApiData.tags.addData(...responseData);
                }
            }
        }

        // do custom page base
        removeError404(); // display none
        injector.injectElement(createPageNavBar, '#app', 'nav');
        injector.injectElement(createPageContent, '#app', '#content');
        setCutomPageTitle(`CB 404 - ${galleryTitle}`);

        const content = makeFactoryRoot(document.querySelector('#content'));
        const pageId = 'nhcb-404-recovery';

        if (!content || content.classList.contains(pageId)) {
            return; 
        }
        injector.injectClass(content, pageId);

        const header = createElement('h1', {}, '404 Recovery');
        const info = createElement('div', { className: 'nhcb-recovery-info' },
            createElement('h2', {}, 'This gallery has been removed from nHentai.'), 
            createElement('p', {}, "The gallery's data has been saved by Custom Brew. If you remove this gallery from Custom Favorites and Read Later the data will be gone when you leave this page.")
        )
        const notice = createElement('p', { className: 'nhcb-404-notice' }, "This gallery is: ");
        const noticeStatus = createSpan('SAVED', { className: 'nhcb-404-notice-status'});

        notice.append(noticeStatus);
        info.append(notice);

        function updateNoticeSatuts() {
            const isSafe = dataStore.favoriteGalleries.value.has(pageData.path) || dataStore.readLater.value.has(pageData.path)
            noticeStatus.replaceChildren(isSafe ? 'SAVED' : 'REMOVED');
            noticeStatus.classList.toggle('nhcb-404-notice-unsafe', !isSafe);
        }

        const unsubscribeFavorites = dataStore.favoriteGalleries.subscribe(updateNoticeSatuts);
        const unsubcribeReadLater = dataStore.readLater.subscribe(updateNoticeSatuts);
        cleaner.addTaskNoFail(unsubscribeFavorites);
        cleaner.addTaskNoFail(unsubcribeReadLater);

        // reconstruct gallery page
        const bigContainer = createGalleryPageBigContainer(recoveredGallery, { disableCoverLink: true, coverOverride: { thumbnail: DEFINITIONS.ERROR_404_IMAGE.path, thumbnail_width: DEFINITIONS.ERROR_404_IMAGE.width, thumbnail_height: DEFINITIONS.ERROR_404_IMAGE.height } });
        
        content.append(header, info, bigContainer);
    }
    //#endregion

    //#region Settings Page
    function addCustomSettingsPage() {
        const content = makeFactoryRoot(document.querySelector('#content'));
        const pageId = 'nhcb-settings-page';

        if (!content || content.classList.contains(pageId)) {
            return;
        }
        content.classList.add(pageId);
        const container = createContainerGeneric({ content: createElement('h1', {}, 'NHCB Settings') });

        const parserCssValue = (v) => v == '' ? v : parseValidFloatInRange(v, 0)?.toString();
        const parserTtlValue = (v) => {
            const parsed = parseValidIntInRange(v, 1);
            return parsed != null ? parsed * 60 * 1000 : null;
        };

        container.append(
            createApiKeySettingsPanel(),
            createAutoLoginSettingsPanel(),
            createLabelSettingsPanel(),
            createBackupSettingsPanel(),
            createSettingsPanel('View/Browse System', 'Everything related to viewing or reading galleries or pages.', [
                { storeKey: 'enableViewSystemButtons',          type: 'binary', binaryOptionType: 'enabled/disabled',   label: 'View System Buttons',               tooltip: 'If enabled, will show buttons that allow for interaction with the view system for galleries.' },
                { storeKey: 'enableBrowseSystemButtons',        type: 'binary', binaryOptionType: 'enabled/disabled',   label: 'Browse System Buttons',             tooltip: 'If enabled, will show buttons that allow for interaction with the browse system for pages.' },
                { storeKey: 'autoSeenIfVisited',                type: 'binary',                                         label: 'Seen if Visited',                   tooltip: 'If enabled, galleries that you visit are also marked as seen. You can still mark them as not seen.' },
                { storeKey: 'autoSeenIfRead',                   type: 'binary',                                         label: 'Seen if Read',                      tooltip: 'If enabled, galleries that are marked as read will also be marked as seen.' },
                { storeKey: 'autoRemoveReadLaterIfRead',        type: 'binary',                                         label: 'Remove Read Later if Read',         tooltip: 'If enabled, galleries that are marked as read will also be removed from your read later list. If disabled, you have to manually remove it.' },
                { storeKey: 'autoRemoveBrowseLaterIfBrowsed',   type: 'binary',                                         label: 'Remove Browse Later if Browsed',    tooltip: 'If enabled, pages that are marked as browsed will also be removed from your browse later list. If disabled, you have to manually remove it.' },
            ]),
            createSettingsPanel('Tag Sentiments', 'Settings related to tag sentiments, basically liked/disliked but with a more generic name.', [
                { storeKey: 'enableTagSentimentButtons',    type: 'binary', binaryOptionType: 'enabled/disabled', label: 'Buttons',     tooltip: 'If enabled, will show buttons that allow for interaction with tag sentiments.' },
                { storeKey: 'enableTagSentimentHighlights', type: 'binary', binaryOptionType: 'enabled/disabled', label: 'Highlights',  tooltip: 'If enabled, tags will be highlighted based on their sentiment to easily see at a glance.' },
            ]),
            createSettingsPanel('Darken Galleries', 'Darken galleries based on conditions. The value sets the opacity, which can be 1 for no darkening or 0 for completely dark. Order of precedence is as shown. You must reload the page for the change to take effect. (Liked and Passed are treated like an alternate version of Read)', [
                { storeKey: 'opacityReadLater',     type: 'text', valueParser: (v) => parseValidFloatInRange(v, 0, 1), label: '1. Read Later' },
                { storeKey: 'opacitLiked',          type: 'text', valueParser: (v) => parseValidFloatInRange(v, 0, 1), label: '2. Liked' },
                { storeKey: 'opacityPassed',        type: 'text', valueParser: (v) => parseValidFloatInRange(v, 0, 1), label: '2. Passed' },
                { storeKey: 'opacityRead',          type: 'text', valueParser: (v) => parseValidFloatInRange(v, 0, 1), label: '2. Read' },
                { storeKey: 'opacityNotEnglish',    type: 'text', valueParser: (v) => parseValidFloatInRange(v, 0, 1), label: '3. Non-English' },
                { storeKey: 'opacitySeen',          type: 'text', valueParser: (v) => parseValidFloatInRange(v, 0, 1), label: '4. Seen' },
            ]),
            createSettingsPanel('Display Adjustments', 'Adjust the way things are displayed to make them look more better.', [
                { storeKey: 'galleryContainerWidth',            type: 'text',       valueParser: parserCssValue, placeholder: 'Enter number...',    label: 'Gallery Container Width',               tooltip: `Overrides the width of the containers that display lists of galleries. Website default is ${DEFINITIONS.WEBSITE_DEFAULT_CONTAINER_WIDTH}, recommended is 1300.` },
                { storeKey: 'thumbnailContainerWidth',          type: 'text',       valueParser: parserCssValue, placeholder: 'Enter number...',    label: 'Thumbnail Container Width',             tooltip: `Overrides the width of the containers that display thumbnails for pages on a gallery. Website default is ${DEFINITIONS.WEBSITE_DEFAULT_CONTAINER_WIDTH}, recommended is 1300.` },
                { storeKey: 'thumbnailWidth',                   type: 'text',       valueParser: parserCssValue, placeholder: 'Enter number...',    label: 'Thumbnail Width',                       tooltip: `Overrides the width of the thumbnail for pages of a gallery. Recommended is 244 if using other recommended values. Website default is technically 200, but there is other stuff that gets changed to change the size. Remove the value to disable the changes.` },
                { storeKey: 'enableThumbnailCentering',         type: 'binary',                                                                     label: 'Center Thumbnails',                     tooltip: `If enabled, thumbails are now sit in the middle of the container instead of the left. I am not sure why the website explicitly changes this for thumbnails, everything else is centered.` },
                { storeKey: 'enablePrettyTitleLists',           type: 'binary',     binaryOptionType: 'enabled/disabled',                           label: 'Pretty Titles on Lists',                tooltip: `If enabled, titles will be adjusted to use pretty display, similar to how they look on gallery pages.` },
                { storeKey: 'prettyTitleListsHighlight',        type: 'options',    options: DEFINITIONS.PRETTY_TITLE_DISPLAY_OPTIONS,              label: 'Pretty Titles Hightlight',              tooltip: `If Pretty Titles on Lists is enabled, titles will be highlighted (or not) based on this setting.` },
                { storeKey: 'prettyTitleListsShorten',          type: 'options',    options: DEFINITIONS.PRETTY_TITLE_DISPLAY_OPTIONS,              label: 'Pretty Titles Shorten',                 tooltip: `If Pretty Titles on Lists is enabled, titles will be shortened (or not) based on this setting.` },
                { storeKey: 'removeBorderOnButtonsWithTooltip', type: 'binary',     binaryOptionType: 'yes/no',                                     label: 'Remove Border On Buttons With Tooltip', tooltip: `Buttons on the gallery page have a tooltip attach that add a small dotted border to the bottom of the button. This setting removes that. I think it only appears on gallery page but this will affect all button with a tooltip.` },
                { storeKey: 'fixMultiLanguageGalleries',        type: 'options',                                                                    label: 'Fix Multi Language Galleries',          tooltip: `Galleries with multiple lagnuages can often be labeled as any of the included languages. This can be misleading about what language the gallery is while also affecting some Custom Brew features.<br><br>"Label English" will re-label the gallery as English.<br><br>"Multi Flag" will re-label the gallery as English and also change the flag to indicate that it has multiple languages.<br><br>"Disabled" will not make any changes.<br><br>("Multi Flag" is recomended)`, options: [['labelEnglish', 'Label English'], ['multiFlag', 'Multi Flag'], ['disabled', 'Disabled']] },
            ]),
            createSettingsPanel('Custom Favorites', 'Custom favorites are galleries that are saved to be customizable.', [
                { storeKey: 'enableCustomFavoritesButton',      type: 'binary', binaryOptionType: 'yes/no',           label: 'Show Buttons',                    tooltip: 'If enabled, will show buttons that allow for interaction with the custom favorites system for galleries.' },
                { storeKey: 'customFavoritesSeparateButton',    type: 'binary', binaryOptionType: 'enabled/disabled', label: 'Separate Custom Favorite Button', tooltip: 'If enabled, the custom favorites will be given a separate button. If disabled, it will override the favorites button. If you are using this while logged in, you probably want the this enabled.' },
                { storeKey: 'allowRatingHalf',                  type: 'binary', binaryOptionType: 'yes/no',           label: 'Allow Rating Half',               tooltip: 'If enabled, you can give a ratings with half points (4.5). If disabled, you can only rate in whole numbers (5). If changed, existing ratings won\'t be changed.' },
                { storeKey: 'showRatingsOnCover',               type: 'binary', binaryOptionType: 'yes/no',           label: 'Show Rating on Cover',            tooltip: 'If enabled, a numberical representation of the rating will be shown on the cover, next to the favorite icon.' },
                { storeKey: 'useTenPointRating',                type: 'binary', binaryOptionType: 'yes/no',           label: 'Use 10 Point Rating',             tooltip: 'If enabled, the numberical representation will be out of 10 instead of 5.' },
                { storeKey: 'displayCustomTitles',              type: 'binary', binaryOptionType: 'enabled/disabled', label: 'Display Customized Titles',       tooltip: 'If enabled, customized titles that you enter will be displayed.' },
            ]),
            createSettingsPanel('Browse Pages', 'Everything related to browse pages.', [
                { storeKey: 'enableJumpToPageOnElipsis',                type: 'binary', binaryOptionType: 'enabled/disabled', label: 'Add Jump To Page on Elipsis',         tooltip: 'If enabled, the elipsis ("...") that appear on pages with multiple pages of results can be clicked to jump to a specifc page number.' },
                { storeKey: 'enableArrowKeyNavigationForPagination',    type: 'binary', binaryOptionType: 'enabled/disabled', label: 'Arrow Key Navigation For Pagination', tooltip: 'If enabled, pages with multiple pages of results can be navigated using the arrow keys. Left arrow for previous page and right arrow for next page.' },
                { storeKey: 'enableEnglishOnlyButton',                  type: 'binary', binaryOptionType: 'enabled/disabled', label: 'English Only Button',                 tooltip: 'A button that will search for the current tag or search but with an additional filter for english galleries.' },
                { storeKey: 'enableFixPipeButton',                      type: 'binary', binaryOptionType: 'enabled/disabled', label: 'Fix Pipe Button',                     tooltip: 'A button that will seach for the current tag without the pipe. The pipes are tags which have an alt name for artists, but they are classified as a spearate tag. Effectively giving an aritst two sepearate tags which can make it a bit awkward for browsing or using other systems.' },
                { storeKey: 'enableSortPopularMonthButton',             type: 'binary', binaryOptionType: 'enabled/disabled', label: 'Sort Popular Month',                  tooltip: 'If enabled, a option to sort by popular month will be added.' },
                { storeKey: 'hideGtsDescriptionIfNone',                 type: 'binary', binaryOptionType: 'yes/no',           label: 'Hide Empty Tag Descriptions',         tooltip: 'If enabled, zooming in will not cause the image to be bigger than what you can see.' },
                { storeKey: 'addTagChipFromSearch',                     type: 'binary', binaryOptionType: 'yes/no',           label: 'Add Tag Chip from Search',            tooltip: 'If enabled, a tag chip will be added to the search page if the search contains exactly one tag, not including an english filter.' },
                { storeKey: 'copyTagOnClick',                           type: 'binary', binaryOptionType: 'enabled/disabled', label: 'Copy Tag on Click',                   tooltip: 'If enabled, clicking on a tag while on the search page or tag page will copy the tag to your clipboard. (Without it, nothing happens)' },
            ]),     
            createSettingsPanel('Gallery Custom Info', 'Add additional info to the gallery page based on other stuff like time you read the gallery.', [
                { storeKey: 'enableGalleryCustomInfo',                  type: 'binary', binaryOptionType: 'enabled/disabled', label: 'Enable',                          tooltip: 'Master system enable/disable. If disabled, no custom gallery info will be added.' },
                { storeKey: 'enableGalleryCustomInfoReadStatus',        type: 'binary', binaryOptionType: 'enabled/disabled', label: 'Date Read',                       tooltip: 'If enabled, shows when you read the gallery if it is read.' },
                { storeKey: 'enableGalleryCustomInfoReadLaterStatus',   type: 'binary', binaryOptionType: 'enabled/disabled', label: 'Date Read Later',                 tooltip: 'If enabled, shows when you added the gallery to your read later list.' },
                { storeKey: 'enableGalleryCustomInfoReadLaterPriority', type: 'binary', binaryOptionType: 'enabled/disabled', label: 'Read Later Priority',             tooltip: 'If enabled, shows the read priority for a read later gallery.' },
                { storeKey: 'enableGalleryCustomInfoReadLaterLabels',   type: 'binary', binaryOptionType: 'enabled/disabled', label: 'Read Later Labels',               tooltip: 'If enabled, shows the labels given to a read later gallery if it has any.' },
                { storeKey: 'enableGalleryCustomInfoFavoriteStatus',    type: 'binary', binaryOptionType: 'enabled/disabled', label: 'Date Favorited',                  tooltip: 'If enabled, shows when you favorited the gallery.' },
                { storeKey: 'enableGalleryCustomInfoFavoriteRating',    type: 'binary', binaryOptionType: 'enabled/disabled', label: 'Favorite Rating',                 tooltip: 'If enabled, shows the rating for the favorited gallery if it has one.' },
                { storeKey: 'enableGalleryCustomInfoFavoriteLabels',    type: 'binary', binaryOptionType: 'enabled/disabled', label: 'Favorite Labels',                 tooltip: 'If enabled, shows the labels given to the favorited gallery if it has any.' },
                { storeKey: 'enableGalleryCustomInfoFavoriteNote',      type: 'binary', binaryOptionType: 'enabled/disabled', label: 'Favorite Note',                   tooltip: 'If enabled, shows the note for the favorited gallery if it has one.' },
                { storeKey: 'hideGalleryCustomInfoReadIfFavorite',      type: 'binary', binaryOptionType: 'yes/no',           label: 'Hide Date Read if Favorited',     tooltip: 'If enabled, it hides the Date Read if it was also favorited. Instead it will only show the Date Favorited. I thought it was a bit uneccessary to have both.' },
            ]),
            createSettingsPanel('Reader Pages', 'Everything related to the gallery reader (the pages of the gallery /g/123456/X/).', [
                { storeKey: 'enableReaderAutoPlayer',               type: 'binary', binaryOptionType: 'enabled/disabled', label: 'Auto Player',                         tooltip: 'If enabled, will add controls to auto play galleries. Has an adjustable delay to view next page.' },
                { storeKey: 'readerDontExitOnArrowNav',             type: 'binary', binaryOptionType: 'enabled/disabled', label: 'Prevent Exit on Arrow Key Nav',       tooltip: 'If enabled, using right arrow key on the keyboard while one the last page will not exit the gallery.' },
                { storeKey: 'readerEnableImprovedZoom',             type: 'binary', binaryOptionType: 'enabled/disabled', label: 'Improved Zoom',                       tooltip: 'If enabled, an improved zoom sytem is used instead of the default. It has the ability to zoom out to zoom out and has smaller increments of 0.1 instead of 0.2.' },
                { storeKey: 'readerDontOverZoom',                   type: 'binary', binaryOptionType: 'enabled/disabled', label: 'Prevent Over Zoom',                   tooltip: 'If enabled, zooming in will not cause the image to be bigger than what you can see.' },
                { storeKey: 'readerZoomCapImageNaturalSize',        type: 'binary', binaryOptionType: 'enabled/disabled', label: 'Zoom Cap Image Natural Size',         tooltip: 'If enabled, zooming will not make it bigger than size of the source image.' },
                { storeKey: 'readerEnableFullscreen',               type: 'binary', binaryOptionType: 'enabled/disabled', label: 'Fullscreen',                          tooltip: 'If enabled, a fullscreen mode is made available for the reader. Will make the image as big as possible and remove the website nav bar.' },
                { storeKey: 'readerFullscreenCapImageNaturalSize',  type: 'binary', binaryOptionType: 'enabled/disabled', label: 'Fullscreen Cap Image Natural Size',   tooltip: 'If enabled, the image will not be made bigger than the size of the source image while in fullscreen.' },
            ]),
            createSettingsPanel('Request Caching', 'API requests are automatically cached to reduce the number of duplicate API calls. If you don\'t know what that means, then you probably shouldn\'t change these settings. A reload is requred for changes to take effect. If you set it to a really big number, you will have to manually clear cache to get rid of the ancient sages you\'ve created.', [
                { storeKey: 'requestCacheGalleryListTtl',   type: 'text', valueParser: parserTtlValue, valueFormatter: (v) => v / (60 * 1000), label: 'Gallery Lists Minutes Ttl',  tooltip: 'Sets how long request that deal with lists of galleries should be cached for (duration is in minutes). Recommended is 2 minutes (changes when new galleries are uploaded).' },
                { storeKey: 'requestCacheGalleryTtl',       type: 'text', valueParser: parserTtlValue, valueFormatter: (v) => v / (60 * 1000), label: 'Galleries Minutes Ttl',      tooltip: 'Sets how long request that deal with individual galleries should be cached for (duration is in minutes). Recommended is 20 minutes (changes when community adds tags or favorites it).' },
                { storeKey: 'requestCacheTagTtl',           type: 'text', valueParser: parserTtlValue, valueFormatter: (v) => v / (60 * 1000), label: 'Tags Minutes Ttl',           tooltip: 'Sets how long request that deal with tag info should be cached for (duration is in minutes). Recommended is 120 minutes (tag info rarely ever changes).' },
            ]),
            createSettingsPanel('Auto Refresh', 'Settings for controlling auto refresh on rate limit.', [
                { storeKey: 'enableAutoRefreshRateLimitGallery',    type: 'binary', binaryOptionType: 'enabled/disabled', label: 'Gallery Rate Limit',  tooltip: 'If enabled, page will auto refresh when rate limited after a delay.' },
                { storeKey: 'enableAutoRefreshCloudflareGallery',   type: 'binary', binaryOptionType: 'enabled/disabled', label: 'Gallery Cloudflare',  tooltip: 'If enabled, page will auto refresh when encountering a cloudflare page after a delay. This page is typically only encounted when being rate limited.' },
            ]),
            createSettingsPanel('Misc Settings', 'Do you think god hides in heaven because he too lives in fear what he\'s created here on earth?', [
                { storeKey: 'enableTryAnotherSiteButton',   type: 'binary', binaryOptionType: 'enabled/disabled',   label: 'Try Another Site Button',           tooltip: 'If enabled, there will be a button that gives links to other websites that could have alt sources the gallery.' },
                { storeKey: 'groupTagNavLinks',             type: 'binary', binaryOptionType: 'yes/no',             label: 'Group Tag Links in Nav Bar',        tooltip: 'If enabled, the links in the nav bar at the top of the page get grouped together into a menu similar to the community links.' },
                { storeKey: 'enableNavDropdownFix',         type: 'binary', binaryOptionType: 'enabled/disabled',   label: 'Nav Bar Dropdown not Closing Fix',  tooltip: 'If enabled, this will apply a fix to the dropdown menu that appears in the navigation bar that is at the top of the page (only visible in some screen sizes). Without the fix, clicking on the button that shows the dropdown will open it, but then the dropdown can only be closed again by clicking on the button. With the fix, clicking anywhere else that isn\'t the dropdown will close the menu. (It\'s a bit shocking this hasn\'t been fixed yet)' },
                { storeKey: 'enableAutoPipeFix',            type: 'binary', binaryOptionType: 'yes/no',             label: 'Auto Tag Pipe Fix in Tag List',     tooltip: 'If enabled, tags with pipes will be automatically be fixed. The pipes are tags which have an alt name for artists, but they are classified as a spearate tag. Effectively giving an aritst two sepearate tags which can make it a bit awkward for browsing or using other systems.' },
                { storeKey: 'addNavBarToErrorPages',        type: 'binary', binaryOptionType: 'yes/no',             label: 'Add Nav Bar to Error Pages',        tooltip: 'If enabled, a nav bar will be added to the top of the page on error pages. A nav bar is the bar at the top of the screen that has the search bar and links.' },
                { storeKey: 'bypassTaxonomyAgreement',      type: 'options',                                        label: 'Bypass Taxonomy Agreement',         tooltip: 'The voting for gallery tags requires an agreement. This agreement requires you to wait 3 seconds. If set to "enabled", it will bypass the agreement. If set to "no waiting", the 3 second delay will be disabled. If set to "disabled", no changes will be made.', options: ['enabled', ['nowaiting', 'no waiting'], 'disabled'] },
                { storeKey: 'bypassAgeGate',                type: 'binary', binaryOptionType: 'enabled/disabled',   label: 'Bypass Age Gate',                   tooltip: 'When you first visit the website, it asks for you age. When enabled, it will bypass it by autofilling the info.' },
                { storeKey: 'autoSubmitAgeGate',            type: 'binary', binaryOptionType: 'enabled/disabled',   label: 'Auto Submit Age Gate',              tooltip: 'If Bypass Age Gate is enabled, this will auto submit the info. This is a separate option because it can be a bit buggy because of how the website works. Most times it shouldn\'t cause an issue. If you run into issues frequently, you might want to disable this.' },
            ]),
            createSettingsPanel('Badges', 'Collect them all.', [
                { storeKey: 'enableViewSystemBadge',                        type: 'binary', binaryOptionType: 'enabled/disabled', label: 'View System',                 tooltip: 'If enabled, galleries will have a badge that shows their view system status.' },
                { storeKey: 'enableFavoriteGalleryBadge',                   type: 'binary', binaryOptionType: 'enabled/disabled', label: 'Custom Favorites',            tooltip: 'If enabled, favorite galleries will have a badge that show they are favorited.' },
                { storeKey: 'enablePageCountBadge',                         type: 'binary', binaryOptionType: 'enabled/disabled', label: 'Page Count',                  tooltip: 'If enabled, galleries will have a badge that shows how many pages they have.' },
                { storeKey: 'adjustPageCountForMultiLang',                  type: 'binary', binaryOptionType: 'yes/no',           label: 'Adjust Page Count',           tooltip: 'If enabled, the number of pages shown on the page count badge will be adjusted to better show number of acutal pages the gallery has. If the gallery has multiple laguages, it likely has duplicate pages in other languages. This will make a simple guess that half or a third of the pages are duplicates based on the number of languages. This will not affect search results. This would work perfectly if the "textless" tag was actually used.' },
                { storeKey: 'enablePageCountBadgeColorIndicator',           type: 'binary', binaryOptionType: 'yes/no',           label: 'Page Count Color Indicator',  tooltip: 'If enabled, page count will have a dot whose color shows how many pages it has. Very short->red, Short->orange, Average->white, Long->green, Very Long->cyan, Super Long->violet. Colors are blended near break points. Breakpoints and colors are not adjustable since it would take a lot of time to make UI for the settings.' },
                //{ storeKey: 'pageCountBadgeColorIndicatorBlendAmount',      type: 'text', valueParser: (v) => parseValidFloatInRange(v, 0, 1), label: 'Color Indicator Blend Ammount', tooltip: '',  },
                { storeKey: 'enableArtistInfoBadge',                        type: 'binary', binaryOptionType: 'enabled/disabled', label: 'Artist Info Badge',           tooltip: 'If enabled, galleries will have a badge that shows a variety of info related to the artists/groups. Customized what\'s displayed with other settings.' },
                { storeKey: 'enableBadTranslationBadge',                    type: 'binary', binaryOptionType: 'enabled/disabled', label: 'Bad Translation Badge',       tooltip: 'If enabled, galleries will have a badge that shows that the gallery has a bad translation. The conditions can be customized. Unfortunately there is no tag for "dogshit MTL" so there is no perfect solution.' },
                { storeKey: 'enableIncompleteBadge',                        type: 'binary', binaryOptionType: 'enabled/disabled', label: 'WIP/Incomplete Badge',        tooltip: 'If enabled, galleries that are marked as incomplete will have and WIP Badge added.' },
                { storeKey: 'enableBrowseSystemBadges',                     type: 'binary', binaryOptionType: 'enabled/disabled', label: 'Browse System',               tooltip: 'If enabled, tags will have a badge that shows their browse system status.' },
            ]),
            createSettingsPanel('Artist Info Badge Sub-Badges', 'Settings for sub-badges shown in the Artist Info Badge.', [
                { storeKey: 'enableArtistInfoAnthology',                    type: 'binary', binaryOptionType: 'enabled/disabled', label: 'Anthology',                   tooltip: 'If enabled, Artist Info Badge will include a badge that shows if the gallery is an anthology containing multiple artists (less accurate for older galleries).' },
                { storeKey: 'enableArtistInfoBrowseLater',                  type: 'binary', binaryOptionType: 'enabled/disabled', label: 'Browse Later',                tooltip: 'If enabled, Artist Info Badge will include a badge that shows if the gallery\'s artists/groups is marked Browse Later.' },
                { storeKey: 'enableArtistInfoTagSentiment',                 type: 'binary', binaryOptionType: 'enabled/disabled', label: 'Tag Sentiment',               tooltip: 'If enabled, Artist Info Badge will include a badge that shows the Tag Setniment for the artists/groups (liked, dubious, scorned).' },
                { storeKey: 'enableArtistInfoCompilation',                  type: 'binary', binaryOptionType: 'enabled/disabled', label: 'Compilation',                 tooltip: 'If enabled, Artist Info Badge will include a badge that shows if the gallery is a compilation containing multiple works by the same artist (not always accurate).' },
            ]),
            createSettingsPanel('Bad Translation Badge Conditions', 'Settings for the conditions that are needed for the Bad Translation Badge to apply. There is no perfect solution, so you just have to choose what you think would work best.', [
                { storeKey: 'badTranslationMinConditions',                  type: 'options', options: [[1, 'Any'], [2, '2'], [3, '3'], [-1, 'All']], label: 'BTB Minimum Conditions',           tooltip: 'The number of conditions needed to apply the Bad Translation Badge.' },
                { storeKey: 'enableBadTranslationRoughTranslationTag',      type: 'binary', binaryOptionType: 'on/off',           label: 'Has Rough Translation Tag',   tooltip: 'Checks if the gallery has a "Rough Translation" tag.' },
                { storeKey: 'enableBadTranslationMachineTranslationTag',    type: 'binary', binaryOptionType: 'on/off',           label: 'Has Machine Translation Tag', tooltip: 'Checks if the gallery has a "Machine Translation" tag. (Uncommon community tag)' },
                { storeKey: 'enableBadTranslationMtlTitle',                 type: 'binary', binaryOptionType: 'on/off',           label: 'Has MTL Title',               tooltip: 'Checks if the gallery has "MTL" in the title (for "[MTL]", "[SCANMTL]", or something similar).' },
                { storeKey: 'enableBadTranslationAiTranslateTitle',         type: 'binary', binaryOptionType: 'on/off',           label: 'Has AI Tranlation Title',     tooltip: 'Checks if the gallery has "AI Translation" in the title or something similar (for "[AI Translation]", "[AI-Translate]", or something similar).' },
            ]),
            createSettingsPanel('Big Cover Badges', 'Separate settings just for Big Cover. The Big Cover is the gallery cover shown on the gallery page (next to the tags and other infomration).', [
                { storeKey: 'enableBadgesOnBigCover',                       type: 'binary', binaryOptionType: 'enabled/disabled', label: 'Badges On Big Cover (BC)',    tooltip: 'If enabled, badges will be added to the big cover on the gallery page (the cover preview for the gallery you are viewing). If disabled, no badges will be added to the big cover despite individual toggles.' },
                { storeKey: 'enableBcViewSystemBadge',                      type: 'binary', binaryOptionType: 'enabled/disabled', label: 'BC View System',              tooltip: 'If enabled, view system badge will be added to the big cover if badges on big cover is enabled.' },
                { storeKey: 'enableBcFavoriteGalleryBadge',                 type: 'binary', binaryOptionType: 'enabled/disabled', label: 'BC Custom Favorites',         tooltip: 'If enabled, custom favorites badge will be added to the big cover if badges on big cover is enabled.' },
                { storeKey: 'enableBcPageCountBadge',                       type: 'binary', binaryOptionType: 'enabled/disabled', label: 'BC Page Count',               tooltip: 'If enabled, page count badge will be added to the big cover if badges on big cover is enabled.' },
                { storeKey: 'enableBcArtistInfoBadge',                      type: 'binary', binaryOptionType: 'enabled/disabled', label: 'BC Artist Info Badge',        tooltip: 'If enabled, artist info badge will be added to the big cover if badges on big cover is enabled.' },
                { storeKey: 'enableBcBadTranslationBadge',                  type: 'binary', binaryOptionType: 'enabled/disabled', label: 'BC Bad Translation Badge',    tooltip: 'If enabled, bad translation badge will be added to the big cover if badges on big cover is enabled.' },
                { storeKey: 'enableBcBadTranslationBadge',                  type: 'binary', binaryOptionType: 'enabled/disabled', label: 'BC WIP/Incomplete Badge',     tooltip: 'If enabled, wip/incomplete badge will be added to the big cover if badges on big cover is enabled.' },
                { storeKey: 'enableBcContentWarningBadge',                  type: 'binary', binaryOptionType: 'enabled/disabled', label: 'BC Content Warning',          tooltip: 'If enabled, content warning badge will be added to the big cover if badges on big cover is enabled.' },
            ]),
            createContentWarningSettingsPanel(),
        );
        content.append(container);
    }
    //#endregion

    function __addCustomPageTemplate() {
        //just copy paste into new function
        const content = makeFactoryRoot(document.querySelector('#content'));
        const pageId = 'nhcb-custom-page';

        if (!content || content.classList.contains(pageId)) {
            return;
        }
        content.classList.add(pageId);
        const container = createContainerGeneric();

        const header = createElement('h1', {}, 'Custom Page');

        container.append(header);
        content.append(container);
    }
    //#endregion

    //#region -- Styles --------------------------------------------
    function addStyles() {
    // function colorScale(baseHex, { selector = '', prefix = 'color', chroma = 1, hueShift = 0} = {}){
    //     const STEPS = [
    //         { n: "50",  L: 0.971, e: 0.18 },
    //         { n: "100", L: 0.936, e: 0.32 },
    //         { n: "200", L: 0.885, e: 0.52 },
    //         { n: "300", L: 0.808, e: 0.74 },
    //         { n: "400", L: 0.704, e: 0.92 },
    //         { n: "500", L: 0.637, e: 1.00 },
    //         { n: "600", L: 0.577, e: 0.97 },
    //         { n: "700", L: 0.505, e: 0.86 },
    //         { n: "800", L: 0.444, e: 0.72 },
    //         { n: "900", L: 0.396, e: 0.62 },
    //         { n: "950", L: 0.258, e: 0.42 },
    //     ];
        
    //     const s2l = (c) => (c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4));
    //     const l2s = (c) => (c <= 0.0031308 ? 12.92 * c : 1.055 * Math.pow(c, 1 / 2.4) - 0.055);
        
    //     function linToOklab(r, g, b) {
    //         const l = 0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b;
    //         const m = 0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b;
    //         const s = 0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b;
    //         const l_ = Math.cbrt(l), m_ = Math.cbrt(m), s_ = Math.cbrt(s);
    //         return [
    //         0.2104542553 * l_ + 0.7936177850 * m_ - 0.0040720468 * s_,
    //         1.9779984951 * l_ - 2.4285922050 * m_ + 0.4505937099 * s_,
    //         0.0259040371 * l_ + 0.7827717662 * m_ - 0.8086757660 * s_,
    //         ];
    //     }
        
    //     function oklabToLin(L, a, b) {
    //         const l_ = L + 0.3963377774 * a + 0.2158037573 * b;
    //         const m_ = L - 0.1055613458 * a - 0.0638541728 * b;
    //         const s_ = L - 0.0894841775 * a - 1.2914855480 * b;
    //         const l = l_ ** 3, m = m_ ** 3, s = s_ ** 3;
    //         return [
    //         4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,
    //         -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,
    //         -0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s,
    //         ];
    //     }
        
    //     function hexToOklch(hex) {
    //         const v = hex.replace("#", "");
    //         const r = s2l(parseInt(v.substr(0, 2), 16) / 255);
    //         const g = s2l(parseInt(v.substr(2, 2), 16) / 255);
    //         const b = s2l(parseInt(v.substr(4, 2), 16) / 255);
    //         const [L, A, B] = linToOklab(r, g, b);
    //         const C = Math.sqrt(A * A + B * B);
    //         let H = (Math.atan2(B, A) * 180) / Math.PI;
    //         if (H < 0) H += 360;
    //         return { L, C, H };
    //     }
        
    //     const inGamut = (rgb) => rgb.every((c) => c >= -0.0005 && c <= 1.0005);
        
    //     function oklchToHex(L, C, H) {
    //         const hr = (H * Math.PI) / 180;
    //         let lo = 0, hi = C, best = 0;
    //         for (let i = 0; i < 24; i++) {
    //             const mid = (lo + hi) / 2;
    //             if (inGamut(oklabToLin(L, mid * Math.cos(hr), mid * Math.sin(hr)))) {
    //                 best = mid; lo = mid;
    //             } else {
    //                 hi = mid;
    //             }
    //         }
    //         const lin = oklabToLin(L, best * Math.cos(hr), best * Math.sin(hr));
    //         const to = (c) =>
    //         Math.round(Math.min(1, Math.max(0, l2s(c))) * 255)
    //             .toString(16)
    //             .padStart(2, "0");
    //         return "#" + to(lin[0]) + to(lin[1]) + to(lin[2]);
    //     }
        
    //     const { C, H } = hexToOklch(baseHex);
    //     const maxC = Math.max(C, 0.1) * chroma;
        
    //     const properties = STEPS.map((st, i) => {
    //         const t = (i / (STEPS.length - 1) - 0.5) * 2;
    //         const stepHue = (H + hueShift * t + 360) % 360;
    //         const hex = oklchToHex(st.L, maxC * st.e, stepHue);
    //         return `  --${prefix}-${st.n}: ${hex};`;
    //     });
        
    //     if (!selector) return properties.map((d) => d.trim()).join("\n");
    //     return `${selector} {\n${properties.join("\n")}\n}`;
    // }

    const styles = [
    //#region Colors
    `
        #app {
            --nhcb-seen-300: #9cc2ff;
            --nhcb-seen-950: #0a2249;
            --nhcb-read-300: #76d99b;
            --nhcb-read-950: #002c15;
            --nhcb-liked-300: #76dd63;
            --nhcb-liked-950: #042d00;
            --nhcb-passed-300: #eca0f2;
            --nhcb-passed-950: #351338;
            --nhcb-read-later-300: #dbbe69;
            --nhcb-read-later-950: #2d2200;

           
        }
    `,
    // original colors
    // ${colorScale('#22C55E', {prefix: 'nhcb-read'})}
    // --nhcb-read-300: #78da8e;
    // --nhcb-read-950: #002d0e;
    //
    // ${colorScale('#3B82F6', {prefix: 'nhcb-seen'})}
    // ${colorScale('#14c271', {prefix: 'nhcb-read'})}
    // ${colorScale('#4fe929', {prefix: 'nhcb-liked'})}
    // ${colorScale('#d771e0', {prefix: 'nhcb-passed'})}
    // ${colorScale('#e2ba35', {prefix: 'nhcb-read-later'})}
    //#endregion
    //#region Basic Element Styles
    `
        /* Field Layout */
        .nhcb-field-layout {
            display: flex;
            align-items: center;
            white-space: nowrap;
            margin-top: 2px;
            margin-botton: 2px;
        }
        .nhcb-field-layout .nhcb-button {
            margin-left: 6px;
            margin-right: 0px;
        }
        .nhcb-field-layout .nhcb-button:last-child {
            margin-right: 0px;
        }
        .nhcb-field-layout .nhcb-input {
            margin: 3px;
            margin-left: 9px;
        }
        .nhcb-field-layout .nhcb-input:first-child {
            margin-left: 0;
        }
        .nhcb-field-layout .nhcb-dropdown-select {
            width: 100%;
            margin: 3px;
            margin-left: 9px;
        }
        .nhcb-field-layout .nhcb-searchable-dropdown {
            margin: 3px;
            margin-left: 0px;
            width: 100%;
        }
        
        /* Button */
        .btn-group > .nhcb-button {
            font-size: 1rem;
        }
        .nhcb-button {
            white-space: nowrap;
            flex-shrink: 0;
        }
        .nhcb-button.btn-primary:hover,
        .nhcb-button.btn-primary:active,
        .nhcb-button.btn-primary:focus {
            background-color: var(--accent);
        }
        .nhcb-button.btn-primary:not(:disabled):hover,
        .nhcb-button.btn-primary:not(:disabled):active {
            background-color: var(--accent-hover);
        }
        .nhcb-button.btn-secondary:hover {
            background-color: var(--bg-elevated);
        }
        .nhcb-button.btn-secondary:not(:disabled):hover,
        .nhcb-button.btn-secondary:not(:disabled):active {
            background-color: var(--bg-input);
        }
        .nhcb-button.btn-square {
            width: 40px;
            height: 40px;
            margin: 3px;
            vertical-align: middle;
            background-color: var(--bg-elevated);
        }
        .nhcb-button.btn-square:hover,
        .nhcb-button.btn-square:active {
            background-color: var(--bg-elevated);
        }
        .nhcb-button.btn-square:not(:disabled):hover,
        .nhcb-button.btn-square:not(:disabled):active{
            background-color: var(--bg-input);
        }
        .nhcb-button.nhcb-btn-toggle {
            background-color: #3d9e48;
        }
        .nhcb-button.nhcb-btn-toggle:not(:disabled):hover,
        .nhcb-button.nhcb-btn-toggle:not(:disabled):active {
            background-color: #52bc5e;
        }
        .nhcb-button.nhcb-btn-toggle.nhcb-btn-toggle-alt {
            background-color: rgb(218, 53, 53);
        }
        .nhcb-button.nhcb-btn-toggle.nhcb-btn-toggle-alt:hover,
        .nhcb-button.nhcb-btn-toggle.nhcb-btn-toggle-alt:not(:disabled):active {
            background-color: #e26060;
        }

        .nhcb-button:disabled {
            cursor: default;
        }        
        #info .buttons .nhcb-button.btn-square {
            min-width: unset;
        }

        /* Split Button */
        .nhcb-split-button {
            position: relative;
            display: inline-flex;
            margin: 3px;
        }

        .nhcb-split-button-main,
        .nhcb-split-button-toggle {
            cursor: pointer;
            color: #fff;
            background: var(--accent);
            padding: 0 12px;
            height: 40px;
            line-height: 40px;
            border: none;
        }
        .nhcb-split-button-main {
            border-top-left-radius: 3px;
            border-bottom-left-radius: 3px;
            font-weight: 700;
        }
        .nhcb-split-button-toggle {
            border-top-right-radius: 3px;
            border-bottom-right-radius: 3px;
            margin-left: 3px;
            padding: 0 .5em;
            display: grid;
            place-items: center;
        }
        .nhcb-split-button-main:not(:disabled):hover,
        .nhcb-split-button-toggle:not(:disabled):hover {
            background: var(--accent-hover);
        }

        .nhcb-split-button-main:disabled,
        .nhcb-split-button-toggle:disabled {
            opacity: .6;
            cursor: default;
        }

        .nhcb-split-button-toggle i { 
            transition: transform .15s ease;
        }
        .nhcb-split-button-toggle[aria-expanded="true"] i {
            transform: rotate(180deg);
        }

        .nhcb-split-button-menu {
            position: absolute;
            top: calc(100% + 6px);
            right: 0;
            min-width: 100%;
            background: var(--bg-elevated);
            border: none;
            border-radius: 3px;
            padding: 0;
            z-index: 100;
            box-shadow: 0 0 30px var(--shadow);
        }

        .nhcb-split-button-menu-item {
            cursor: pointer;
            display: block;
            width: 100%;
            text-align: left;
            white-space: nowrap;
            padding: 0 10px;
            line-height: 40px;
            height: 40px;
            margin: 3px 0;
            border: none;
            font-weight: 700;
            background-color: transparent;
            color: var(--text-primary);
        }
        .nhcb-split-button-menu-item:hover,
        .nhcb-split-button-menu-item:focus {
            background: rgba(255,255,255,.08);
        }

        /* Input */
        .nhcb-input {
            display: block;
            height: 40px;
            width: 100%;
            padding: 8px 12px;
            border-radius: 4px;
        }
        .nhcb-input:disabled {
            color: var(--text-muted) !important;
            background: hsl(0, 0%, 20%) !important;
        }

        /* Dropdown Select */
        .nhcb-dropdown-select {
            display: inline-block;
            height: 40px;

            padding: 8px 16px 8px 12px;
            border-radius: 4px;
            border: var(--input-border);

            color: var(--text-primary);
            background-color: var(--bg-input);

            cursor: pointer;
        }
        .nhcb-dropdown-select:not(:disabled):hover {
            color: var(--text-bright);
            background-color: var(--bg-hover);
        }
        .nhcb-dropdown-select:focus {
            color: var(--text-primary);
            background-color: var(--bg-input);
        }
        .nhcb-dropdown-select:disabled {
            color: var(--text-muted) !important;
            background-color: hsl(0, 0%, 20%) !important;
            cursor: default !important;
        }
        .nhcb-dropdown-select option {
            padding: 8px 12px;
        }

        /* Tooltip */
        .nhcb-tooltip {
            border-bottom: none;
            margin-left: 2px;
        }
        .nhcb-tooltip > i {
            font-size: 1.25em;
            vertical-align: middle;
            margin: 2px;
            margin-top: 0; /* don't know why this is but it's off by 2px in some cases without it */
        }
        .nhcb-tooltip > i:hover {
            color: var(--text-bright);
        }
        .nhcb-tooltip-info {
            text-align: center;
            font-size: 14px;
            white-space: normal;
            top: -1em !important;
        }
        .nhcb-tooltip:hover {
            z-index: 99999999; /* for flip state */
        }
        .nhcb-tooltip-info.nhcb-tooltip-flip {
            transform: translate(-50%,25%);
        }
        .nhcb-tooltip-info.nhcb-tooltip-flip i {
            top: unset;
            bottom: 100%;
            transform: rotate(180deg);
        }
        h1 .nhcb-tooltip i, h2 .nhcb-tooltip i, h3 .nhcb-tooltip i,
        h4 .nhcb-tooltip i, h5 .nhcb-tooltip i, h6 .nhcb-tooltip i {
            font-size: 1em;
        }

        /* Safety Lock */
        .nhcb-safety-lock {
            display: inline-flex;
            align-items: center;
            vertical-align: middle;
            cursor: pointer;
            user-select: none;
            margin: 4px 8px;
        }
        .nhcb-safety-lock:hover {
            color: var(--text-bright);
        }
        .nhcb-safety-lock input[type="checkbox"] {
            position: absolute;
            opacity: 0;
            width: 0;
            height: 0;
            pointer-events: none;
        }
        .nhcb-safety-lock i {
            font-size: 22px;
            margin: 2px;
        }
        .nhcb-safety-lock i.fa-lock-open {
            font-size: 22px;
            margin-right: -3.5px;
        }
        
        /* Gallery Labels */
        .nhcb-gallery-label {
            display: inline-flex;
            vertical-align: middle;
            margin: .13em;
            color: var(--text-primary);
            font-size: 1em;
        }
        .nhcb-gallery-label .nhcb-gallery-label-name {
            border-top-left-radius: .3em;
            border-bottom-left-radius: .3em;
        }
        .nhcb-gallery-label:has(button.hidden) .nhcb-gallery-label-name {
            border-top-right-radius: .3em;
            border-bottom-right-radius: .3em;
        }
        .nhcb-gallery-label button {
            border-top-right-radius: .3em;
            border-bottom-right-radius: .3em;
        }
        .nhcb-gallery-label .nhcb-gallery-label-name {
            font-weight: 700;
            display: flex;
            align-items: center;
            padding: .13em .39em;
            background: var(--bg-input);
            word-break: break-word;
            overflow-wrap: anywhere;
        }
        .nhcb-gallery-label button {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            padding: .13em .39em;
            border: 0;
            background-color: var(--border);
            color: var(--text-secondary);
            font-size: 1.2em;
            cursor: pointer;
            z-index: 10;
        }
        .nhcb-gallery-label button:hover {
            color: var(--text-bright);
            background-color: var(--bg-hover);
        }
        .nhcb-gallery-label a.nhcb-gallery-label-name:hover {
            color: var(--text-bright);
            background-color: var(--bg-hover);
        }
        .nhcb-label-box {
            min-height: 20px;
            border-radius: 3px;
            background-color: hsl(0, 0%, 20%);;
            padding: 5px;
            margin: 5px 0;
        }
        .nhcb-label-box .nhcb-label-box-placeholder {
            display: none;
            color: var(--text-secondary);
            padding: .23em;
        }
        .nhcb-label-box .nhcb-label-box-placeholder:last-child {
            display: inline-block;
        }
        
        /* Searchable Dropdown */
        .nhcb-searchable-dropdown {
            position: relative;
            display: inline-block;
        }
        .nhcb-searchable-dropdown .nhcb-input{
            margin: 0;
        }
        .nhcb-searchable-dropdown-options {
            position: absolute;
            top: calc(100% + 5px);
            left: 0;
            right: auto;
            min-width: 100%;
            width: 180px;
            max-width: calc(100vw - 100px);
            margin: 0;
            padding: 0;
            list-style: none;
            color: var(--text-primary);
            background: var(--bg-raised);
            border: 1px solid var(--border);
            border-radius: 3px;
            box-shadow: 0 4px 30px var(--shadow);
            z-index: 100;
            max-height: 513.2px; /* hardcoded version of calc((.4em * 2 + 20px + 1px) * 16); */
            overflow-y: auto;
        }
        .nhcb-searchable-dropdown-option {
            padding: .4em .6em;
            gap: .5em;
            cursor: pointer;
            white-space: nowrap;
            border-bottom: 1px solid var(--border);
        }
        .nhcb-searchable-dropdown-options .nhcb-searchable-dropdown-option:last-child {
            border-bottom: 0;
        }
        .nhcb-searchable-dropdown-option:not(.nhcb-option-disabled):hover,
        .nhcb-searchable-dropdown-option.selected {
            background: var(--bg-hover);
        }
        .nhcb-searchable-dropdown-options:hover .nhcb-searchable-dropdown-option.selected:not(:hover) {
            background: unset;
        }
        .nhcb-searchable-dropdown-option.nhcb-option-disabled {
            color: var(--text-muted);
            cursor: not-allowed;
        }
        .nhcb-searchable-dropdown-empty {
            padding: .4em .6em;
            color: var(--text-muted);
        }
    `,
    //#endregion

    //#region Site Element Styles
    `
        /* Sorts */
        .nhcb-sort-container + .nhcb-sort-container {
            margin-top: -30px;
        }
        
        /* Nav Group */
        .nhcb-nav-group {
            position: relative;
        }
        .nhcb-nav-group .nhcb-nav-group-button {
            display: inline-block;
            height: 50px;
            line-height: 50px;
            padding: 0 10px;
            background: transparent;
            border: 0;
            color: inherit;
            font: inherit;
            cursor: pointer;
        }
        .nhcb-nav-group .nhcb-nav-group-button:hover {
            background-color:var(--nav-hover)
        }
        .nhcb-nav-group .nhcb-nav-group-button i {
            font-size: .7em;
            margin-left: .35em;
            opacity: .7;
        }
        .nhcb-nav-group:has(.nhcb-nav-group-menu .active) > .nhcb-nav-group-button /* contiains active link highlight */ {
            background-color: var(--accent);
            color: #fff;
        }
        .nhcb-nav-group .nhcb-nav-group-menu {
            display: none;
            list-style: none;
            margin: 0;
            padding: .3em 0;
            position: absolute;
            top: 100%;
            left: 0;
            min-width: 12em;
            background-color: var(--nav-hover);
            border-radius: 3px;
            box-shadow: 0 0 30px var(--shadow);
            z-index: 30;
        }
        .nhcb-nav-group .nhcb-nav-group-menu.open,
        .nhcb-nav-group .nhcb-nav-group-menu li,
        .nhcb-nav-group .nhcb-nav-group-menu li a {
            display: block;
        }

        .nhcb-nav-group .nhcb-nav-group-menu li a {
            padding: .4em .9em;
            height: auto;
            line-height: 1.6;
            white-space: nowrap;
        }
        .nhcb-nav-group .nhcb-nav-group-menu li a:hover {
            filter:brightness(1.3)
        }
        @media(max-width:644px) {
            .nhcb-nav-group {
                display: block !important;
            }
            .nhcb-nav-group .nhcb-nav-group-button {
                display: none;
            }
            .nhcb-nav-group .nhcb-nav-group-menu {
                display: block;
                position: static;
                background: transparent;
                box-shadow: none;
                padding: 0;
                min-width: 0;
            }
            .nhcb-nav-group .nhcb-nav-group-menu li a {
                height:48px;
                line-height:48px;
                padding:0;
            }
        }

        /* Tag Chip */
        .nhcb-tagchip.variant-pill {
            flex: 0 0 auto;
            display: inline-flex;
            vertical-align: middle;
            margin: .13em;
            max-width: 100%;
            text-decoration: none;
            color: var(--text-primary);
            font-size: 1em;
        }
        .nhcb-tagchip.variant-pill:hover {
            filter: brightness(1.3);
        }
        .nhcb-tagchip.variant-pill > :first-child {
            border-top-left-radius:.3em;
            border-bottom-left-radius:.3em;
        }
        .nhcb-tagchip.variant-pill > :last-child {
            border-top-right-radius:.3em;
            border-bottom-right-radius:.3em
        }
        .nhcb-tagchip.variant-pill .type,
        .nhcb-tagchip.variant-pill .name,
        .nhcb-tagchip.variant-pill .count {
            display: flex;
            align-items: center;
            padding: .13em .39em;
        }
        .nhcb-tagchip.variant-pill .name {
            background: var(--bg-input);
            min-width: 0;
            word-break: break-word;
            overflow-wrap: anywhere;
        }
        .nhcb-tagchip.variant-pill .count {
            font-size: .9em;
            font-weight: 400;
            font-variant-numeric: tabular-nums;
            padding: .13em .26em;
            background: var(--border);
            color: var(--text-primary);
        }
        .nhcb-tagchip.variant-pill .type {
            font-size: .85em;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: .04em;
            color: var(--text-secondary);
            background: var(--bg-elevated);
        }
        .nhcb-tagchip.variant-pill .type-parody {
            background: #20604a;
            color: #fff;
        }
        .nhcb-tagchip.variant-pill .type-character {
            background: #265973;
            color: #fff;
        }
        .nhcb-tagchip.variant-pill .type-tag {
            /* sadge */
        }
        .nhcb-tagchip.variant-pill .type-artist {
            background: #592673;
            color: #fff;
        }        
        .nhcb-tagchip.variant-pill .type-group {
            background: #735926;
            color: #fff;
        }
        .nhcb-tagchip.variant-pill .type-language {
            background: #364563;
            color: #fff;
        }
        .nhcb-tagchip.variant-pill .type-category {
            background: #862d2d;
            color: #fff;
        }
        
        /* Pagination */
        .nhcb-pagination {
            font-size: 1.3em;
            margin-bottom: 2em;
            margin-top: 2em;
        }
        .nhcb-pagination .current {
            font-weight:700;
            border-radius:100%;
            background-color:var(--bg-highlight)
        }
        .nhcb-pagination-page,
        .nhcb-pagination-first,
        .nhcb-pagination-next,
        .nhcb-pagination-previous,
        .nhcb-pagination-last {
            display:inline-block;
            min-width:35px;
            padding:5px
        }
        .nhcb-pagination-page:hover,
        .nhcb-pagination-first:hover,
        .nhcb-pagination-next:hover,
        .nhcb-pagination-previous:hover,
        .nhcb-pagination-last:hover {
            border-radius:100%;
            background-color:var(--bg-elevated)
        }

        /* Time Ago Display */
        .nhcb-time-ago-display {
            font-weight: 400;
            font-variant-numeric: tabular-nums;
        }
        .nhcb-time-ago-display span {
            opacity: .6;
        }

        /* Info Section */
        .nhcb-info-name {
            font-weight: 700;
        }
        .nhcb-info-name .nhcb-info-content {
            font-weight: 400;
        }

        /* Search Results Header */
        .nhcb-header-row {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: .75rem;
            flex-wrap: wrap;
            margin-bottom: 1rem;
        }
        .nhcb-header-row .fa-search {
            color: var(--accent);
        }
        .nhcb-header-row h1 {
            margin: 0;
        }
    `,
    //#endregion

    //#region Combo Element Styles
    `
        /* Dropdown Field */
        .nhcb-dropdown-field {
            margin-top: 2px;
            margin-bottom: 2px;
        }
        .nhcb-dropdown-field .nhcb-tooltip {
            margin-right: 8px;
        }
        
        /* Dropdown Menu */
        .nhcb-dropdown-wrapper {
            display: inline-block;
            position: relative;
            vertical-align: middle;
        }
        .nhcb-dropdown-button {
            margin: 0 !important;
        }
        .nhcb-dropdown-menu {
            display: inline-block;
            position: absolute;
            left: 50%;
            top: 100%;
            border-radius: 3px;
            padding: 6px 0;
            background-color: var(--nav-hover);
            z-index: 15;
            box-shadow: 0 0 30px var(--shadow);
            min-width: 40px;
            min-height: 20px;
            transform: translate(-50%, 0);
        }
        .nhcb-dropdown-menu.nhcb-menu-open:before {
            position: absolute;
            content: "";
            pointer-events: none;
            bottom: 100%;
            left: 50%;
            margin-left: -10px;
            border-color: transparent transparent var(--nav-hover) transparent;
            border-style: solid;
            border-width: 10px 10px 10px 10px;
            height: 0px;
            width: 0px;
        }
        #info .buttons .nhcb-dropdown-wrapper {
            margin: 3px 5px 10px 0px;
        }

        /* Notes Field */
        .nhcb-notes-field textarea {
            display: block;
            width: 100%;
            border: var(--input-border);
            border-radius: 4px;

            height: calc(3lh + 16px);
            line-height: 20px;
            padding: 8px 12px;
            margin: 8px 0px;

            box-shadow: none;
            outline: none;
        }
        .nhcb-notes-field textarea[readonly] {
            background: hsl(0, 0%, 20%);
            color: inherit;
            cursor: text;
            caret-color: transparent;
        }
        .nhcb-notes-field textarea[readonly]::placeholder {
            text-align: center;
        }
        .nhcb-notes-field textarea[readonly]:placeholder-shown {
            height: calc(1lh + 16px);
            cursor: default;
        }
    `,
    //#endregion

    //#region Special Element Styles
    `
        #nhcb-notifier {
            position: fixed;
            bottom: 16px;
            right:  16px;
            display: flex;
            flex-direction: column;
            align-items: flex-end;
            gap: 8px;
            z-index: 999999;
            pointer-events: none;
        }
        .nhcb-notice {
            pointer-events: auto;
            user-select: none;
            padding: 10px 14px;
            border-radius: 6px;
            background: var(--bg-elevated);
            min-width: 200px;
            max-width: 350px;
            width: fit-content;
            box-shadow: 0 1px 8px 4px var(--shadow);
            cursor: pointer;
            opacity: .8;
        }
        .nhcb-notice:hover {
            background: var(--bg-input);
            opacity: 1;
        }
        .nhcb-notice-info {
            color: var(--text-primary);
        }
        .nhcb-notice-warn {
            color: var(--warning);
            border: 1px solid var(--warning);
        }
        .nhcb-notice-error {
            color: var(--error);
            border: 1px solid var(--error);
        }

        /* Modal */
        @container scroll-state(scrollable: y)
        body:has(.nhcb-modal-overlay) {
            /* overflow: hidden; decdided against this */
        }
        .nhcb-modal-overlay {
            z-index: 1000;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: #000c;
            display: flex;
            align-items: flex-start;
            justify-content: center;
            overflow-y: auto;
            padding: 5vh 0;
        }
        .nhcb-modal-container {
            background: var(--bg-highlight);
            padding: 20px;
            border-radius: 5px;
            max-width: 90%;
            margin: auto;
        }
        .nhcb-modal-header {
            margin-top: 0;
            text-align: center;
        }
        .nhcb-modal-buttons {
            margin-top: 16px;
            display: flex;
            gap: 10px;
            justify-content: center;
        }

        /* Form */
        .nhcb-form {
            margin: 12px auto;
            padding: 16px;
            border: 1px solid #ccc;
            border-radius: 6px;
            width: 400px;
            display: grid;
            gap: 12px;
        }
        .nhcb-form input {
            display: block;
            width: 100%;
            padding: 8px;
            border-radius: 4px;
        }

        /* Content Warning Edit */
        .nhcb-cw-rule {
            display: flex;
            align-items: center;
            margin: 6px;
        }
        .nhcb-cw-rule-label {
            font-weight: 700;
            padding: 4px 8px;
            background: rgba(125,8,8,.7);
            border-radius: 10px;
        }
        .nhcb-cw-rule-order-button {
            margin: 2px;
            border-radius: 50%;
            width: 25px;
            height: 25px;
            line-height: 1em;
            padding: 0;
        }
        .nhcb-cw-rule:first-child :nth-child(1 of .nhcb-cw-rule-order-button) {
            visibility: hidden;
        }
        .nhcb-cw-rule:last-child :nth-child(2 of .nhcb-cw-rule-order-button) {
            visibility: hidden;
        }
        .nhcb-cw-rule-conditions-display {
            flex: 1;
            align-content: center;
        }
        .nhcb-cw-rule-condition {
            display: inline-block;
            white-space: nowrap;
            font-size: 1em;
            font-weight: 700;
            margin: .13em;
            padding: .13em .39em;
            color: var(--text-primary);
            background: var(--bg-input);
            border-radius: .3em;
        }
        .nhcb-cw-rule-condition i {
            margin-right: 2px;
        }
        .nhcb-cw-rule-condition i.fa-check {
            color: var(--success);
        }
        .nhcb-cw-rule-condition i.fa-times {
            color: var(--accent-hover);
        }
        .nhcb-cw-edit-tag {
            display: flex;
            align-items: center;
            min-width: 350px;
        }
        .nhcb-cw-edit-tag input {
            margin: 2px;
        }
        .nhcb-cw-edit-tag span {
            display: inline-block;
            white-space: nowrap;
            font-size: 1em;
            font-weight: 700;
            margin: 0 auto;
            padding: .13em .39em;
            color: var(--text-primary);
            background: var(--bg-input);
            border-radius: .3em;

        }

        /* Custom Search */
        .nhcb-custom-search {
            position: relative;
            display: flex;
            width: calc(100vw - 50px);
            min-width: 450px;
            max-width: 800px;
            align-items: center;
            margin: 0 auto;
            margin-bottom: 16px;
        }
        .nhcb-custom-search label, 
        .nhcb-custom-search .nhcb-tooltip i {
            font-size: 18px;
        }
        .nhcb-custom-search .nhcb-input {
            margin: 0;
            margin-left: .5em;
            border-top-right-radius: 0;
            border-bottom-right-radius: 0;
        }
        .nhcb-custom-search-button {
            background-color: var(--accent) !important;
            margin: 0 !important;
            border-top-left-radius: 0;
            border-bottom-left-radius: 0;
        }
        .nhcb-custom-search-button:hover {
            background-color: var(--accent-hover) !important;
        }
        .nhcb-custom-search-button i {
            font-size: 1.33333em;
            vertical-align: -.0667em;
        }
        .nhcb-custom-search-options {
            position: absolute;
            top: calc(100% + 5px);
            left: 167px;
            right: auto;
            min-width: calc(100% - 167px);
            width: 300px;
            max-width: calc(100vw - 100px);
            margin: 0;
            padding: 0;
            list-style: none;
            color: var(--text-primary);
            background: var(--bg-raised);
            border: 1px solid var(--border);
            border-radius: 3px;
            box-shadow: 0 4px 30px var(--shadow);
            z-index: 100;
            max-height: 386.4px; /* hardcoded version of calc((.4em * 2 + 20px + 1px) * 12 + 2px); */
            overflow-y: auto;
        }
        .nhcb-custom-search-option {
            display: flex;
            align-items: center;
            padding: .4em .6em;
            gap: .5em;
            cursor: pointer;
            white-space: nowrap;
            border-bottom: 1px solid var(--border);
            overflow: hidden;
            white-space: nowrap;
        }
        .nhcb-custom-search-option .nhcb-custom-search-tag-type {
            font-size: .75em;
            text-transform: uppercase;
            letter-spacing: .04em;
            padding: .1em .5em;
            border-radius: 3px;
            background: var(--bg-elevated);
            color: var(--text-secondary);
        }
        .nhcb-custom-search-option .nhcb-tag-type-artist {
            background: #592673;
            color: #fff
        }
        .nhcb-custom-search-option .nhcb-tag-type-character {
            background: #265973;
            color: #fff;
        }
        .nhcb-custom-search-option .nhcb-tag-type-parody {
            background: #20604a;
            color: #fff;
        }
        .nhcb-custom-search-option .nhcb-tag-type-group {
            background: #735926;
            color: #fff;
        }
        .nhcb-custom-search-option .nhcb-tag-type-language {
            background: #364563;
            color: #fff;
        }
        .nhcb-custom-search-option .nhcb-tag-type-category {
            background: #862d2d;
            color: #fff;
        }
        .nhcb-custom-search-option .nhcb-custom-search-option-label {
            white-space: nowrap;
        }
        .nhcb-custom-search-option .nhcb-custom-search-option-description {
            flex: 1;
            min-width: 0;
            color: var(--text-muted);
            font-size: .85em;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            text-align: right;
        }
            
        .nhcb-custom-search-options .nhcb-custom-search-option:last-child {
            border-bottom: 0;
        }
        .nhcb-custom-search-option:hover,
        .nhcb-custom-search-option.selected {
            background: var(--bg-hover);
        }
        .nhcb-custom-search-option:hover .nhcb-custom-search-option-description,
        .nhcb-custom-search-option.selected .nhcb-custom-search-option-description {
            color: var(--text-primary);
        }
        .nhcb-custom-search-options:hover .nhcb-custom-search-option.selected:not(:hover) {
            background: unset;
        }
        .nhcb-custom-search-options:hover .nhcb-custom-search-option.selected:not(:hover) .nhcb-custom-search-option-description {
            color: var(--text-secondary);
        }

    `,
    //#endregion

    //#region Custom Button Styles
    `
        /* Tag Sentiment Button */
        #nhcb-tag-sentiment-edit {
            font-size: 14px;
            height: auto;
            line-height: initial;
        }
        #nhcb-tag-sentiment-edit .nhcb-split-button-main {
            height: auto;
            line-height: initial;
            padding: 6px 10px;
        }
        #nhcb-tag-sentiment-edit .nhcb-split-button-toggle {
            height: auto;
            line-height: initial;
            padding-top: 6px;
            padding-bottom: 6px;
        }
        #nhcb-tag-sentiment-edit .nhcb-split-button-main,
        #nhcb-tag-sentiment-edit .nhcb-split-button-toggle {
            background: #3d9e48;
        }
        #nhcb-tag-sentiment-edit .nhcb-split-button-main:not(:disabled):hover,
        #nhcb-tag-sentiment-edit .nhcb-split-button-toggle:not(:disabled):hover {
            background: #52bc5e;
        }
        #nhcb-tag-sentiment-edit.nhcb-has-status .nhcb-split-button-main,
        #nhcb-tag-sentiment-edit.nhcb-has-status .nhcb-split-button-toggle {
            background: #da3535;
        }
        #nhcb-tag-sentiment-edit.nhcb-has-status .nhcb-split-button-main:not(:disabled):hover,
        #nhcb-tag-sentiment-edit.nhcb-has-status .nhcb-split-button-toggle:not(:disabled):hover {
            background: #e26060;
        }
        #nhcb-tag-sentiment-edit .nhcb-split-button-toggle i {
            margin-top: 2px;
        }

        /* Browsed Button */
        .nhcb-browsed-button {
            height: auto;
            line-height: initial;
            font-size: 14px;
            padding: 6px 10px;
        }

        /* Browse Later Button */
        .nhcb-browse-later-button {
            height: auto;
            line-height: initial;
            font-size: 14px;
            padding: 6px 10px;
        }

        /* Alt Site Suggestions */
        .nhcb-link-button {
            display: inline-block;
            font-size: 14px;
            padding: .75rem 1.25rem;
            margin: .5rem;
            background-color: rgb(56, 56, 56);
            color: var(--text-bright);
            text-decoration: none;
            border-radius: 4px;
            font-weight: 700;
            transition: background-color .2s;
        }
        .nhcb-link-button:hover {
            background: var(--bg-input);
        }
    `,
    //#endregion

    //#region Gallery List Styles
    `
        /* Darken non-english */
        .gallery:not(.lang-gb):not(.nhcb-gb):not(.nhcb-gb-multi):not(.nhcb-is-read):not(.nhcb-is-read-later):not(.nhcb-is-liked):not(.nhcb-is-passed) .cover img,
        .gallery:not(.lang-gb):not(.nhcb-gb):not(.nhcb-gb-multi):not(.nhcb-is-read):not(.nhcb-is-read-later):not(.nhcb-is-liked):not(.nhcb-is-passed) .cover .caption {
            opacity: ${formatOpacity(settingsStore.opacityNotEnglish.load())};
        }

        /* Darken read galleries */
        .gallery.nhcb-is-read-later .cover img,
        .gallery.nhcb-is-read-later .cover .caption {
            opacity: ${formatOpacity(settingsStore.opacityReadLater.load())};
        }
        .gallery.nhcb-is-liked .cover img,
        .gallery.nhcb-is-liked .cover .caption {
            opacity: ${formatOpacity(settingsStore.opacitLiked.load())};
        }
        .gallery.nhcb-is-passed .cover img,
        .gallery.nhcb-is-passed .cover .caption {
            opacity: ${formatOpacity(settingsStore.opacityPassed.load())};
        }
        .gallery.nhcb-is-read .cover img,
        .gallery.nhcb-is-read .cover .caption {
            opacity: ${formatOpacity(settingsStore.opacityRead.load())};
        }
        .gallery.nhcb-is-seen .cover img,
        .gallery.nhcb-is-seen .cover .caption {
            opacity: ${formatOpacity(settingsStore.opacitySeen.load())};
        }
        

        /* Fix mislabled language */
        .gallery.nhcb-gb .caption:before {
            background-image:url(../../../flags/gb.svg) !important;
        }
        .gallery.nhcb-gb-multi .caption:after {
            content: "";
            width: 24px;
            height: 16px;
            display: inline-block;
            position: absolute;
            top: 3px;
            left: 3px;
            background-size: contain;
            background-repeat: no-repeat;
            background-image:url(../../../flags/gb.svg) !important;
            clip-path: rect(0 50% 100% 0);

            /* Looked odd no how I fiddle with it */
            /*clip-path: polygon(0 0, 95% 0, 5% 100%, 0 100%);*/
            /*clip-path: polygon(0 0, 100% 0, 0 100%);*/
        }

        /* Make caption readable while hovered */
        .gallery .cover:hover .caption {
            opacity: 1 !important;
        }
        
        /* Pretty Titles */
        ${settingsStore.prettyTitleListsHighlight.load() == 'always' ? 
        `.nhcb-pretty-title .nhcb-before,
        .nhcb-pretty-title .nhcb-after {
            color: var(--text-secondary);
        }`
        : settingsStore.prettyTitleListsHighlight.value == 'hover' ?
        `.nhcb-pretty-title:hover .nhcb-before,
        .nhcb-pretty-title:hover .nhcb-after {
            color: var(--text-secondary);
        }`
        : settingsStore.prettyTitleListsHighlight.value == 'nothover' ?
        `.nhcb-pretty-title:not(:hover) .nhcb-before,
        .nhcb-pretty-title:not(:hover) .nhcb-after {
            color: var(--text-secondary);
        }`
        : ''}

        ${settingsStore.prettyTitleListsShorten.load() == 'always' ? 
        `.nhcb-pretty-title .nhcb-before,
        .nhcb-pretty-title .nhcb-after {
            display: none;
        }`
        : settingsStore.prettyTitleListsShorten.value == 'hover' ?
        `.nhcb-pretty-title:hover .nhcb-before,
        .nhcb-pretty-title:hover .nhcb-after {
            display: none;
        }`
        : settingsStore.prettyTitleListsShorten.value == 'nothover' ?
        `.nhcb-pretty-title:not(:hover) .nhcb-before,
        .nhcb-pretty-title:not(:hover) .nhcb-after {
            display: none;
        }`
        : ''}
    `,
    //#endregion

    // good combos
    // 300-85/950-70
    // 100-85/700-70
    // 50-80/700-70
    //#region Badges Styles
    `
        .nhcb-gallery-cover-badges {
            position: relative;
            display: block;
            width: fit-content;
            height: fit-content;
            margin: 0 auto;
            line-height: 0;
        }
        .nhcb-gallery-cover-badge {
            line-height: 14px;
            zoom: 1.1;
        }
        .nhcb-view-system-badge {
            position: absolute;
            bottom: 7px;
            right: 7px;
            border-radius: 50%;
            width: 2em;
            height: 2em;
            font-size: 14px;
            opacity: 1;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .nhcb-read-later-badge {
            color: rgba(from var(--nhcb-read-later-300) r g b / 85%);
            background-color: rgba(from var(--nhcb-read-later-950) r g b / 70%);
        }
        .nhcb-read-badge {
            color: rgba(from var(--nhcb-read-300) r g b / 85%);
            background-color: rgba(from var(--nhcb-read-950) r g b / 70%);
        }
        .nhcb-liked-badge {
            color: rgba(from var(--nhcb-liked-300) r g b / 85%);
            background-color: rgba(from var(--nhcb-liked-950) r g b / 70%);
        }
        .nhcb-passed-badge {
            color: rgba(from var(--nhcb-passed-300) r g b / 85%);
            background-color: rgba(from var(--nhcb-passed-950) r g b / 70%);
        }
        .nhcb-seen-badge {
            color: rgba(from var(--nhcb-seen-300) r g b / 85%);
            background-color: rgba(from var(--nhcb-seen-950) r g b / 70%);
        }

        .nhcb-browse-system-badge {
            font-size: .75em;
            padding: 0;
            margin: 0;
            margin-left: .5em;
            display: inline-flex;
            justify-content: center;
            align-items: center;
            opacity: .7;
            transition: opacity .12s;
        }
        .nhcb-browse-system-badge:hover {
            opacity: 1;
        }
        .nhcb-browse-later-badge {
            margin-left: .4em;
        }
        .nhcb-browse-later-badge i {
            margin-top: .1em;
        }

        .nhcb-favorite-badge {
            position: absolute;
            bottom: 7px;
            left: 7px;
            border-radius: 1em;
            height: 2em;
            font-size: 14px;
            opacity: 1;
            display: flex;
            justify-content: center;
            align-items: center;
            color: rgba(255,255,255,.8);
            background-color: rgba(273, 37, 83, .7);   
            padding: 0 7px;
        }
        .nhcb-favorite-badge i.fa-heart {
            margin: 0;
        }
        .nhcb-favorite-badge .nhcb-favorite-rating {
            font-weight: 700;
            padding: 0 2px;
            padding-bottom: 1px;
            /* ended up not looking good
            color: rgba(273, 37, 83, .7);
            position: absolute;
            -webkit-text-stroke: rgba(255,255,255,.8) 3px;
            paint-order: stroke fill;*/
        }
        .nhcb-content-warning-badge {
            position: absolute;
            top: 7px;
            left: 7px;
            border-radius: 10px;
            padding: 4px 8px;
            font-size: 12px;
            font-weight: 900;
            background-color: rgba(125,8,8,.7);
            color: rgba(255,255,255,.8);
            opacity: 1;
            max-width: 50%;
            max-height: 50%;
            overflow-y: auto;
        }
        .nhcb-content-warning-badge span {
            display: block;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        .nhcb-info-badge {
            position: absolute;
            top: 7px;
            right: 7px;
            border-radius: 10px;
            padding: 4px 8px;
            font-size: 12px;
            font-weight: 700;
            color: rgba(255,255,255,.8);
            background-color: rgba(0, 0, 0, 0.7);
            opacity: 1;
            max-width: 50%;
            max-height: 50%;
            overflow-y: auto;
            display: flex;
            flex-direction: column;
        }
        .nhcb-info-badge > div {
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            display: flex;
            gap: 4px;
            justify-content: right;
            align-items: center;
        }
        .nhcb-gallery-page-count {
        }
        .nhcb-gallery-page-count-indicator {
            width: .5em;
            height: .5em;
            border-radius: 50%; 
        }
        .nhcb-artists-badge {
            height: 1.42857143em;
        }
        .nhcb-bad-translation-badge {
            height: 1.42857143em;

        }
        .nhcb-alt-source-badge {
            position: absolute;
            bottom: 7.5px;
            left: 50%;
            transform: translateX(-50%);
            border-radius: 10px;
            padding: 4px 8px;
            font-size: 12px;
            font-weight: 900;
            color: rgba(255,255,255,.8);
            background-color: rgba(0, 0, 0, 0.7);
            opacity: 1;
        }
        .nhcb-alt-source-badge .nhcb-alt-source-name-span {
            display: inline-block;
            max-width: 90px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            line-height: 1;
        }
        .nhcb-404-badge {
            position: absolute;
            top: 7.5px;
            left: 50%;
            transform: translateX(-50%);
            border-radius: 10px;
            padding: 4px 8px;
            font-size: 12px;
            font-weight: 900;
            color: rgba(255,255,255,.8);
            background-color: rgba(0, 0, 0, 0.7);
            opacity: 1;
        }
    `,
    //#endregion

    //#region Gallery Button Styles
    `
        /* View System Warpper */
        #nhcb-view-system-buttons {
            display: inline;
            font-size: 1rem;
            vertical-align: center;
        }

        #nhcb-view-system-buttons .nhcb-button {
            min-width: 60px !important;
        }

        /* Read Status Button */
        #nhcb-read-status-edit {
            font-size: 14px;
            line-height: initial;
            margin: 3px 5px 10px 0;
            vertical-align: middle;
        }
        #nhcb-read-status-edit .nhcb-split-button-main {
            line-height: initial;
            padding: 6px 10px;
        }
        #nhcb-read-status-edit .nhcb-split-button-toggle {
            line-height: initial;
            padding-top: 6px;
            padding-bottom: 6px;
        }
        #nhcb-read-status-edit .nhcb-split-button-main,
        #nhcb-read-status-edit .nhcb-split-button-toggle {
            background: #3d9e48;
        }
        #nhcb-read-status-edit .nhcb-split-button-main:not(:disabled):hover,
        #nhcb-read-status-edit .nhcb-split-button-toggle:not(:disabled):hover {
            background: #52bc5e;
        }
        #nhcb-read-status-edit.nhcb-has-status .nhcb-split-button-main,
        #nhcb-read-status-edit.nhcb-has-status .nhcb-split-button-toggle {
            background: #da3535;
        }
        #nhcb-read-status-edit.nhcb-has-status .nhcb-split-button-main:not(:disabled):hover,
        #nhcb-read-status-edit.nhcb-has-status .nhcb-split-button-toggle:not(:disabled):hover {
            background: #e26060;
        }
        #nhcb-read-status-edit .nhcb-split-button-toggle i {
            margin-top: 2px;
        }

        /* Gallery Read Button */
        /*
        .nhcb-button.nhcb-read-button,
        .nhcb-button.nhcb-read-button:hover,
        .nhcb-button.nhcb-read-button:active,
        .nhcb-buttonnhcb-read-button:focus {
            background-color: var(--nhcb-read-500);
        }
        .nhcb-button.nhcb-read-button:not(:disabled):hover,
        .nhcb-button.nhcb-read-button:not(:disabled):active {
            background-color: var(--nhcb-read-400);
        }
        .nhcb-button.nhcb-read-button.nhcb-is-read,
        .nhcb-button.nhcb-read-button.nhcb-is-read:hover,
        .nhcb-button.nhcb-read-button.nhcb-is-read:active,
        .nhcb-buttonnhcb-read-button.nhcb-is-read:focus {
            background-color: var(--nhcb-read-900);
        }
        .nhcb-button.nhcb-read-button.nhcb-is-read:not(:disabled):hover,
        .nhcb-button.nhcb-read-button.nhcb-is-read:not(:disabled):active {
            background-color: var(--nhcb-read-800);
        }
        */
    `,
    //#endregion
    
    //#region Reader Styles
    `
        /* Auto Player */
        #nhcb-auto-player {
            display: flex;
            min-height: 100%;
            align-items: center;
        }

        #nhcb-auto-player > div {
            padding: 0 5px;
        }
        #nhcb-auto-player input {
            width: 180px;
        }

        #nhcb-auto-player-labels {
            display: flex;
            justify-content: space-between;
            font-size: 8px;
            margin: -3px 10px 0;
        }

        #nhcb-auto-player-labels span {
            width: 0;
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        #nhcb-auto-player-button {
            display: block;
            padding: 0 !important;
            border-radius: 3px;
            margin: 0;
            min-height: 0;
            min-width: 0;
            height: 30px;
            width: 30px;
        }
        #nhcb-auto-player-button .fa-stop {
            margin-bottom: 4px;
        }

        /* Dont over zoom */
        .reader #image-container img { 
            ${settingsStore.readerDontOverZoom.load() ? 'max-width: 100% !important;' : 'max-width: none !important;'}
            ${settingsStore.readerZoomCapImageNaturalSize.load() ? 'object-fit: scale-down;' : ''}
        }

        /* Reader fullscreen */
        .nhcb-fullscreen-button {
            cursor: pointer;
        }
        @media (display-mode:fullscreen) {
            .reader.nhcb-allow-fullscreen #content {
                width: 100vw;
                max-height: 100vh;
            }
            .reader.nhcb-allow-fullscreen #content img {
                ${settingsStore.readerFullscreenCapImageNaturalSize.load() ? 'object-fit: scale-down;' : 'object-fit: contain;'}
                width: 100vw;
                height: calc(100vh - 80px) !important;
                background: #000;
            }
        }
    `,
    //#endregion
 
    //#region Tag List Styles
    `
        /* Tag Highlight */
        .nhcb-tag-highlight {
            border-radius: .3em;
        }
        .nhcb-tag-highlight .name {
            background-color: hsla(0, 0%, 0%, 0.0)  !important;
        }
        .nhcb-tag-highlight .count {
            background-color: hsla(0, 0%, 0%, 0.3) !important;
        }

        .nhcb-tag-highlight.nhcb-liked-tag {
            background-color: #167721;
        }
        .nhcb-tag-highlight.nhcb-dubious-tag{
            background-color: #713f12;
        }
        .nhcb-tag-highlight.nhcb-scorned-tag {
            background-color: #7f1d1d;
        }
    `,
    //#endregion

    //#region Customize Display Styles
    `
        /* Wider Gallery Containers */
        .container.index-container,
        #related-container,
        #favcontainer,
        div.container:has(.gallery-grid) {
            ${settingsStore.galleryContainerWidth.load() ? `max-width: ${settingsStore.galleryContainerWidth.value}px;` : ''}
        }        
        /* Wider Thumbnail Containers */
        #thumbnail-container {
            ${settingsStore.thumbnailContainerWidth.load() ? `max-width: ${settingsStore.thumbnailContainerWidth.value}px;` : ''}
            ${settingsStore.enableThumbnailCentering.load() ? `text-align: center;` : ''}
        }
        /* Wider Thumbnails */
        div.thumb-container {
            ${settingsStore.thumbnailWidth.load() ? 'width: auto;' : ''}
        }
        div.thumb-container img {
            ${settingsStore.thumbnailWidth.value ? `width: ${settingsStore.thumbnailWidth.value}px;` : ''}
            ${settingsStore.thumbnailWidth.value ? `max-height: ${settingsStore.thumbnailWidth.value * DEFINITIONS.THUMBNAIL_MAX_HEIGHT_FROM_WIDTH_RATIO}px;` : ''}
            ${settingsStore.thumbnailWidth.value ? `object-fit: contain;` : ''}
        }
    `,
    //#endregion

    //#region Custom Page Styles
    `
        .nhcb-custom-page-error {
            display: none !important;
        }

        /* Liked Tags */
        .nhcb-tag-container {
            padding-bottom: 5px;
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
        }
        .nhcb-tag-container > div {
            text-align: left;
            padding-right: 1em;
            padding-left: 1em;
            padding-bottom: .2em;
        }
        .nhcb-tag-container .tagchip {
            column-break-inside: avoid;
            page-break-inside: avoid;
            zoom: 125%;
        }
        .nhcb-tag-container .nhcb-browse-later-info-block {
            display: block;
            margin: 8px;
            margin-top: -.52em;
            padding: 6px 12px;
            padding-top: 8px;
            background: var(--bg-elevated);
            border-radius: .3em;
            overflow-wrap: break-word;
            width: fit-content;
        }
        .nhcb-tag-container .nhcb-browse-later-info-section {
            display: block;
            font-weight: 700;
        }
        .nhcb-tag-container .nhcb-browse-later-info-section .nhcb-browse-later-info {
            display: inline;
            font-weight: 400;
            margin-left: .5em;
        }
        .nhcb-tag-container .nhcb-browse-later-info-section + .nhcb-browse-later-info-section {
            margin-top: .5em;
        }

        /* Recovery 404 */
        .nhcb-404-recovery .nhcb-recovery-info {
            max-width: 75ch;
            margin: .6em auto 2em;
            padding: 0 1em;
            line-height: 1.55;
            text-align: center;
        }
        .nhcb-404-recovery .nhcb-recovery-info h2 {
            margin: 0;
            line-height: 1;
            font-size: 18px;
        }
        .nhcb-404-recovery .nhcb-404-notice {
            font-size: 16px;
            margin: 0;
        }
        .nhcb-404-recovery .nhcb-404-notice-status {
            font-weight: 700;
            color: var(--success);
        }
        .nhcb-404-recovery .nhcb-404-notice-status.nhcb-404-notice-unsafe {
            color: var(--error);
        }
        

        /* Settings */
        .nhcb-settings-page .container {
            padding: 30px;
            padding-top: 10px;
            max-width: 1100px;
            min-width: 600px;
        }
        .nhcb-settings-page .container > div {
            max-width: 600px;
            margin-left: auto;
            margin-right: auto;
        }
    `,
    //#endregion

    //#region Favorites Customization Styles
    `
        /* Customize Panel */
        #nhcb-customize-favorite-panel {
            width: 800px;
            min-width: 550px;
            max-width: 100%;
        }

        /* Favorite At */
        .nhcb-favorited-at-display {
            display: block;
            width: 100%;
            padding: 8px 12px;
            border-radius: 4px;
            height: 40px;
            line-height: 24px;
            background: hsl(0, 0%, 20%);
            margin: 3px;
            margin-left: 0px;
            text-align: start;
        }
        
        /* Custom Title */
        .nhcb-favorite-custom-title-panel .nhcb-input {
            margin: 8px 0px;
        }
        .nhcb-custom-title-display {
            text-align: center;
            background: hsl(0, 0%, 20%);
            color: var(--text-primary);
            border-radius: 4px;
            padding: 5.72px 12px;
            margin: 8px 0px;
            font-size: 20px;
            font-weight: 700;
        }
        .nhcb-custom-title-display .nhcb-empty, 
        .nhcb-custom-title-display .nhcb-before, 
        .nhcb-custom-title-display .nhcb-after {
            color: var(--text-secondary);
        }

        /* Notes */
        .nhcb-favorite-notes-text {
            display: block;
            width: 100%;
            border: var(--input-border);
            border-radius: 4px;

            height: calc(3lh + 16px);
            line-height: 20px;
            padding: 8px 12px;
            margin: 8px 0px;

            box-shadow: none;
            outline: none;
        }
        .nhcb-favorite-notes-text[readonly] {
            background: hsl(0, 0%, 20%);
            color: inherit;
            cursor: text;
            caret-color: transparent;
        }
        .nhcb-favorite-notes-text[readonly]::placeholder {
            text-align: center;
        }
        .nhcb-favorite-notes-text[readonly]:placeholder-shown {
            height: calc(1lh + 16px);
            cursor: default;
        }

        /* Rating */
        .nhcb-rating-field .nhcb-rating-decrement {
            margin-left: 2px;
            margin-right: 5px;
        }
        .nhcb-rating-field .nhcb-rating-increment {
            margin-right: 2px;
            margin-left: 5px;
        }
        .nhcb-rating-field .nhcb-rating-decrement,
        .nhcb-rating-field .nhcb-rating-increment {
            font-size: 1.5rem;
            padding: 3px;
            color: var(--text-primary);
            background: transparent;
            border: none;
        }
        .nhcb-rating-field .nhcb-rating-decrement:hover,
        .nhcb-rating-field .nhcb-rating-increment:hover {
            color: var(--text-bright);
        }

        .nhcb-rating-hearts-container {
            display: flex;
            margin: 0 auto;
            font-size: 1.65rem;
        }
        .nhcb-rating-none {
            color: var(--text-muted);
            font-size: 1.2rem;
        }
        .nhcb-rating-heart {
            display: inline-block;
            position: relative;
            line-height: 1em;
        }
        .nhcb-rating-heart i {
            margin: 0;
        }
        .nhcb-rating-display {
            display: inline-flex;
            gap: .2em;
            color: var(--accent);
            flex-wrap: nowrap;
            dominant-baseline: middle;
            margin: 2px;
        }
        .nhcb-rating-heart i:first-child {
            padding-left: 1px; /* padding needed for cliping issues with pixel rounding */
            width: calc(.5em + 1px);
            overflow: clip;
        }
        .nhcb-rating-heart i:last-child {
            direction: rtl;
            padding-right: 1px; /* padding needed for cliping issues with pixel rounding */
            width: calc(.5em + 1px);
            overflow: clip;
        }
        .nhcb-rating-heart.nhcb-heart-none i {
            visibility: hidden;
        }
        .nhcb-rating-heart.nhcb-heart-half i:last-child {
            visibility: hidden;
        }

        /* Alt Cover */
        .nhcb-alt-cover-panel .nhcb-form {
            width: 100%;
        }

        /* Alt Source */
        .nhcb-alt-source-panel .nhcb-form {
            width: 100%;
        }
        .nhcb-alt-source-panel .container {
            border-radius: 4px;
        }
        .nhcb-alt-source-panel .container .gallery {
            width: 30%;
            max-width: 244px;
        }
    `,
    //#endregion

    //#region Misc Modal Styles
    `
        .nhcb-read-later-modal {
            width: 435px;
        }
        .nhcb-browse-later-modal {
            width: 435px;
        }
    `,
    //#endregion

    //#region Misc Styles
    `
        /* Remove ad links */
        nav ul.left li:has(> a[href^="//tsyndicate.com"]) {
            display: none;
        }

        /* Fix nav dropdown displaying behind galleries */
        nav ul.dropdown-menu {
            z-index: 15 !important;
        }

        /* Jump to Page */
        .nhcb-jump-page {
            cursor: pointer;
        }

        /* Remove Border On Buttons With Tooltip*/
        .btn.tooltip {
            ${settingsStore.removeBorderOnButtonsWithTooltip.value ? 'border-bottom: none;' : '' }
        } 
        
        /* Add Nav Bar to Error Pages */
        #app .error-page.nhcb-error-page-nav-bar {
            min-height: calc(100vh - 50px);
        }
    `,
    //#endregion
    ];
    GM_addStyle(styles.join('\n'));
    }
    //#endregion

    //#region -- MAIN -------------------------------------
    await onDocumentImmediate();
    if (document.readyState === 'complete') {
        onDocumentLoad();
    } else {
        window.addEventListener('load', () => {
            setTimeout(onDocumentLoad, 0);
        });
    }
    //#endregion
})();