☰

Pornhub Pro-ish

Download videos, filter/sort playlists and categories, cross-tab queue, autoscroll through playlists, hide shorts/vr/paid content, and much more! Auto mute volume, hide your cursor over videos, auto age verification, and when visiting pornhub in other languages change it to English automatically. Actively maintained and used by me so updated regularly. Feel free to request features!

Dovrai installare un'estensione come Tampermonkey, Greasemonkey o Violentmonkey per installare questo script.

Dovrai installare un'estensione come Tampermonkey o Violentmonkey per installare questo script.

Dovrai installare un'estensione come Tampermonkey o Violentmonkey per installare questo script.

Dovrai installare un'estensione come Tampermonkey o Userscripts per installare questo script.

Dovrai installare un'estensione come ad esempio Tampermonkey per installare questo script.

Dovrai installare un gestore di script utente per installare questo script.

(Ho già un gestore di script utente, lasciamelo installare!)

Dovrai installare un'estensione come ad esempio Stylus per installare questo stile.

Dovrai installare un'estensione come ad esempio Stylus per installare questo stile.

Dovrai installare un'estensione come ad esempio Stylus per installare questo stile.

Dovrai installare un'estensione per la gestione degli stili utente per installare questo stile.

Dovrai installare un'estensione per la gestione degli stili utente per installare questo stile.

Dovrai installare un'estensione per la gestione degli stili utente per installare questo stile.

(Ho già un gestore di stile utente, lasciamelo installare!)

// ==UserScript==
// @name         Pornhub Pro-ish
// @namespace    https://www.reddit.com/user/Alpacinator
// @version      9.1.2
// @match        *://*.pornhub.com/*
// @grant        none
// @run-at       document-start
// @license      MIT
// @description  Download videos, filter/sort playlists and categories, cross-tab queue, autoscroll through playlists, hide shorts/vr/paid content, and much more! Auto mute volume, hide your cursor over videos, auto age verification, and when visiting pornhub in other languages change it to English automatically. Actively maintained and used by me so updated regularly. Feel free to request features!
// ==/UserScript==

(() => {
	'use strict';

	// Same-origin frames (the site's own embed player, for one) load this script
	// too. A second copy there would add a second menu and a second participant
	// in the cross-tab queue, so frames are skipped.
	const inFrame = (() => {
		// A cross-origin parent can make window.top throw rather than compare false.
		try {
			return window.top !== window.self;
		} catch {
			return true;
		}
	})();
	if (inFrame) return;

	// Mobile userscript managers can inject twice, which would give two
	// instances racing over the same storage and DOM. Pornhub Pro-ish uses the
	// same flag, so with both installed only the first to load runs.
	if (window.__phproLoaded) return;
	window.__phproLoaded = true;

	// =====================================================================
	// 0. Config
	// =====================================================================

	const CONFIG = Object.freeze({
		SCRIPT_NAME: 'PH-PRO',
		// Per-pass logging is noisy on infinite-scroll pages; flip for debugging.
		DEBUG_LOGGING: false,

		TIMING: {
			OBSERVER_THROTTLE_MS: 1000,
			FEATURE_INIT_DELAY_MS: 100,
			LANGUAGE_CHECK_DELAY_MS: 1000,
			CURSOR_HIDE_DELAY_S: 3,
			AUTOSCROLL_MIN_DELAY_MS: 800,
			AUTOSCROLL_MAX_DELAY_MS: 2500,
			// Lets the DOM settle after autoscroll stops before jumping to the top.
			AUTOSCROLL_STOP_SCROLL_DELAY_MS: 350,
			BUTTON_FLASH_MS: 100,
			// A 'volumechange' this soon after a tap or keypress counts as the
			// user's own change and is worth persisting.
			VOLUME_GESTURE_WINDOW_MS: 1500,
			VOLUME_SAVE_DEBOUNCE_MS: 300,
			// Same idea for playback: a 'play' this soon after a gesture is the
			// user pressing play, not the site autoplaying.
			AUTOPLAY_GESTURE_WINDOW_MS: 1000,
			PANEL_SLIDE_MS: 280,
			PANEL_HIDE_GRACE_MS: 20,
			RESIZE_DEBOUNCE_MS: 300,
			// Lets a burst of player DOM changes finish before buttons are checked.
			PLAYER_BUTTONS_SETTLE_MS: 50,
			PLAYER_TOOLTIP_RESTORE_MS: 60,
			TOAST_SUCCESS_MS: 1800,
			TOAST_FAILURE_MS: 3000,
			TOAST_FADE_MS: 400,
			// Revoking a blob URL straight after click() can cancel the download
			// in some browsers, so it is kept alive for a while.
			OBJECT_URL_REVOKE_MS: 60_000,
			MENU_BUTTON_FADE_DELAY_MS: 5000,
		},

		LIMITS: {
			FILTER_WORDS_MAX_LENGTH: 255,
			PLAYLIST_PAGE_SIZE: 32,
			AUTOSCROLL_MAX_CONSECUTIVE_EMPTY: 3,
			// Browsers silently drop a cookie pair over ~4096 bytes.
			COOKIE_MAX_BYTES: 4000,
			COOKIE_MAX_AGE_S: 10 * 365 * 24 * 60 * 60,
			LANGUAGE_COOKIE_MAX_AGE_S: 365 * 24 * 60 * 60,
			FILENAME_MAX_LENGTH: 200,
		},

		UI: {
			MENU_BUTTON_EDGE_MARGIN_PX: 12,
			MENU_BUTTON_SNAP_MARGIN_PX: 90,
			// Touch needs a larger threshold so finger wobble on a tap is not a drag.
			DRAG_THRESHOLD_MOUSE_PX: 5,
			DRAG_THRESHOLD_TOUCH_PX: 15,
			SWIPE_EDGE_PX: 30,
			// How far a finger may drift and still count as a tap.
			TAP_SLOP_PX: 10,
			SWIPE_MIN_PX: 60,
			DURATION_STOPS_MIN: [0, 10, 20, 30, 40],
			// How far up from the fullscreen button to look for the whole control bar,
			// and how many of the player's buttons make a control bar.
			CONTROL_BAR_SEARCH: { MIN_BUTTONS: 3, MAX_DEPTH: 4 },
		},

		STORAGE: {
			SYNC_PING_KEY: 'phpro_sync_ping',
			AGE_GATE_RELOADED_KEY: 'ageGateReloaded',
			PLAYER_PREFS_KEY: 'mgp_player',
		},

		COOKIES: {
			AGE_GATE: { name: 'accessAgeDisclaimerPH', value: '2' },
			CONSENT: { name: 'cookieConsent', value: '3', partialValue: '1' },
			LANGUAGE: { name: 'lang', value: 'en' },
		},

		PATHS: {
			LISTING: /^\/video(\/|$)/i,
			WATCH_PAGE: /^\/view_video\.php/i,
			PLAYLIST_ID_FROM_PATH: /\/(\d+)$/,
			PLAYLIST_CHUNK: '/playlist/viewChunked',
			TITLE_SUFFIX: /\s*-\s*Pornhub\.com.*/i,
			WATCH: '/view_video.php',
			EMBED_PREFIX: '/embed/',
		},

		SELECTORS: {
			VIDEO_LISTS: 'ul.videos, ul.videoList',
			AUTOSCROLL_LIST: 'ul.videos.row-5-thumbs',
			DURATION: '.duration',
			VIEWS: '.views var',
			AWARD: '[class*="award-icon"]',
			WATCHED: '.watchedVideoText, .watchedVideo',
			PAID: 'span.price, .premiumicon, img.privateOverlay',
			PAID_LINK_HREF: 'javascript:void(0)',
			VR: 'span.vr-thumbnail',
			// The badge the site puts next to the uploader of AI-generated content.
			AI_GENERATED: '.ph-icon-ai',
			SHORTS_SECTION: '#shortiesListSection',
			// Not the generic 'video' tag: hover previews on listings are <video> too.
			PLAYER_VIDEO: '.mgp_videoElement',
			PLAYER_PLACEHOLDER_VIDEO: '.player-html5',
			PLAYER_PLAYING: '.mgp_playingState',
			PLAYER_BUTTON_CLASS: 'mgp_button',
			PLAYER_ICON_CLASS: 'mgp_icon',
			// The player container also gets mgp_fullscreen while it is fullscreen, so the button's own class is needed too.
			FULLSCREEN_BUTTON: '.mgp_button.mgp_fullscreen',
			// The row of pills under the player on watch pages (Add to, Share, Report).
			UNDERPLAYER_CELL: '.tab-menu-wrapper-cell',
			UNDERPLAYER_SHARE: '#jsShare',
			UNDERPLAYER_REPORT: '#video_flag',
			// The phone row under the player: plain pill buttons, Share among them.
			UNDERPLAYER_SHARE_MOBILE: '#shareModal',
			// Carries the video's listed length in seconds, ads not included.
			WATCH_DURATION: '#js-shareData[data-duration]',
			// Tried in order. The control bar's play/pause toggle, not the big play overlay.
			// The player names its tooltips through data-text, which is the most stable hook.
			PLAYER_PLAY_BUTTON: [
				'.mgp_play',
				'.mgp_playPause',
				'.mgp_playButton',
				'[data-text="Play"]',
				'[data-text="Pause"]',
				// On phones the only play/pause button is the big one in the middle.
				'.mgp_btn-playback',
			],
			// The phone player's play button in the bottom bar, which only a tablet's wider layout shows.
			PLAYER_BOTTOM_BAR_PLAY: '.mgp_bottomBarPlay',
			// The phone player: top row, a big play button in the middle, bottom row.
			MOBILE_PLAYER: '.mgp_mobile-skin, .mgp_mobilePlayer',
			MOBILE_MIDDLE_CONTROLS: '.mgp_middle-controls',
			// The player's own next-video button, which the queue's next button replaces.
			PLAYER_NEXT_BUTTON: ['.mgp_next', '.mgp_nextVideo', '.mgp_nextBtn', '[data-text^="Next"]'],
			LANGUAGE_DROPDOWN: 'li.languageDropdown',
			CURRENT_LANGUAGE: 'span.networkTab',
			ENGLISH_OPTION: 'li[data-lang="en"] a.networkTab',
			PLAYLIST_ID: '[data-playlist-id]',
			PLAYLIST_TOKEN: '[data-token]',
			PLAYLIST_DELETE_BUTTON: 'button[onclick="deleteFromPlaylist(this);"]',
			// Editing one's own playlist: the Edit tab is marked active and its form shown.
			PLAYLIST_EDIT_TRIGGER: '#js-editPlaylistTrigger',
			PLAYLIST_EDIT_FORM: '#edit-pl-form',
			PLAYLIST_EDIT_LIST: '#videoPlaylist',
			PLAYLIST_VIDEO_ITEM: 'li[data-video-id]',
			// The site's classes for an active tab and for a hidden section.
			ACTIVE_CLASS: 'active',
			HIDDEN_CLASS: 'displayNone',
			PLAYLIST_CONTAINERS: [
				'#videoPlaylist',
				'#videoPlaylistSection',
				'#playListSection',
				'[id*="playlist"]',
				'[class*="playlist"]',
				'[data-context="playlist"]',
			],
			CLUTTER: [
				'#countryRedirectMessage',
				'#js-abContainterMain',
				'#welcome',
				'div.pornInLangWrapper',
				'#loadMoreRelatedVideosCenter',
				'[data-label="recommended_load_more"]',
				'.buttonClass.blackBtn.eudsaLink',
				'#cookieBanner',
				'.cbShort',
			],
			// Every ad slot carries the site's "Remove Ads" pill, while the slot's own
			// class names change, so slots are found by the pill.
			AD_SLOT_MARKER: '.adsRemoveButtonWrapper',
			MOBILE_CONTAINER: '#mobileContainer',
			// The phone site has no #player; its player sits in the placeholder.
			WATCH_PLAYER: '#player, #videoPlayerPlaceholder',
			// Tried in order: the first is the bare title, the second its whole heading.
			WATCH_TITLE: ['h1.title .inlineFree', 'h1.title'],
			WATCH_UPLOADER: '.video-detailed-info .usernameBadgesWrapper a, .userInfo .usernameWrap a',
			QUEUE_CARD: 'li.pcVideoListItem, li.videoBox, li[data-video-vkey]',
			CARD_LINK: 'a[href*="viewkey="]',
			CARD_TITLE: '.title a',
			CARD_UPLOADER: '.usernameWrap a, .videoUploaderBlock a',
			// The menu behind a card's three dots. The site builds it on the first
			// click, inside a <v-more-action-menu> whose id is the video's numeric id.
			ACTION_MENU: '.moreActionMenu, .kebabMenuItems',
			ACTION_MENU_HOST: 'v-more-action-menu',
			// On phones the menu is a drawer that slides up, outside any card and
			// reused for every video; it shows a preview of the video it is for.
			ACTION_MENU_DRAWER: '.moreActionKebabMenu',
			DRAWER_PREVIEW_LINK: '.kebabMenuPreview a[href*="viewkey="]',
			DRAWER_PREVIEW_TITLE: '.kebabMenuPreviewDetails .title',
			DRAWER_PREVIEW_UPLOADER: '.kebabMenuPreviewDetails .name',
			ACTION_MENU_WATCH_LATER: '.addToWatchLaterLink',
			ACTION_MENU_LINK_CLASS: 'moreActionLink',
			// Glyphs from the site's icon font, used for the script's own buttons.
			SITE_ICONS: {
				DELETE: 'ph-icon-delete-ghost',
				CLOSE: 'ph-icon-cross',
				DOWNLOAD: 'ph-icon-cloud-download',
			},
			// The player can wait for a click on its poster before it starts its <video>.
			PLAYER_BIG_PLAY: '.mgp_bigPlay',
			PLAYER_PLAY_OVERLAY: '.mgp_bigPlay, .mgp_playIcon, [class*="bigPlay"]',
		},

		QUEUE: {
			STORAGE: {
				STATE: 'phq_state_v1',
				POSITIONS: 'phq_positions',
				// sessionStorage: survives a reload of this tab and nothing else, so the
				// reloaded page knows to pick the queue back up while a new tab does not.
				RESUME_AFTER_RELOAD: 'phq_resume_after_reload',
				// sessionStorage: the video page the queue sent this tab to, so a page
				// that landed elsewhere instead can tell it was diverted.
				HEADING_TO: 'phq_heading_to',
				// sessionStorage: the queue the play pill was closed for, so it stays
				// closed until the queue changes.
				PLAY_PILL_DISMISSED: 'phq_play_pill_dismissed',
			},
			LOCKS: { PLAYBACK: 'phq-playback', STATE: 'phq-state' },
			HISTORY_MAX: 50,
			POSITIONS: { MAX_ENTRIES: 100, MIN_SECONDS: 5, END_GAP_SECONDS: 10 },
			// A run of unplayable videos this long means something is wrong with the
			// player itself, so the queue stops instead of skipping through everything.
			MAX_CONSECUTIVE_SKIPS: 3,
			// Prerolls play in the queue's <video> too. A video much shorter than the
			// listed duration is taken for an ad and never advances the queue.
			AD_SHORTER_BY: { MIN_S: 15, RATIO: 0.1 },
			MEDIA_SESSION_INTERVAL_S: { MIN: 1, MAX: 60, DEFAULT: 5 },
			MEDIA_SESSION_ALBUM: 'PH PRO Q',
			// In fullscreen on a touch screen, a swipe starting this close to the left
			// or right edge and moving at least MIN_PX inwards opens the queue panel.
			// Only touches starting in that strip are taken from the player.
			FULLSCREEN_SWIPE: { EDGE_PX: 30, MIN_PX: 60 },
			TOUCH_DRAG: { AUTOSCROLL_EDGE_PX: 48, AUTOSCROLL_STEP_PX: 8 },
			TIMING: {
				NAV_TIMEOUT_MS: 30000,
				NAV_GUARD_MS: 8000,
				WAIT_POLL_MS: 500,
				// A watch page loads a whole player, so this is far longer than YT-Q's grace.
				UNAVAILABLE_GRACE_MS: 8000,
				SKIP_UNPLAYABLE_MS: 200,
				END_THRESHOLD_S: 2,
				END_WINDOW_S: 5,
				END_POLL_LEAD_S: 28,
				END_POLL_SLEEP_ABOVE_S: 30,
				END_POLL_TICK_MS: 1000,
				SEEK_SETTLE_MS: 600,
				EARLY_PAUSE_GRACE_MS: 3000,
				POSITION_SAVE_MS: 4000,
				RESTART_SKIP_UNDER_S: 3,
				PREV_RESTART_AFTER_S: 10,
				RESTORE_TOLERANCE_S: 2,
				// How long after a video attaches the queue keeps trying to start it, and how often.
				PLAY_RETRY_WINDOW_MS: 15000,
				PLAY_RETRY_MAX: 3,
				PLAY_STATE_LOG_MS: 3000,
				STREAM_WAIT_MS: 4000,
				PLAY_RETRY_USER_QUIET_MS: 2000,
				RESTART_REASSERT_MS: 200,
				RESTART_REASSERT_TRIES: 6,
				RESUME_SEEK_SLACK_S: 1,
				MEDIA_SESSION_DELAY_MS: 1000,
				MEDIA_SESSION_THROTTLE_MS: 500,
				THUMB_HIDE_MS: 1000,
				PANEL_AUTOCLOSE_MS: 3000,
				CONFIRM_MS: 1800,
				// How long a tab that went on to the next video's page still counts as
				// playing while that page loads and picks the queue back up.
				PAGE_MOVE_GRACE_MS: 15000,
			},
			STATUS_MS: { BRIEF: 1500, SHORT: 2000, MEDIUM: 3000, NORMAL: 3500, LONGER: 5000, STICKY: Infinity },
			THUMB_BUTTON: { SIZE_PX: 34, INSET_PX: 8, MIN_PICTURE_WIDTH_PX: 40, MIN_PICTURE_HEIGHT_PX: 20, AVOID_UI_PAD_PX: 8 },
			STATUS_PILL_BOTTOM_PX: 24,
			PLAY_PILL_EDGE_PX: 20,
			PLAY_NEXT_ANIMATION: { MOVED_MS: 420, OTHERS_MS: 320, EASING: 'cubic-bezier(.2,.8,.2,1)' },
		},
	});

	// =====================================================================
	// 1. Infrastructure
	// =====================================================================

	const Log = {
		debug(message) {
			if (CONFIG.DEBUG_LOGGING) console.log(`${CONFIG.SCRIPT_NAME}:`, message);
		},
		info(message) {
			console.log(`${CONFIG.SCRIPT_NAME}:`, message);
		},
		warn(context, detail) {
			console.warn(`${CONFIG.SCRIPT_NAME} [${context}]:`, detail);
		},
		error(context, detail) {
			console.error(`${CONFIG.SCRIPT_NAME} [${context}]:`, detail);
		},
	};

	/** Delays `callback` until `waitMs` have passed without another call. */
	function debounce(callback, waitMs) {
		let timer = null;
		return (...args) => {
			clearTimeout(timer);
			timer = setTimeout(() => callback(...args), waitMs);
		};
	}

	/**
	 * Runs `callback` at most once per interval. Unlike a leading-only throttle
	 * it always schedules one trailing run, so the end of a burst is never lost.
	 */
	function throttle(callback, intervalMs) {
		let lastRunAt = 0;
		let trailingTimer = null;
		const run = () => {
			trailingTimer = null;
			lastRunAt = Date.now();
			callback();
		};
		return () => {
			const remaining = intervalMs - (Date.now() - lastRunAt);
			if (remaining <= 0) {
				clearTimeout(trailingTimer);
				run();
				return;
			}
			if (!trailingTimer) trailingTimer = setTimeout(run, remaining);
		};
	}

	/** Collapses every call made in the same task into one run on the next microtask. */
	function coalesceToMicrotask(callback) {
		let queued = false;
		return () => {
			if (queued) return;
			queued = true;
			queueMicrotask(() => {
				queued = false;
				callback();
			});
		};
	}

	function createId() {
		return crypto.randomUUID?.() ?? `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
	}

	function randomBetween(min, max) {
		return min + Math.floor(Math.random() * (max - min));
	}

	function clamp(value, min, max) {
		return Math.max(min, Math.min(value, max));
	}

	const Dom = {
		/** Creates an element in one call; `attrs` are set with setAttribute. */
		create(tag, { id, className, text, attrs = {}, children = [] } = {}) {
			const element = document.createElement(tag);
			if (id) element.id = id;
			if (className) element.className = className;
			if (text !== undefined) element.textContent = text;
			for (const [name, value] of Object.entries(attrs)) element.setAttribute(name, value);
			element.append(...children);
			return element;
		},

		query(selector, root = document) {
			return root.querySelector(selector);
		},

		queryAll(selector, root = document) {
			return Array.from(root.querySelectorAll(selector));
		},

		/** The first match of the first selector that matches anything, so fallbacks are tried in order. */
		queryFirst(selectors, root = document) {
			for (const selector of selectors) {
				const match = root.querySelector(selector);
				if (match) return match;
			}
			return null;
		},

		/** Builds an element from this script's own static SVG markup. Never pass it text from the page. */
		/**
		 * A glyph from the site's icon font in a `sizePx` square, centred in it.
		 * Left to its line box, a font glyph sits on the text baseline and ends up
		 * lower than drawn icons beside it.
		 */
		iconFont(className, sizePx) {
			const glyph = Dom.create('span', { className, attrs: { 'aria-hidden': 'true' } });
			Object.assign(glyph.style, {
				display: 'inline-flex',
				alignItems: 'center',
				justifyContent: 'center',
				width: `${sizePx}px`,
				height: `${sizePx}px`,
				fontSize: `${sizePx}px`,
				lineHeight: '1',
				verticalAlign: 'middle',
				flexShrink: '0',
			});
			return glyph;
		},

		svg(markup) {
			const template = document.createElement('template');
			template.innerHTML = markup.trim();
			return template.content.firstElementChild;
		},

		/**
		 * Taps `element` the way a finger does, for players that only listen to touch
		 * input: pointer and touch events at the element's centre, then the mouse
		 * events and click a browser adds unless the touch was handled.
		 */
		tap(element) {
			const win = element.ownerDocument.defaultView;
			const box = element.getBoundingClientRect();
			const point = { clientX: box.left + box.width / 2, clientY: box.top + box.height / 2 };
			const fire = (type, Constructor, extra = {}) => {
				const options = { bubbles: true, cancelable: true, composed: true, view: win, ...point, ...extra };
				const event = typeof Constructor === 'function' ? new Constructor(type, options) : new win.Event(type, options);
				// A browser without the constructor still gets the touch lists the player reads.
				if (extra.touches && !event.touches?.length) {
					Object.defineProperties(event, {
						touches: { value: extra.touches },
						changedTouches: { value: extra.changedTouches },
					});
				}
				element.dispatchEvent(event);
				return event;
			};
			const pointer = { pointerId: 1, pointerType: 'touch', isPrimary: true };
			const touch =
				typeof win.Touch === 'function' ? new win.Touch({ identifier: 1, target: element, ...point }) : { identifier: 1, target: element, ...point };
			fire('pointerdown', win.PointerEvent, pointer);
			fire('touchstart', win.TouchEvent, { touches: [touch], changedTouches: [touch] });
			fire('pointerup', win.PointerEvent, pointer);
			const touchEnd = fire('touchend', win.TouchEvent, { touches: [], changedTouches: [touch] });
			if (touchEnd.defaultPrevented) return;
			fire('mousedown', win.MouseEvent);
			fire('mouseup', win.MouseEvent);
			fire('click', win.MouseEvent);
		},

		/**
		 * Adds a stylesheet once per id. Falls back to <html> because <head> may not
		 * exist yet at document-start, and some mobile browsers run the script before
		 * <html> exists too, so then the sheet goes in as soon as it does.
		 */
		addStyle(css, id) {
			const existing = document.getElementById(id);
			if (existing) return existing;
			const style = Dom.create('style', { id, text: css });
			const parent = document.head ?? document.documentElement;
			if (parent) {
				parent.append(style);
				return style;
			}
			const observer = new MutationObserver(() => {
				if (!document.documentElement) return;
				observer.disconnect();
				(document.head ?? document.documentElement).append(style);
			});
			observer.observe(document, { childList: true });
			return style;
		},

		/** Click plus Enter/Space, for elements that act as buttons without being <button>. */
		onActivate(element, handler) {
			element.addEventListener('click', handler);
			element.addEventListener('keydown', event => {
				if (event.key !== 'Enter' && event.key !== ' ') return;
				event.preventDefault();
				handler(event);
			});
		},

		FULLSCREEN_EVENTS: ['fullscreenchange', 'webkitfullscreenchange'],

		fullscreenElement(doc = document) {
			return doc.fullscreenElement ?? doc.webkitFullscreenElement ?? null;
		},

		/**
		 * Starts a self-contained function in the page's own context with JSON
		 * arguments, without waiting for it. Unlike evaluateInPage it always
		 * injects, since its point is to run as the page rather than as the script.
		 */
		runInPage(pageFunction, ...args) {
			const script = document.createElement('script');
			script.textContent = `(${pageFunction.toString()})(...${JSON.stringify(args)});`;
			document.documentElement.append(script);
			script.remove();
		},

		/**
		 * Runs a self-contained function against the page's own `window` and
		 * returns its JSON-serialisable result.
		 *
		 * With @grant none most managers already run us in the page context, so
		 * a direct call is tried first. Sandboxed managers need the function
		 * injected as an inline <script>; inline scripts run synchronously on
		 * insertion, so the result can be read straight back from an attribute.
		 */
		evaluateInPage(pageFunction) {
			try {
				const direct = pageFunction();
				if (direct !== null && direct !== undefined) return direct;
			} catch (error) {
				Log.debug(`evaluateInPage direct call failed: ${error}`);
			}

			const resultAttribute = 'data-phpro-page-result';
			const root = document.documentElement;
			const script = document.createElement('script');
			script.textContent = `(() => {
				let serialised = 'null';
				try { serialised = JSON.stringify((${pageFunction.toString()})() ?? null); } catch (error) {}
				document.documentElement.setAttribute('${resultAttribute}', serialised);
			})();`;
			root.append(script);
			script.remove();

			const raw = root.getAttribute(resultAttribute);
			root.removeAttribute(resultAttribute);
			try {
				return raw === null ? null : JSON.parse(raw);
			} catch {
				return null;
			}
		},
	};

	/** Wraps Web Storage so private modes and quota errors degrade to no-ops. */
	function createSafeStorage(getStore) {
		return {
			get(key) {
				try {
					return getStore().getItem(key);
				} catch {
					return null;
				}
			},
			set(key, value) {
				try {
					getStore().setItem(key, value);
				} catch (error) {
					Log.debug(`storage write failed for ${key}: ${error}`);
				}
			},
			remove(key) {
				try {
					getStore().removeItem(key);
				} catch (error) {
					Log.debug(`storage remove failed for ${key}: ${error}`);
				}
			},
		};
	}

	const SafeLocalStorage = createSafeStorage(() => window.localStorage);
	const SafeSessionStorage = createSafeStorage(() => window.sessionStorage);

	const Cookies = {
		// Leading dot so cookies are shared across subdomains. Assumes a
		// single-label TLD; a domain like .co.uk would need a public suffix list.
		rootDomain: `.${window.location.hostname.split('.').slice(-2).join('.')}`,

		/** Returns the decoded value of the first cookie called `name`, or null. */
		read(name) {
			for (const pair of document.cookie.split('; ')) {
				const separator = pair.indexOf('=');
				if (separator < 0 || pair.slice(0, separator).trim() !== name) continue;
				const raw = pair.slice(separator + 1);
				try {
					return decodeURIComponent(raw);
				} catch {
					return raw;
				}
			}
			return null;
		},

		/** Writes one cookie. `domain: null` makes it host-only. Returns false when it would be too large. */
		write(name, value, { domain = Cookies.rootDomain, maxAgeSeconds = CONFIG.LIMITS.COOKIE_MAX_AGE_S, secure = false } = {}) {
			const encoded = encodeURIComponent(String(value));
			if (name.length + encoded.length > CONFIG.LIMITS.COOKIE_MAX_BYTES) return false;
			const parts = [`${name}=${encoded}`, 'path=/', `max-age=${maxAgeSeconds}`, 'SameSite=Lax'];
			if (domain) parts.push(`domain=${domain}`);
			if (secure) parts.push('Secure');
			document.cookie = parts.join('; ');
			return true;
		},

		/**
		 * Writes both a root-domain and a host-only copy. The site reads either
		 * depending on the page, so setting just one leaves gaps.
		 */
		writeEverywhere(name, value, options = {}) {
			Cookies.write(name, value, { ...options, domain: Cookies.rootDomain });
			Cookies.write(name, value, { ...options, domain: null });
		},

		removeEverywhere(name) {
			for (const domain of [Cookies.rootDomain, null]) {
				Cookies.write(name, '', { domain, maxAgeSeconds: 0 });
			}
		},
	};

	/**
	 * Key/value storage shared across subdomains.
	 *
	 * The root-domain cookie is the cross-subdomain channel; the localStorage
	 * mirror is the durable copy, because Safari expires script-written cookies
	 * after 7 days regardless of max-age. Every write also touches a ping key so
	 * other tabs on this origin get a 'storage' event (cookie writes fire none).
	 */
	const CrossDomainStorage = {
		SYNC_PING_KEY: CONFIG.STORAGE.SYNC_PING_KEY,

		getItem(key) {
			const cookieValue = Cookies.read(key);
			if (cookieValue !== null) {
				// The cookie may have been written by another subdomain or an older
				// version of the script, so the mirror is brought up to date.
				if (SafeLocalStorage.get(key) !== cookieValue) SafeLocalStorage.set(key, cookieValue);
				return cookieValue;
			}
			// Cookie expired: fall back to the mirror and restore the cookie so
			// other subdomains can see the value again.
			const mirrored = SafeLocalStorage.get(key);
			if (mirrored !== null) Cookies.write(key, mirrored, { secure: true });
			return mirrored;
		},

		setItem(key, value) {
			const text = String(value);
			Cookies.write(key, text, { secure: true });
			SafeLocalStorage.set(key, text);
			SafeLocalStorage.set(CrossDomainStorage.SYNC_PING_KEY, `${key}:${Date.now()}`);
		},
	};

	/** Minimal pub/sub. `on` returns an unsubscribe function. */
	class EventBus {
		constructor() {
			this._handlers = new Map();
		}

		on(event, handler) {
			if (!this._handlers.has(event)) this._handlers.set(event, new Set());
			this._handlers.get(event).add(handler);
			return () => this._handlers.get(event)?.delete(handler);
		}

		emit(event, payload) {
			for (const handler of [...(this._handlers.get(event) ?? [])]) {
				try {
					handler(payload);
				} catch (error) {
					Log.error(`EventBus "${event}"`, error);
				}
			}
		}
	}

	/** Collects teardown functions so UI that is rebuilt can drop its subscriptions in one go. */
	class DisposableScope {
		constructor() {
			this._disposers = [];
		}

		add(disposer) {
			this._disposers.push(disposer);
			return disposer;
		}

		dispose() {
			for (const disposer of this._disposers.splice(0)) {
				try {
					disposer();
				} catch (error) {
					Log.warn('DisposableScope.dispose', error);
				}
			}
		}
	}

	// =====================================================================
	// 2. Settings
	// =====================================================================

	/** Splits a comma-separated word list into trimmed, lowercased, unique words. */
	function parseWordList(text) {
		if (typeof text !== 'string') return [];
		const words = text
			.split(',')
			.map(word => word.trim().toLowerCase())
			.filter(word => word.length > 0);
		return [...new Set(words)];
	}

	const EMPTY_LIST = Object.freeze([]);

	// Modifiers plus a KeyboardEvent.code, such as 'Alt+KeyQ'. At least one modifier is required.
	const SHORTCUT_PATTERN = /^((Ctrl|Alt|Shift|Meta)\+)+[A-Za-z0-9]+$/;

	// A codec turns a stored string into a value (`decode` returns undefined for
	// anything invalid, which means "use the default"), turns a value back into
	// a string, and says which values `set` may accept.
	const Codecs = {
		boolean: {
			decode: raw => (raw === 'true' ? true : raw === 'false' ? false : undefined),
			encode: value => String(value),
			accepts: value => typeof value === 'boolean',
		},
		wordList: {
			decode: raw => parseWordList(raw),
			encode: words => words.join(', '),
			accepts: value => Array.isArray(value) && value.every(word => typeof word === 'string'),
		},
		idList: {
			decode: raw => raw.split(',').map(id => id.trim()).filter(Boolean),
			encode: ids => ids.join(','),
			accepts: value => Array.isArray(value) && value.every(id => typeof id === 'string'),
		},
		optionalMinutes: {
			decode: raw => {
				const minutes = parseInt(raw.trim(), 10);
				return Number.isFinite(minutes) && minutes >= 0 ? minutes : undefined;
			},
			encode: minutes => (minutes === null ? '' : String(minutes)),
			accepts: value => value === null || (Number.isInteger(value) && value >= 0),
		},
		unitInterval: {
			decode: raw => {
				const number = parseFloat(raw);
				return Number.isFinite(number) && number >= 0 && number <= 1 ? number : undefined;
			},
			encode: value => String(value),
			accepts: value => typeof value === 'number' && value >= 0 && value <= 1,
		},
		json: {
			decode: raw => {
				try {
					const parsed = JSON.parse(raw);
					return parsed === null || typeof parsed === 'object' ? parsed : undefined;
				} catch {
					return undefined;
				}
			},
			encode: value => JSON.stringify(value),
			accepts: value => value === null || (typeof value === 'object' && !Array.isArray(value)),
		},
		shortcut: {
			decode: raw => (SHORTCUT_PATTERN.test(raw) ? raw : undefined),
			encode: value => String(value),
			accepts: value => typeof value === 'string' && SHORTCUT_PATTERN.test(value),
		},
		integerBetween(min, max) {
			const accepts = value => Number.isInteger(value) && value >= min && value <= max;
			return {
				decode: raw => {
					const number = parseInt(raw, 10);
					return accepts(number) ? number : undefined;
				},
				encode: value => String(value),
				accepts,
			};
		},
		enumOf(allowed, legacyAliases = {}) {
			return {
				decode: raw => {
					const value = legacyAliases[raw] ?? raw;
					return allowed.includes(value) ? value : undefined;
				},
				encode: value => String(value),
				accepts: value => allowed.includes(value),
			};
		},
	};

	function booleanSetting(storageKey, defaultValue) {
		return { storageKey, codec: Codecs.boolean, default: defaultValue };
	}

	const SORT_MODES = Object.freeze(['none', 'duration', 'award', 'views']);
	const THUMB_BUTTON_SIDES = Object.freeze(['left', 'right']);
	const SHORTCUT_SETTINGS = Object.freeze(['queueShortcutAdd', 'queueShortcutNext', 'queueShortcutPrev']);

	// What the quick menu shows until the user picks otherwise: the everyday
	// actions and filters. Ids are the quick menu's item ids (storage keys for
	// switches), as persisted in quickMenuItems.
	const DEFAULT_QUICK_MENU_ITEMS = Object.freeze([
		'dropdown_sortMode',
		'action_sortDuration',
		'action_sortViews',
		'action_sortAward',
		'action_autoscroll',
		'action_scrollTop',
		'hideWatchedState',
		'hidePaidContentState',
		'hideVRState',
		'hideAIState',
		'phq_enabled',
	]);

	// Every persisted value, with its default, in one place. Storage keys are
	// the historical ones so existing users keep their settings.
	const SETTINGS_SCHEMA = {
		autoConfirmAge: booleanSetting('autoConfirmAgeState', true),
		redirectToEnglish: booleanSetting('redirectToEnglishState', true),
		// The stored value has always meant "transparent", despite the key name.
		transparency: booleanSetting('opaqueMenuButtonState', false),
		menuOnRight: booleanSetting('menuOnRightState', false),
		swipeToOpen: booleanSetting('swipeToOpenState', false),
		sortWithinPlaylists: booleanSetting('sortWithinPlaylistsState', false),
		muteByDefault: booleanSetting('muteState', false),
		blockAutoplay: booleanSetting('blockAutoplayState', false),
		syncVolume: booleanSetting('syncVolumeState', true),
		hideCursor: booleanSetting('cursorHideState', false),
		downloadButton: booleanSetting('downloadButtonState', true),
		hideWatched: booleanSetting('hideWatchedState', false),
		hidePaid: booleanSetting('hidePaidContentState', true),
		hideVR: booleanSetting('hideVRState', true),
		hideAI: booleanSetting('hideAIState', true),
		playlistListView: booleanSetting('phpro_playlistListView', false),
		hideShorts: booleanSetting('hideShortsState', true),
		enforceSearchDuration: booleanSetting('enforceSearchDurationState', false),
		hideDurationOutOfRange: booleanSetting('hideDurationOutOfRangeState', false),
		// 'trophy' was renamed to 'award' in an earlier version.
		sortMode: { storageKey: 'sortModeState', codec: Codecs.enumOf(SORT_MODES, { trophy: 'award' }), default: 'none' },
		hideWords: { storageKey: 'savedFilterWords', codec: Codecs.wordList, default: EMPTY_LIST },
		showWords: { storageKey: 'savedShowWords', codec: Codecs.wordList, default: EMPTY_LIST },
		minDuration: { storageKey: 'savedMinDuration', codec: Codecs.optionalMinutes, default: null },
		maxDuration: { storageKey: 'savedMaxDuration', codec: Codecs.optionalMinutes, default: null },
		quickMenuItems: { storageKey: 'phpro_quickMenuItems', codec: Codecs.idList, default: DEFAULT_QUICK_MENU_ITEMS },
		menuButtonPosition: { storageKey: 'phpro_menuButtonPos', codec: Codecs.json, default: null },
		savedVolume: { storageKey: 'savedVolume', codec: Codecs.unitInterval, default: null },
		savedMuted: { storageKey: 'savedMuted', codec: Codecs.boolean, default: null },

		queueEnabled: booleanSetting('phq_enabled', true),
		queueThumbSide: { storageKey: 'phq_thumb_side', codec: Codecs.enumOf(THUMB_BUTTON_SIDES), default: 'left' },
		queueRestartFromBeginning: booleanSetting('phq_restart_from_beginning', false),
		queueMediaSessionRefresh: booleanSetting('phq_media_session_refresh', true),
		queueMediaSessionInterval: {
			storageKey: 'phq_media_session_interval',
			codec: Codecs.integerBetween(CONFIG.QUEUE.MEDIA_SESSION_INTERVAL_S.MIN, CONFIG.QUEUE.MEDIA_SESSION_INTERVAL_S.MAX),
			default: CONFIG.QUEUE.MEDIA_SESSION_INTERVAL_S.DEFAULT,
		},
		queueShortcuts: booleanSetting('phq_shortcuts', false),
		queueShortcutAdd: { storageKey: 'phq_key_add', codec: Codecs.shortcut, default: 'Alt+KeyQ' },
		queueShortcutNext: { storageKey: 'phq_key_next', codec: Codecs.shortcut, default: 'Alt+KeyN' },
		queueShortcutPrev: { storageKey: 'phq_key_prev', codec: Codecs.shortcut, default: 'Alt+KeyP' },
	};

	const ChangeSource = Object.freeze({
		// Changed in this tab (a click, a keypress, a player volume change).
		USER: 'user',
		// Picked up from another tab or subdomain by refresh().
		SYNC: 'sync',
	});

	/**
	 * The single store for everything the script persists. Values are cached in
	 * memory, validated by their codec, and every effective change is emitted
	 * to `onChange` subscribers together with where it came from.
	 */
	class Settings {
		constructor(schema, storage) {
			this._schema = new Map(Object.entries(schema));
			this._storage = storage;
			this._cache = new Map();
			this._bus = new EventBus();
		}

		get(name) {
			if (!this._cache.has(name)) this._cache.set(name, this._load(name));
			return this._cache.get(name).value;
		}

		/** Validates, persists and caches a value. Returns false when the value was rejected. */
		set(name, value, source = ChangeSource.USER) {
			const { storageKey, codec } = this._spec(name);
			if (!codec.accepts(value)) {
				Log.warn(`Settings.set("${name}")`, `rejected invalid value ${JSON.stringify(value)}`);
				return false;
			}
			const raw = codec.encode(value);
			// Compared against storage rather than the cache, because the cache can
			// be stale when another tab wrote since our last refresh().
			if (this._storage.getItem(storageKey) !== raw) this._storage.setItem(storageKey, raw);

			const previous = this.get(name);
			const entry = { raw, value: this._decode(name, raw) };
			this._cache.set(name, entry);
			if (codec.encode(previous) !== raw) this._emit(name, entry.value, previous, source);
			return true;
		}

		toggle(name, source = ChangeSource.USER) {
			return this.set(name, !this.get(name), source);
		}

		/** Subscribes to effective changes of one setting. Returns an unsubscribe function. */
		onChange(name, handler) {
			this._spec(name);
			return this._bus.on(name, handler);
		}

		/** Re-reads every cached setting from storage and emits changes made by other tabs. */
		refresh() {
			for (const [name, cached] of this._cache) {
				const fresh = this._load(name);
				if (fresh.raw === cached.raw) continue;
				this._cache.set(name, fresh);
				const { codec } = this._spec(name);
				if (codec.encode(fresh.value) !== codec.encode(cached.value)) {
					this._emit(name, fresh.value, cached.value, ChangeSource.SYNC);
				}
			}
		}

		_spec(name) {
			const spec = this._schema.get(name);
			if (!spec) throw new Error(`Unknown setting "${name}"`);
			return spec;
		}

		_load(name) {
			const raw = this._storage.getItem(this._spec(name).storageKey);
			return { raw, value: raw === null ? this._spec(name).default : this._decode(name, raw) };
		}

		_decode(name, raw) {
			const spec = this._spec(name);
			const decoded = spec.codec.decode(raw);
			return decoded === undefined ? spec.default : decoded;
		}

		_emit(name, value, previous, source) {
			Log.debug(`setting ${name} = ${JSON.stringify(value)} (${source})`);
			this._bus.emit(name, { value, previous, source });
		}
	}

	// =====================================================================
	// 3. Site adapter: the only layer that knows the site's markup and URLs
	// =====================================================================

	const SELECTORS = CONFIG.SELECTORS;

	// Marks buttons this script adds to the player's control bar.
	const PLAYER_BUTTON_ATTRIBUTE = 'data-phpro-player-button';
	// The phone player sets this class on itself while its controls show.
	const MOBILE_CONTROLS_SHOWN_CLASS = 'mgp_showControls';
	const MOBILE_CONTROLS_FADE_MS = 200;
	const PLAYER_BUTTON_STYLE_ID = 'phpro-player-button-style';
	// Marks the player's own buttons that one of ours stands in for, which hides them.
	const REPLACED_PLAYER_BUTTON_ATTRIBUTE = 'data-phpro-replaced';
	const REPLACED_PLAYER_BUTTON_STYLE_ID = 'phpro-replaced-buttons-style';

	const Site = {
		isListingPage() {
			return CONFIG.PATHS.LISTING.test(window.location.pathname);
		},

		isWatchPage() {
			return CONFIG.PATHS.WATCH_PAGE.test(window.location.pathname);
		},

		/** "HH:MM:SS" or "MM:SS" to seconds; unparsable parts are skipped. */
		parseDuration(text) {
			if (typeof text !== 'string') return 0;
			return text
				.trim()
				.split(':')
				.map(Number)
				.reduce((total, part) => (Number.isNaN(part) ? total : total * 60 + part), 0);
		},

		/** "62.8K", "1.2M", "945" and similar to a plain number. */
		parseViewCount(text) {
			if (typeof text !== 'string') return 0;
			const normalised = text.trim().replace(/,/g, '');
			const number = parseFloat(normalised);
			if (Number.isNaN(number)) return 0;
			const multipliers = { k: 1e3, m: 1e6, b: 1e9 };
			return number * (multipliers[normalised.slice(-1).toLowerCase()] ?? 1);
		},

		isPlaylistList(list) {
			return (
				list.id.toLowerCase().includes('playlist') ||
				SELECTORS.PLAYLIST_CONTAINERS.some(selector => list.closest(selector))
			);
		},

		videoLists({ includePlaylists }) {
			const lists = Dom.queryAll(SELECTORS.VIDEO_LISTS);
			return includePlaylists ? lists : lists.filter(list => !Site.isPlaylistList(list));
		},

		itemsIn(list) {
			return Dom.queryAll(':scope > li', list);
		},

		isMobilePlayer(doc = document) {
			return Boolean(Dom.query(SELECTORS.MOBILE_PLAYER, doc));
		},

		/** The playlist whose order can be edited on this page, or null. */
		editablePlaylist() {
			return Dom.query(SELECTORS.PLAYLIST_EDIT_LIST);
		},

		/** The elements whose classes change when playlist editing starts or ends. */
		playlistEditIndicators() {
			return [Dom.query(SELECTORS.PLAYLIST_EDIT_TRIGGER), Dom.query(SELECTORS.PLAYLIST_EDIT_FORM)].filter(Boolean);
		},

		isPlaylistEditing() {
			const trigger = Dom.query(SELECTORS.PLAYLIST_EDIT_TRIGGER);
			if (trigger?.classList.contains(SELECTORS.ACTIVE_CLASS)) return true;
			const form = Dom.query(SELECTORS.PLAYLIST_EDIT_FORM);
			return Boolean(form && !form.classList.contains(SELECTORS.HIDDEN_CLASS) && form.style.display !== 'none');
		},

		/** The videos of a playlist, without the ads placed between them. */
		playlistVideoItems(list) {
			return Dom.queryAll(`:scope > ${SELECTORS.PLAYLIST_VIDEO_ITEM}`, list);
		},

		playlistRemoveButtons(root) {
			return Dom.queryAll(SELECTORS.PLAYLIST_DELETE_BUTTON, root);
		},

		allItems() {
			return Site.videoLists({ includePlaylists: true }).flatMap(Site.itemsIn);
		},

		/** Video items found in (or equal to) the given nodes, ignoring <li>s outside video lists. */
		itemsWithin(nodes) {
			const items = new Set();
			for (const node of nodes) {
				if (node.nodeType !== Node.ELEMENT_NODE) continue;
				const candidates = node.matches('li') ? [node] : node.querySelectorAll('li');
				for (const item of candidates) {
					if (item.parentElement?.matches(SELECTORS.VIDEO_LISTS)) items.add(item);
				}
			}
			return [...items];
		},

		countItemsIn(roots) {
			return roots.reduce((total, root) => total + root.querySelectorAll('li').length, 0);
		},

		itemDurationSeconds(item) {
			const text = Dom.query(SELECTORS.DURATION, item)?.textContent;
			return text ? Site.parseDuration(text) : null;
		},

		itemViewCount(item) {
			return Site.parseViewCount(Dom.query(SELECTORS.VIEWS, item)?.textContent ?? '0');
		},

		itemHasAward(item) {
			return Boolean(Dom.query(SELECTORS.AWARD, item));
		},

		itemIsWatched(item) {
			const marker = Dom.query(SELECTORS.WATCHED, item);
			return Boolean(marker && !marker.classList.contains('hidden'));
		},

		itemIsPaid(item) {
			return Boolean(
				Dom.query(SELECTORS.PAID, item) || Dom.query('a', item)?.getAttribute('href') === SELECTORS.PAID_LINK_HREF
			);
		},

		itemIsAI(item) {
			return Boolean(Dom.query(SELECTORS.AI_GENERATED, item));
		},

		itemIsVR(item) {
			return Boolean(Dom.query(SELECTORS.VR, item));
		},

		itemSearchText(item) {
			return item.textContent.toLowerCase();
		},

		playerVideos() {
			return Dom.queryAll(SELECTORS.PLAYER_VIDEO);
		},

		autoscrollList() {
			return Dom.query(SELECTORS.AUTOSCROLL_LIST);
		},

		/** URL of one page of the current playlist, or null when not on a playlist page. */
		playlistChunkUrl(page) {
			const id =
				Dom.query(SELECTORS.PLAYLIST_ID)?.dataset.playlistId ??
				window.location.pathname.match(CONFIG.PATHS.PLAYLIST_ID_FROM_PATH)?.[1];
			const token = Dom.query(SELECTORS.PLAYLIST_TOKEN)?.dataset.token;
			if (!id || !token) return null;
			const url = new URL(CONFIG.PATHS.PLAYLIST_CHUNK, window.location.origin);
			url.searchParams.set('id', id);
			url.searchParams.set('token', token);
			url.searchParams.set('page', String(page));
			return url.toString();
		},

		parseItemsFromHtml(html) {
			const template = document.createElement('template');
			template.innerHTML = html;
			return Dom.queryAll('li[data-video-id]', template.content);
		},

		currentLanguageCode() {
			const dropdown = Dom.query(SELECTORS.LANGUAGE_DROPDOWN);
			return dropdown ? Dom.query(SELECTORS.CURRENT_LANGUAGE, dropdown)?.textContent.trim().toLowerCase() : null;
		},

		englishLanguageLink() {
			return Dom.query(SELECTORS.ENGLISH_OPTION);
		},

		/** The control bar buttons other buttons are placed next to, or null before the controls exist. */
		controlBarAnchors(doc) {
			const fullscreen = Dom.query(SELECTORS.FULLSCREEN_BUTTON, doc);
			if (!fullscreen) return null;
			// A tablet shows the bottom bar's own play button, and its big play button
			// sits in the middle of the video, so the transport buttons go by the bar's.
			const bottomBarPlay = Dom.query(SELECTORS.PLAYER_BOTTOM_BAR_PLAY, doc);
			const barShowsPlay = Boolean(bottomBarPlay) && isShownOnScreen(bottomBarPlay) && bottomBarPlay.getBoundingClientRect().width > 0;
			return {
				fullscreen,
				play: (barShowsPlay && bottomBarPlay) || Dom.queryFirst(SELECTORS.PLAYER_PLAY_BUTTON, doc) || Site._firstControlButton(fullscreen),
				isMobile: Site.isMobilePlayer(doc),
			};
		},

		/**
		 * The player's own next-video button, or null. Known selectors first, then
		 * any of the player's buttons that calls itself "next" in its class or
		 * tooltip, since the class names have changed before.
		 */
		nativeNextButton(doc) {
			const notOurs = element => !element.hasAttribute(PLAYER_BUTTON_ATTRIBUTE);
			const known = Dom.queryAll(SELECTORS.PLAYER_NEXT_BUTTON.join(', '), doc).find(notOurs);
			if (known) return known;
			const describesNext = element =>
				/next/i.test(`${element.className} ${element.getAttribute('data-text') ?? ''} ${element.getAttribute('aria-label') ?? ''}`);
			return Dom.queryAll(`.${SELECTORS.PLAYER_BUTTON_CLASS}`, doc).find(element => notOurs(element) && describesNext(element)) ?? null;
		},

		/**
		 * The leftmost of the player's own control buttons, which is where players put
		 * play/pause. Used when no known play selector matches, since the class
		 * names have changed before. Walks up from the fullscreen button to the
		 * smallest ancestor that holds the whole control bar.
		 */
		_firstControlButton(fullscreen) {
			const { MIN_BUTTONS, MAX_DEPTH } = CONFIG.UI.CONTROL_BAR_SEARCH;
			const ownButtons = `.${SELECTORS.PLAYER_BUTTON_CLASS}:not([${PLAYER_BUTTON_ATTRIBUTE}])`;
			let container = fullscreen.parentElement;
			for (let depth = 0; container && depth < MAX_DEPTH; depth++) {
				const buttons = Dom.queryAll(ownButtons, container);
				if (buttons.length >= MIN_BUTTONS && buttons[0] !== fullscreen) return buttons[0];
				container = container.parentElement;
			}
			return null;
		},

		/**
		 * Where the under-player Download pill goes: right after Share, or right
		 * before Report when Share is missing, in the desktop row; right after
		 * Share in the phone row. Null when none of them is on the page.
		 */
		underPlayerDownloadSpot() {
			const share = Dom.query(SELECTORS.UNDERPLAYER_SHARE)?.closest(SELECTORS.UNDERPLAYER_CELL);
			if (share) return { anchor: share, position: 'after', layout: 'desktop' };
			const report = Dom.query(SELECTORS.UNDERPLAYER_REPORT)?.closest(SELECTORS.UNDERPLAYER_CELL);
			if (report) return { anchor: report, position: 'before', layout: 'desktop' };
			const mobileShare = Dom.query(SELECTORS.UNDERPLAYER_SHARE_MOBILE);
			return mobileShare ? { anchor: mobileShare, position: 'after', layout: 'mobile' } : null;
		},

		videoTitle() {
			return document.title.replace(CONFIG.PATHS.TITLE_SUFFIX, '').trim();
		},

		/** The player's stream list, read from the page's own globals. */
		readMediaDefinitions() {
			// Runs in the page context, so it must not reference anything outside itself.
			function findMediaDefinitionsInPage() {
				const holder = Object.values(window).find(value => value && value.mediaDefinitions);
				return (holder && holder.mediaDefinitions) || window.mediaDefinitions || null;
			}
			return Dom.evaluateInPage(findMediaDefinitionsInPage);
		},

		/** Volume preferences the site's player stores itself, used to seed our own. */
		readPlayerVolumePrefs() {
			const none = { volume: null, muted: null };
			const raw = SafeLocalStorage.get(CONFIG.STORAGE.PLAYER_PREFS_KEY);
			if (!raw) return none;
			try {
				const prefs = JSON.parse(raw)?.volume;
				return {
					volume: typeof prefs?.volume === 'number' ? clamp(prefs.volume, 0, 100) / 100 : null,
					muted: typeof prefs?.muted === 'boolean' ? prefs.muted : null,
				};
			} catch {
				return none;
			}
		},

		// ---- Queue ---------------------------------------------------------

		/** The viewkey in a watch or embed URL, or null. */
		viewkeyOf(url) {
			try {
				const parsed = new URL(url, window.location.origin);
				const { EMBED_PREFIX } = CONFIG.PATHS;
				if (parsed.pathname.startsWith(EMBED_PREFIX)) {
					return parsed.pathname.slice(EMBED_PREFIX.length).split('/')[0] || null;
				}
				return parsed.searchParams.get('viewkey');
			} catch {
				return null;
			}
		},

		currentViewkey() {
			return Site.isWatchPage() ? Site.viewkeyOf(window.location.href) : null;
		},

		watchPath(viewkey) {
			return `${CONFIG.PATHS.WATCH}?viewkey=${encodeURIComponent(viewkey)}`;
		},

		watchUrl(viewkey) {
			return new URL(Site.watchPath(viewkey), window.location.origin).toString();
		},

		/** What the watch page shows about its own video, or null off watch pages. */
		watchPageMeta() {
			const viewkey = Site.currentViewkey();
			if (!viewkey) return null;
			return {
				viewkey,
				title: Dom.queryFirst(SELECTORS.WATCH_TITLE)?.textContent.trim() || Site.videoTitle() || 'Untitled video',
				uploader: Dom.query(SELECTORS.WATCH_UPLOADER)?.textContent.trim() || '',
				duration: Site.watchPageDuration(),
			};
		},

		/**
		 * The watch page's listed length in whole seconds, or null. The page's
		 * own figure comes first: the <video> may be playing a preroll.
		 */
		watchPageDuration() {
			const listed = Number(Dom.query(SELECTORS.WATCH_DURATION)?.dataset.duration);
			if (Number.isFinite(listed) && listed > 0) return Math.round(listed);
			const playing = Site.playerVideos()[0]?.duration;
			return Number.isFinite(playing) ? Math.round(playing) : null;
		},

		/** The three-dot menus currently on the page. */
		actionMenus() {
			return Dom.queryAll(SELECTORS.ACTION_MENU);
		},

		actionMenuWatchLaterLink(menu) {
			return Dom.query(SELECTORS.ACTION_MENU_WATCH_LATER, menu);
		},

		/**
		 * The card a three-dot menu belongs to, like cardAt(). The menu may be
		 * built inside its card or elsewhere on the page, so the video id the
		 * site puts on the menu is the fallback.
		 */
		cardForActionMenu(menu) {
			const inside = Site.cardAt(menu);
			if (inside) return inside;
			const videoId = menu.closest(SELECTORS.ACTION_MENU_HOST)?.id || Dom.query('[data-video-id]', menu)?.dataset.videoId;
			if (!videoId) return null;
			const card = Dom.query(`[data-video-id="${CSS.escape(videoId)}"]`)?.closest(SELECTORS.QUEUE_CARD);
			return card ? Site.cardAt(card) : null;
		},

		/**
		 * The video a three-dot menu is for, as queue metadata, or null. The phone
		 * drawer names its video in its preview; its card, when one is on the
		 * page, adds the duration.
		 */
		actionMenuVideo(menu) {
			const hit = Site.cardForActionMenu(menu);
			const drawer = menu.closest(SELECTORS.ACTION_MENU_DRAWER);
			const preview = drawer && Dom.query(SELECTORS.DRAWER_PREVIEW_LINK, drawer);
			if (!preview) return hit ? Site.cardMeta(hit) : null;
			const viewkey = Site.viewkeyOf(preview.getAttribute('href'));
			if (!viewkey) return null;
			return {
				viewkey,
				title: Dom.query(SELECTORS.DRAWER_PREVIEW_TITLE, drawer)?.textContent.trim() || preview.querySelector('img')?.alt || 'Untitled video',
				uploader: Dom.query(SELECTORS.DRAWER_PREVIEW_UPLOADER, drawer)?.textContent.trim() || '',
				duration: hit && Site.viewkeyOf(hit.anchor.getAttribute('href')) === viewkey ? Site.itemDurationSeconds(hit.card) : null,
			};
		},

		/** The video card under `target` with its link to the video, or null. */
		cardAt(target) {
			const card = target.closest?.(SELECTORS.QUEUE_CARD);
			if (!card) return null;
			const links = Dom.queryAll(SELECTORS.CARD_LINK, card);
			const anchor = links.find(link => Dom.query('img', link)) ?? links[0];
			return anchor && Site.viewkeyOf(anchor.getAttribute('href')) ? { card, anchor } : null;
		},

		cardMeta({ card, anchor }) {
			return {
				viewkey: Site.viewkeyOf(anchor.getAttribute('href')),
				title:
					Dom.query(SELECTORS.CARD_TITLE, card)?.textContent.trim() ||
					anchor.getAttribute('title')?.trim() ||
					Dom.query('img', anchor)?.alt?.trim() ||
					'Untitled video',
				uploader: Dom.query(SELECTORS.CARD_UPLOADER, card)?.textContent.trim() || '',
				duration: Site.itemDurationSeconds(card),
			};
		},

		/** The visible picture of a card, falling back to its link when the picture is not laid out. */
		cardPictureRect(anchor) {
			const { MIN_PICTURE_WIDTH_PX, MIN_PICTURE_HEIGHT_PX } = CONFIG.QUEUE.THUMB_BUTTON;
			const picture = Dom.query('img', anchor)?.getBoundingClientRect();
			return picture && picture.width > MIN_PICTURE_WIDTH_PX && picture.height > MIN_PICTURE_HEIGHT_PX
				? picture
				: anchor.getBoundingClientRect();
		},

		playerContainer() {
			return Dom.query(SELECTORS.WATCH_PLAYER);
		},

		/**
		 * The player's video element. Until the player is built the page only holds
		 * its plain placeholder <video>, which has no source and never plays, so
		 * that one does not count: starting it would leave the queue "playing" a
		 * video that does not exist.
		 */
		videoIn(doc) {
			return Dom.query(SELECTORS.PLAYER_VIDEO, doc) ?? Dom.query(`video:not(${SELECTORS.PLAYER_PLACEHOLDER_VIDEO})`, doc);
		},

		/**
		 * Presses the player's big play button, if it shows one. Returns whether it
		 * did. The phone player does not react to a plain click, so there it gets a
		 * tap: the touch and pointer events a finger would make.
		 */
		pressPlay(doc) {
			const isMobile = Site.isMobilePlayer(doc);
			const button = (isMobile && Dom.query(SELECTORS.PLAYER_BIG_PLAY, doc)) || Dom.query(SELECTORS.PLAYER_PLAY_OVERLAY, doc);
			if (!button) return false;
			if (isMobile) Dom.tap(button);
			else button.click();
			return true;
		},
	};

	// =====================================================================
	// 4. Features
	// =====================================================================

	/**
	 * Sets the age-disclaimer cookie at document-start so the disclaimer never
	 * shows, and reloads once if the server already sent the gated page.
	 */
	class AgeGate {
		constructor(settings) {
			this._settings = settings;
			this._servedWithGate = false;
		}

		/** Must run at document-start, before the page reads its cookies. */
		applyAtDocumentStart() {
			// Captured whether or not the feature is on, so a later reload decision
			// reflects what the server actually saw.
			this._servedWithGate = !this._hasAgeCookie();
			if (this._settings.get('autoConfirmAge')) this.confirm();
		}

		confirm() {
			const { AGE_GATE, CONSENT } = CONFIG.COOKIES;
			Cookies.writeEverywhere(AGE_GATE.name, AGE_GATE.value);
			// A missing or partial consent cookie brings the cookie banner back.
			const consent = Cookies.read(CONSENT.name);
			if (consent === null || consent === CONSENT.partialValue) {
				Cookies.writeEverywhere(CONSENT.name, CONSENT.value);
			}
		}

		/** Reloads once when the gated page was served. Returns true when a reload was started. */
		reloadIfServedWithGate() {
			if (!this._settings.get('autoConfirmAge')) return false;
			const flagKey = CONFIG.STORAGE.AGE_GATE_RELOADED_KEY;
			if (!this._servedWithGate) {
				SafeSessionStorage.remove(flagKey);
				return false;
			}
			if (!this._hasAgeCookie()) this.confirm();
			if (!this._hasAgeCookie()) {
				Log.warn('AgeGate', 'cookie could not be set; not reloading');
				return false;
			}
			// The session flag stops a reload loop if the site keeps serving the gate.
			if (SafeSessionStorage.get(flagKey)) {
				Log.warn('AgeGate', 'already reloaded once this session; not reloading again');
				return false;
			}
			SafeSessionStorage.set(flagKey, 'true');
			Log.info('AgeGate: reloading to clear the age gate');
			window.location.reload();
			return true;
		}

		/** Removes the cookie and reloads so the disclaimer is shown again. */
		revoke() {
			Cookies.removeEverywhere(CONFIG.COOKIES.AGE_GATE.name);
			SafeSessionStorage.remove(CONFIG.STORAGE.AGE_GATE_RELOADED_KEY);
			window.location.reload();
		}

		_hasAgeCookie() {
			return Cookies.read(CONFIG.COOKIES.AGE_GATE.name) !== null;
		}
	}

	/**
	 * Hides persistent site clutter with a stylesheet injected at document-start,
	 * so banners never flash in and late-inserted ones are covered too.
	 */
	// What an ad slot never contains: the video player and its <video>.
	const AD_SLOT_KEEP = `video, ${SELECTORS.WATCH_PLAYER}`;

	const SiteCleanup = {
		STYLE_ID: 'phpro-site-cleanup',
		HIDE_SHORTS_CLASS: 'phpro-hide-shorts',

		install() {
			Dom.addStyle(
				`
				${SELECTORS.CLUTTER.join(',\n')} { display: none !important; }
				html.${SiteCleanup.HIDE_SHORTS_CLASS} ${SELECTORS.SHORTS_SECTION} { display: none !important; }
				/* Rules of their own: a browser without :has() then drops only these, not the list above.
				   The player carries the pill too, for its prerolls, so nothing holding a video is hidden. */
				:has(> ${SELECTORS.AD_SLOT_MARKER}):not(${AD_SLOT_KEEP}, :has(${AD_SLOT_KEEP})) { display: none !important; }
				:is(${SELECTORS.VIDEO_LISTS}) > li:not([data-video-id]):has(${SELECTORS.AD_SLOT_MARKER}) { display: none !important; }
				/* The phone site pads its container to make room for the banner slot, which stays as a gap once the ad is hidden. */
				${SELECTORS.MOBILE_CONTAINER}:has(> div ${SELECTORS.AD_SLOT_MARKER}) { padding-top: 0 !important; }
				`,
				SiteCleanup.STYLE_ID
			);
		},

		setShortsHidden(hidden) {
			if (document.documentElement) {
				document.documentElement.classList.toggle(SiteCleanup.HIDE_SHORTS_CLASS, hidden);
				return;
			}
			// Some mobile browsers run the script before <html> exists.
			const observer = new MutationObserver(() => {
				if (!document.documentElement) return;
				observer.disconnect();
				document.documentElement.classList.toggle(SiteCleanup.HIDE_SHORTS_CLASS, hidden);
			});
			observer.observe(document, { childList: true });
		},
	};

	/** Forces the English version of the site. */
	class LanguageRedirect {
		constructor(settings) {
			this._settings = settings;
		}

		scheduleCheck() {
			if (!this._settings.get('redirectToEnglish')) return;
			setTimeout(() => {
				try {
					this._check();
				} catch (error) {
					Log.error('LanguageRedirect', error);
				}
			}, CONFIG.TIMING.LANGUAGE_CHECK_DELAY_MS);
		}

		_check() {
			const { LANGUAGE } = CONFIG.COOKIES;
			if (Cookies.read(LANGUAGE.name) !== LANGUAGE.value) {
				Cookies.removeEverywhere(LANGUAGE.name);
				Cookies.write(LANGUAGE.name, LANGUAGE.value, { maxAgeSeconds: CONFIG.LIMITS.LANGUAGE_COOKIE_MAX_AGE_S });
				// Language subdomains (de., fr., ...) ignore the cookie, so go to the bare domain.
				const bareDomain = Cookies.rootDomain.slice(1);
				const { protocol, pathname, search } = window.location;
				Log.info(`LanguageRedirect: switching to English on ${bareDomain}`);
				window.location.href = `${protocol}//${bareDomain}${pathname}${search}`;
				return;
			}
			if (Site.currentLanguageCode() !== LANGUAGE.value) Site.englishLanguageLink()?.click();
		}
	}

	/**
	 * Duration bounds in whole minutes. Drives both the listing-URL rewrite
	 * (min_duration / max_duration) and hiding out-of-range items.
	 */
	class DurationFilter {
		constructor(settings) {
			this._settings = settings;
		}

		bounds() {
			return { min: this._settings.get('minDuration'), max: this._settings.get('maxDuration') };
		}

		hasBounds() {
			const { min, max } = this.bounds();
			return min !== null || max !== null;
		}

		isOutOfRange(seconds) {
			if (seconds === null) return false;
			const { min, max } = this.bounds();
			return (min !== null && seconds < min * 60) || (max !== null && seconds > max * 60);
		}

		/** Rewrites a listing URL to carry the saved bounds. Navigates when the URL changes. */
		enforceListingUrl() {
			if (!this._settings.get('enforceSearchDuration') || !Site.isListingPage() || !this.hasBounds()) return;

			const { min, max } = this.bounds();
			const url = new URL(window.location.href);
			const params = url.searchParams;
			const desired = { min_duration: min, max_duration: max };
			const alreadyApplied = Object.entries(desired).every(
				([param, value]) => params.get(param) === (value === null ? null : String(value))
			);
			if (alreadyApplied) return;

			for (const [param, value] of Object.entries(desired)) {
				if (value === null) params.delete(param);
				else params.set(param, String(value));
			}
			Log.info(`DurationFilter: applying listing range (min=${min ?? '-'}, max=${max ?? '-'})`);
			window.location.replace(url.toString());
		}
	}

	/** Hides video items matching any active filter. */
	class VideoFilter {
		constructor(settings, durationFilter) {
			this._settings = settings;
			this._durationFilter = durationFilter;
		}

		hasActiveFilters() {
			const criteria = this._criteria();
			return (
				criteria.hideWatched ||
				criteria.hidePaid ||
				criteria.hideVR ||
				criteria.hideAI ||
				criteria.hideByDuration ||
				criteria.hideWords.length > 0 ||
				criteria.showWords.length > 0
			);
		}

		/** Shows every item again, for while a playlist is being edited. */
		reveal(items) {
			for (const item of items) item.style.display = '';
		}

		/** Shows or hides each item. Defaults to every item on the page. */
		apply(items = Site.allItems()) {
			const criteria = this._criteria();
			for (const item of items) {
				item.style.display = this._shouldHide(item, criteria) ? 'none' : '';
			}
			Log.debug(`VideoFilter: evaluated ${items.length} item(s)`);
		}

		_criteria() {
			const get = name => this._settings.get(name);
			return {
				hideWatched: get('hideWatched'),
				hidePaid: get('hidePaid'),
				hideVR: get('hideVR'),
				hideAI: get('hideAI'),
				hideByDuration: get('hideDurationOutOfRange') && this._durationFilter.hasBounds(),
				hideWords: get('hideWords'),
				showWords: get('showWords'),
			};
		}

		_shouldHide(item, criteria) {
			if (criteria.hideWatched && Site.itemIsWatched(item)) return true;
			if (criteria.hidePaid && Site.itemIsPaid(item)) return true;
			if (criteria.hideVR && Site.itemIsVR(item)) return true;
			if (criteria.hideAI && Site.itemIsAI(item)) return true;
			if (criteria.hideByDuration && this._durationFilter.isOutOfRange(Site.itemDurationSeconds(item))) return true;

			if (criteria.hideWords.length === 0 && criteria.showWords.length === 0) return false;
			const text = Site.itemSearchText(item);
			if (criteria.hideWords.some(word => text.includes(word))) return true;
			return criteria.showWords.length > 0 && !criteria.showWords.some(word => text.includes(word));
		}
	}

	// On <html> while the user edits a playlist's videos.
	const PLAYLIST_EDITING_CLASS = 'phpro-playlist-editing';

	/**
	 * Follows whether the user is editing a playlist and emits
	 * 'playlist:editing' on the bus when that changes.
	 */
	class PlaylistEditMode {
		constructor(bus) {
			this._bus = bus;
			this._editing = false;
		}

		get isEditing() {
			return this._editing;
		}

		watch() {
			const indicators = Site.playlistEditIndicators();
			if (indicators.length === 0) return;
			const observer = new MutationObserver(() => this._update());
			for (const element of indicators) observer.observe(element, { attributes: true, attributeFilter: ['class', 'style'] });
			this._update();
		}

		_update() {
			const editing = Site.isPlaylistEditing();
			if (editing === this._editing) return;
			this._editing = editing;
			document.documentElement.classList.toggle(PLAYLIST_EDITING_CLASS, editing);
			this._bus.emit('playlist:editing', { isEditing: editing });
		}
	}

	// Higher key sorts first. The video id grows with the upload date, which the
	// playlist's own markup does not carry.
	const PLAYLIST_SORT_KEYS = {
		views: item => Site.itemViewCount(item),
		duration: item => Site.itemDurationSeconds(item) ?? 0,
		newest: item => Number(item.dataset.videoId) || 0,
	};

	/**
	 * Re-orders a playlist that is being edited. The site saves whatever order
	 * the list is in when the user presses Save, so sorting the elements is all
	 * it takes. Ads between the videos keep their places.
	 */
	class PlaylistOrder {
		constructor() {
			this._saved = null;
		}

		/** Remembers the order the page loaded with, which is the saved one. Only the first call counts. */
		remember(list) {
			if (!list || this._saved) return;
			this._saved = Site.playlistVideoItems(list);
		}

		sort(list, key, descending) {
			const keyOf = PLAYLIST_SORT_KEYS[key];
			if (!list || !keyOf) return;
			const direction = descending ? -1 : 1;
			const sorted = Site.playlistVideoItems(list)
				.map(item => ({ item, value: keyOf(item) }))
				.sort((a, b) => (a.value - b.value) * direction)
				.map(entry => entry.item);
			this._arrange(list, sorted);
		}

		/** Back to the saved order. Videos the page loaded later go last, in their current order. */
		restore(list) {
			if (!list || !this._saved) return;
			const rank = new Map(this._saved.map((item, index) => [item, index]));
			const sorted = Site.playlistVideoItems(list)
				.map((item, index) => ({ item, rank: rank.get(item) ?? this._saved.length + index }))
				.sort((a, b) => a.rank - b.rank)
				.map(entry => entry.item);
			this._arrange(list, sorted);
		}

		_arrange(list, videoItems) {
			const pending = [...videoItems];
			const children = [...list.children];
			const order = children.map(child => (child.matches(SELECTORS.PLAYLIST_VIDEO_ITEM) ? pending.shift() : child));
			// Skipping no-op reorders keeps the mutation observers quiet.
			if (order.every((child, index) => child === children[index])) return;
			list.append(...order);
		}
	}

	// Higher key sorts first. Array#sort is stable, so 'award' keeps the
	// site's order within the awarded and non-awarded groups.
	const SORT_KEYS = {
		duration: item => Site.itemDurationSeconds(item) ?? 0,
		views: item => Site.itemViewCount(item),
		award: item => (Site.itemHasAward(item) ? 1 : 0),
	};

	/** Re-orders video items within each list. */
	class VideoSorter {
		constructor(settings) {
			this._settings = settings;
		}

		/** Sorts every applicable list by `mode`. Playlists follow the setting unless overridden. */
		sort(mode, { includePlaylists = this._settings.get('sortWithinPlaylists') } = {}) {
			const keyOf = SORT_KEYS[mode];
			if (!keyOf) return;
			const lists = Site.videoLists({ includePlaylists });
			for (const list of lists) this._sortList(list, keyOf);
			Log.debug(`VideoSorter: sorted ${lists.length} list(s) by ${mode}`);
		}

		_sortList(list, keyOf) {
			const items = Site.itemsIn(list);
			const sorted = items
				.map(item => ({ item, key: keyOf(item) }))
				.sort((a, b) => b.key - a.key)
				.map(entry => entry.item);
			// Skipping no-op reorders keeps the mutation observer quiet.
			if (sorted.every((item, index) => item === items[index])) return;
			list.append(...sorted);
		}
	}

	/**
	 * Loads every page of a playlist through the site's chunk endpoint instead of
	 * clicking "Load more" repeatedly. Emits 'autoscroll:state' on the bus.
	 */
	class PlaylistAutoScroller {
		constructor({ bus, onItemsAppended }) {
			this._bus = bus;
			this._onItemsAppended = onItemsAppended;
			this._running = false;
			this._timer = null;
		}

		get isRunning() {
			return this._running;
		}

		start() {
			if (this._running) return;
			const list = Site.autoscrollList();
			if (!list || !Site.playlistChunkUrl(1)) {
				Log.info('AutoScroll: not a playlist page, nothing to load');
				return;
			}
			this._running = true;
			this._page = Math.floor(Site.itemsIn(list).length / CONFIG.LIMITS.PLAYLIST_PAGE_SIZE) + 1;
			this._consecutiveEmpty = 0;
			this._retriedCurrentPage = false;
			Log.info('AutoScroll started');
			this._bus.emit('autoscroll:state', { isRunning: true });
			this._scheduleNext(0);
		}

		stop() {
			if (!this._running) return;
			this._running = false;
			clearTimeout(this._timer);
			this._timer = null;
			Log.info('AutoScroll stopped');
			this._bus.emit('autoscroll:state', { isRunning: false });
		}

		toggle() {
			if (this._running) this.stop();
			else this.start();
		}

		_scheduleNext(delayMs) {
			this._timer = setTimeout(() => this._step(), delayMs);
		}

		async _step() {
			if (!this._running) return;
			let appended = 0;
			try {
				appended = await this._loadPage(this._page);
			} catch (error) {
				Log.error('AutoScroll', error);
				// Nudges the site's own lazy loader in case the endpoint changed.
				window.scrollTo(0, document.body.scrollHeight);
			}
			if (!this._running) return;
			this._advance(appended);
			if (this._running) {
				this._scheduleNext(randomBetween(CONFIG.TIMING.AUTOSCROLL_MIN_DELAY_MS, CONFIG.TIMING.AUTOSCROLL_MAX_DELAY_MS));
			}
		}

		/** Fetches one page and appends the items not already on screen. Returns how many were added. */
		async _loadPage(page) {
			const url = Site.playlistChunkUrl(page);
			if (!url) throw new Error('playlist id or token disappeared');
			const response = await fetch(url, {
				credentials: 'include',
				headers: { 'X-Requested-With': 'XMLHttpRequest' },
			});
			if (!response.ok) throw new Error(`HTTP ${response.status}`);
			const html = await response.text();

			const list = Site.autoscrollList();
			if (!list) {
				this.stop();
				return 0;
			}
			// The endpoint's pagination overlaps, so ids are deduped against the DOM.
			const knownIds = this._removeDuplicateItems(list);
			const incoming = Site.parseItemsFromHtml(html).filter(item => {
				const id = item.dataset.videoId;
				if (knownIds.has(id)) return false;
				knownIds.add(id);
				return true;
			});
			if (incoming.length === 0) return 0;

			list.append(...incoming);
			this._onItemsAppended(incoming);
			const firstVisible = incoming.find(item => item.style.display !== 'none');
			(firstVisible ?? incoming[incoming.length - 1]).scrollIntoView({ behavior: 'smooth', block: 'start' });
			return incoming.length;
		}

		_removeDuplicateItems(list) {
			const seen = new Set();
			for (const item of Dom.queryAll('li[data-video-id]', list)) {
				const id = item.dataset.videoId;
				if (seen.has(id)) item.remove();
				else seen.add(id);
			}
			return seen;
		}

		// An empty page is retried once before it counts, because the endpoint
		// sometimes returns nothing for a page that does have items.
		_advance(appendedCount) {
			if (appendedCount > 0) {
				this._page++;
				this._consecutiveEmpty = 0;
				this._retriedCurrentPage = false;
				return;
			}
			if (!this._retriedCurrentPage) {
				this._retriedCurrentPage = true;
				Log.debug(`AutoScroll: page ${this._page} came back empty, retrying once`);
				return;
			}
			this._retriedCurrentPage = false;
			this._page++;
			this._consecutiveEmpty++;
			if (this._consecutiveEmpty >= CONFIG.LIMITS.AUTOSCROLL_MAX_CONSECUTIVE_EMPTY) {
				Log.info('AutoScroll: no more items, stopping');
				this.stop();
			}
		}
	}

	/**
	 * Remembers when the user last tapped or pressed a key. Browsers and the
	 * player change volume and start playback on their own too, and those
	 * events look identical to real ones; recency of a gesture tells them apart.
	 */
	const GestureTracker = {
		_lastGestureAt: 0,
		_documents: new WeakSet(),

		/** Starts listening in `doc`, the document a player lives in. */
		install(doc = document) {
			if (GestureTracker._documents.has(doc)) return;
			GestureTracker._documents.add(doc);
			const mark = () => {
				GestureTracker._lastGestureAt = Date.now();
			};
			for (const type of ['pointerdown', 'touchstart', 'keydown']) {
				doc.addEventListener(type, mark, { capture: true, passive: true });
			}
		},

		isRecent(windowMs) {
			return Date.now() - GestureTracker._lastGestureAt < windowMs;
		},
	};

	/** True on iOS and iPadOS, where video.volume is read-only and always reports 1. */
	function hasReadOnlyVolume() {
		try {
			return (
				/iP(hone|ad|od)/.test(navigator.platform || '') ||
				(navigator.userAgent.includes('Mac') && 'ontouchend' in document)
			);
		} catch {
			return false;
		}
	}

	/** Keeps player volume and mute state the same across tabs and subdomains. */
	class VolumeSync {
		constructor(settings) {
			this._settings = settings;
			this._watched = new WeakSet();
		}

		/** Applies the saved volume to players not seen before and starts saving the user's changes on them. */
		attach(videos) {
			const unseen = videos.filter(video => !this._watched.has(video));
			for (const video of unseen) this._watch(video);
			this.applyTo(unseen);
		}

		applyTo(videos) {
			if (videos.length === 0) return;
			this._seedFromPlayerPrefs();
			const volume = this._settings.get('savedVolume');
			const muted = this._settings.get('savedMuted');
			for (const video of videos) {
				if (volume !== null) video.volume = volume;
				if (muted !== null) video.muted = muted;
			}
		}

		_seedFromPlayerPrefs() {
			const needsVolume = this._settings.get('savedVolume') === null;
			const needsMuted = this._settings.get('savedMuted') === null;
			if (!needsVolume && !needsMuted) return;
			const prefs = Site.readPlayerVolumePrefs();
			if (needsVolume && prefs.volume !== null) this._settings.set('savedVolume', prefs.volume);
			if (needsMuted && prefs.muted !== null) this._settings.set('savedMuted', prefs.muted);
		}

		_watch(video) {
			this._watched.add(video);
			GestureTracker.install(video.ownerDocument);
			const save = debounce(() => {
				// Mobile browsers mute for autoplay policy and the player mutes during
				// setup; persisting those would overwrite the saved state everywhere.
				if (!GestureTracker.isRecent(CONFIG.TIMING.VOLUME_GESTURE_WINDOW_MS)) return;
				this._settings.set('savedMuted', video.muted);
				if (!hasReadOnlyVolume()) this._settings.set('savedVolume', video.volume);
			}, CONFIG.TIMING.VOLUME_SAVE_DEBOUNCE_MS);
			video.addEventListener('volumechange', save);
		}
	}

	/** Mutes each player once, so a user who unmutes is not overruled on the next pass. */
	class AutoMute {
		constructor() {
			this._muted = new WeakSet();
		}

		apply(videos) {
			for (const video of videos) {
				if (this._muted.has(video)) continue;
				video.muted = true;
				this._muted.add(video);
			}
		}

		/** Forgets which players were muted, so the next apply() mutes them again. */
		reset() {
			this._muted = new WeakSet();
		}
	}

	/**
	 * Pauses playback that starts without a user gesture. A single pause() on
	 * load is not enough: the site starts playback from its own scripts, at
	 * times well after the element exists and again after preroll.
	 */
	class AutoplayBlocker {
		constructor() {
			this._enabled = false;
			this._userStartedPlayback = false;
			this._watched = new WeakSet();
		}

		setEnabled(enabled) {
			this._enabled = enabled;
		}

		/**
		 * Stands down for the rest of the page. The queue starts the video on the
		 * page it moved to, and that page has had no click that would tell this
		 * blocker the user asked for playback.
		 */
		allowPlayback() {
			this._userStartedPlayback = true;
		}

		/** Re-arms blocking after the user had started playback themselves. */
		reset() {
			this._userStartedPlayback = false;
		}

		watch(videos) {
			for (const video of videos) {
				if (this._watched.has(video)) continue;
				this._watched.add(video);
				GestureTracker.install(video.ownerDocument);
				video.addEventListener('play', () => this._onPlay(video));
				// The player may have started before we could attach the listener.
				if (!video.paused) this._onPlay(video);
			}
		}

		_onPlay(video) {
			if (!this._enabled || this._userStartedPlayback) return;
			if (GestureTracker.isRecent(CONFIG.TIMING.AUTOPLAY_GESTURE_WINDOW_MS)) {
				// The user pressed play; stand down for the rest of the page or our
				// own listener would keep undoing it.
				this._userStartedPlayback = true;
				return;
			}
			video.pause();
			Log.debug('AutoplayBlocker: blocked autoplay');
		}
	}

	const CursorHider = {
		STYLE_ID: 'phpro-cursor-hide-style',

		setEnabled(enabled) {
			const existing = document.getElementById(CursorHider.STYLE_ID);
			if (!enabled) {
				existing?.remove();
				return;
			}
			Dom.addStyle(
				`
				@keyframes phproHideCursor {
					0%, 99% { cursor: default; }
					100% { cursor: none; }
				}
				${SELECTORS.PLAYER_PLAYING} { animation: none; }
				${SELECTORS.PLAYER_PLAYING}:hover {
					animation: phproHideCursor ${CONFIG.TIMING.CURSOR_HIDE_DELAY_S}s forwards;
				}
				`,
				CursorHider.STYLE_ID
			);
		},
	};

	/** Small status message in the corner of the page. */
	class Toast {
		static STYLE_ID = 'phpro-toast-style';

		constructor() {
			Dom.addStyle(
				`
				.phpro-toast {
					position: fixed; bottom: 25px; left: 25px; padding: 12px 18px;
					background: rgba(0,0,0,0.92); color: #fff; font-size: 14px; border-radius: 8px;
					z-index: 2147483647; border: 1px solid #ff9800; transition: opacity 0.3s;
					font-family: Arial, sans-serif;
				}
				.phpro-toast--fading { opacity: 0; }
				`,
				Toast.STYLE_ID
			);
			this._element = Dom.create('div', { className: 'phpro-toast', attrs: { role: 'status' } });
			document.body.append(this._element);
		}

		update(text) {
			this._element.textContent = text;
		}

		dismissAfter(delayMs) {
			setTimeout(() => {
				this._element.classList.add('phpro-toast--fading');
				setTimeout(() => this._element.remove(), CONFIG.TIMING.TOAST_FADE_MS);
			}, delayMs);
		}
	}

	function sanitizeFilename(name) {
		const cleaned = (name || '')
			// eslint-disable-next-line no-control-regex
			.replace(/[<>:"/\\|?*\x00-\x1f]/g, '_')
			.replace(/\s+/g, ' ')
			.trim()
			.slice(0, CONFIG.LIMITS.FILENAME_MAX_LENGTH);
		return cleaned || 'video';
	}

	/**
	 * Every MP4 the player lists, best quality first, as { quality, url }. Most
	 * videos list a remote endpoint that returns the qualities; some list files
	 * directly. Not every listed file can be fetched, so callers try them in turn.
	 */
	async function resolveVideoCandidates() {
		const media = Site.readMediaDefinitions();
		if (!Array.isArray(media) || media.length === 0) throw new Error('mediaDefinitions not found');
		const candidates = media
			.filter(entry => entry.format === 'mp4' && !entry.remote && entry.videoUrl)
			.map(entry => ({ quality: Number(entry.quality) || 0, url: entry.videoUrl }));
		for (const remote of media.filter(entry => entry.remote && entry.videoUrl)) {
			try {
				const response = await fetch(remote.videoUrl);
				if (!response.ok) throw new Error(`quality list HTTP ${response.status}`);
				const listed = await response.json();
				if (!Array.isArray(listed)) continue;
				for (const entry of listed) {
					if (!entry?.videoUrl || (entry.format && entry.format !== 'mp4')) continue;
					candidates.push({ quality: Number(entry.quality) || 0, url: entry.videoUrl });
				}
			} catch (error) {
				Log.warn('DownloadButton', `could not read a quality list: ${error}`);
			}
		}
		const unique = [...new Map(candidates.map(candidate => [candidate.url, candidate])).values()];
		if (unique.length === 0) throw new Error('no MP4 stream in mediaDefinitions');
		return unique.sort((a, b) => b.quality - a.quality);
	}

	/**
	 * Fetches `url` and saves it under `filename`, run by the page itself.
	 * Userscript managers that sandbox the script send its requests from another
	 * origin, which the video servers answer with 404; from the page the same
	 * address works. Runs in the page, so it must not reference anything outside
	 * itself; it reports back through postMessage on `channel`.
	 */
	function downloadInPage(url, filename, channel, revokeAfterMs) {
		const report = (type, detail) => window.postMessage({ channel, type, ...detail }, window.location.origin);
		(async () => {
			const response = await fetch(url);
			if (!response.ok || !response.body) throw new Error(`HTTP ${response.status}`);
			const total = Number(response.headers.get('Content-Length')) || 0;
			const reader = response.body.getReader();
			const chunks = [];
			let received = 0;
			for (;;) {
				const { done, value } = await reader.read();
				if (done) break;
				chunks.push(value);
				received += value.length;
				report('progress', { received, total });
			}
			const objectUrl = URL.createObjectURL(new Blob(chunks, { type: 'video/mp4' }));
			const link = document.createElement('a');
			link.href = objectUrl;
			link.download = filename;
			document.body.append(link);
			link.click();
			link.remove();
			// Revoking straight after click() can cancel the download in some browsers.
			setTimeout(() => URL.revokeObjectURL(objectUrl), revokeAfterMs);
			report('done', {});
		})().catch(error => report('error', { message: String(error?.message ?? error) }));
	}

	/** Has the page download `url` as `filename`, reporting progress. Rejects with the page's error. */
	function downloadToFile(url, filename, onProgress) {
		const channel = `phpro-download-${Date.now()}-${Math.random().toString(36).slice(2)}`;
		return new Promise((resolve, reject) => {
			const onMessage = event => {
				// Matched on the random channel alone: a sandboxed script's window is a
				// wrapper that does not compare equal to the page's own as the sender.
				if (event.data?.channel !== channel) return;
				const { type, received, total, message } = event.data;
				if (type === 'progress') {
					onProgress(received, total);
					return;
				}
				window.removeEventListener('message', onMessage);
				if (type === 'done') resolve();
				else reject(new Error(message));
			};
			window.addEventListener('message', onMessage);
			Dom.runInPage(downloadInPage, url, filename, channel, CONFIG.TIMING.OBJECT_URL_REVOKE_MS);
		});
	}

	function formatProgress(received, total) {
		const BYTES_PER_MB = 1024 * 1024;
		return total
			? `Downloading... ${((received / total) * 100).toFixed(1)}%`
			: `Downloading... ${(received / BYTES_PER_MB).toFixed(1)} MB`;
	}

	// The player bar's icon is white and sized to the player's own icons, which
	// differ between desktop and phones: the glyph is this many times the drawn
	// height of the fullscreen icon (22 px on desktop). The drawing, not its box:
	// on phones the box is far larger than what is drawn in it. Until it can be
	// measured, the desktop size stands in.
	const DOWNLOAD_PLAYER_ICON_SIZE_PX = 22;
	const DOWNLOAD_PLAYER_ICON_SCALE = 1.75;
	// The font draws the cloud low in its square; raised by this share of its
	// size (2 px on desktop), it lines up with the player's drawn icons.
	const DOWNLOAD_PLAYER_ICON_RAISE_EM = 0.09;
	const DOWNLOAD_BUTTON_KEY = 'download';
	const DOWNLOAD_PILL_ICON_SIZE_PX = 20;
	// The site's pills space their icons from the label through their SVG
	// styling, which a font glyph does not get.
	const DOWNLOAD_PILL_ICON_GAP_PX = 8;
	// The site's own classes for a pill in the phone row, for their look only.
	const SITE_MOBILE_PILL_CLASSES = ['videoCtaPill', 'buttonClass', 'generalBtn'];

	function downloadPlayerIconHtml() {
		const glyph = Dom.iconFont(SELECTORS.SITE_ICONS.DOWNLOAD, DOWNLOAD_PLAYER_ICON_SIZE_PX);
		glyph.style.color = '#ffffff';
		glyph.style.transform = `translateY(-${DOWNLOAD_PLAYER_ICON_RAISE_EM}em)`;
		return glyph.outerHTML;
	}

	// How long after a tap ran a button the click the browser sends for it is ignored.
	const PLAYER_TAP_CLICK_GRACE_MS = 600;

	/**
	 * Routes taps on the script's player buttons to them before the player can
	 * take them. The phone player listens on the window itself and, having been
	 * there first, stops touches on its controls; so this installs at
	 * document-start, ahead of every page script, and listens for pointer and
	 * touch events alike, whichever the browser sends first. A tap is found by
	 * position, since a transparent layer may be what the finger touched; a tap
	 * on a visible button runs it and goes no further. Drags, mouse input and
	 * taps anywhere else pass through untouched.
	 */
	const PlayerTapRouter = {
		_sets: new Set(),
		_pending: null,
		_swallowClicksUntil: 0,

		install(win) {
			const capture = { capture: true };
			win.addEventListener('pointerdown', event => this._onDown(event, event), { ...capture, passive: true });
			win.addEventListener('touchstart', event => this._onDown(event, event.touches[0]), { ...capture, passive: true });
			win.addEventListener('pointerup', event => this._onUp(event, event), { ...capture, passive: false });
			win.addEventListener('touchend', event => this._onUp(event, event.changedTouches[0]), { ...capture, passive: false });
			win.addEventListener('click', event => this._onClick(event), capture);
		},

		register(set) {
			this._sets.add(set);
		},

		unregister(set) {
			this._sets.delete(set);
		},

		_onDown(event, point) {
			if (event.pointerType === 'mouse' || !point) return;
			const hit = this._buttonAt(point.clientX, point.clientY);
			if (!hit) {
				this._pending = null;
				return;
			}
			this._pending = { ...hit, x: point.clientX, y: point.clientY };
			event.stopImmediatePropagation();
		},

		_onUp(event, point) {
			if (event.pointerType === 'mouse' || !point) return;
			const tap = this._pending;
			if (!tap) return;
			event.stopImmediatePropagation();
			// Pointer events come first; the touch events that follow end the same tap.
			if (event.type === 'touchend') this._pending = null;
			if (Math.hypot(point.clientX - tap.x, point.clientY - tap.y) > CONFIG.UI.TAP_SLOP_PX) return;
			if (this._buttonAt(point.clientX, point.clientY)?.key !== tap.key) return;
			this._swallowClicksUntil = Date.now() + PLAYER_TAP_CLICK_GRACE_MS;
			tap.activate(event);
		},

		/** The click the browser sends after a handled tap would otherwise reach the player. */
		_onClick(event) {
			if (Date.now() > this._swallowClicksUntil) return;
			if (!this._buttonAt(event.clientX, event.clientY)) return;
			event.preventDefault();
			event.stopImmediatePropagation();
		},

		_buttonAt(x, y) {
			for (const set of this._sets) {
				const hit = set.buttonAt(x, y);
				if (hit) return hit;
			}
			return null;
		},
	};

	// The player fades its controls out rather than removing them, a few levels
	// up from each button.
	const SHOWN_CHECK_DEPTH = 6;
	const MIN_VISIBLE_OPACITY = 0.05;

	/** Whether `element` and the few ancestors that hide controls are visible. */
	function isShownOnScreen(element) {
		let node = element;
		for (let depth = 0; node && depth < SHOWN_CHECK_DEPTH; depth++, node = node.parentElement) {
			const style = getComputedStyle(node);
			if (style.display === 'none' || style.visibility === 'hidden') return false;
			if (Number(style.opacity) < MIN_VISIBLE_OPACITY) return false;
		}
		return true;
	}

	// Where a button goes in the player's control bar. Placement is checked
	// loosely (same group, right side of the anchor) so that several sets
	// sharing one anchor never keep swapping places with each other.
	const PLAYER_BUTTON_PLACEMENT = Object.freeze({
		BEFORE_FULLSCREEN: 'beforeFullscreen',
		BEFORE_PLAY: 'beforePlay',
		AFTER_PLAY: 'afterPlay',
	});

	/**
	 * Keeps a set of buttons in a player's control bar. The player builds its
	 * controls after load and rebuilds them (after ads, on resize), so buttons
	 * are put back whenever they go missing rather than added once.
	 * Each button is { key, label, icon, placement, follows, onClick }, where the
	 * optional `follows` is the key of another button in the set to sit right
	 * after. `onAdded` runs after buttons were (re)created, so their owner can
	 * give them their state. A button's optional `replaces` finds a player
	 * button to hide while that button shows, because it stands in for it.
	 */
	class PlayerButtonSet {
		constructor(buttons, { onAdded = () => {} } = {}) {
			this._buttons = buttons;
			this._onAdded = onAdded;
			this._hiddenKeys = new Set();
			this._elements = new Map();
			this._activators = new Map();
			this._doc = null;
			this._observer = null;
			this._settleTimer = null;
		}

		/** Starts keeping the buttons in `doc`'s player, leaving any earlier document. */
		attach(doc) {
			if (doc && doc === this._doc) {
				this._ensure();
				return;
			}
			this.detach();
			if (!doc?.documentElement) return;
			this._doc = doc;
			this._observer = new MutationObserver(() => {
				clearTimeout(this._settleTimer);
				this._settleTimer = setTimeout(() => this._ensure(), CONFIG.TIMING.PLAYER_BUTTONS_SETTLE_MS);
			});
			this._observer.observe(doc.documentElement, { childList: true, subtree: true });
			// Turning a tablet or resizing the window changes the layout without adding anything.
			this._onResize = () => {
				clearTimeout(this._settleTimer);
				this._settleTimer = setTimeout(() => this._ensure(), CONFIG.TIMING.PLAYER_BUTTONS_SETTLE_MS);
			};
			doc.defaultView?.addEventListener('resize', this._onResize);
			this._addStyle(doc);
			PlayerTapRouter.register(this);
			this._ensure();
		}

		detach() {
			this._observer?.disconnect();
			this._observer = null;
			if (this._onResize) this._doc?.defaultView?.removeEventListener('resize', this._onResize);
			this._onResize = null;
			PlayerTapRouter.unregister(this);
			clearTimeout(this._settleTimer);
			for (const element of this._elements.values()) element.remove();
			this._elements.clear();
			for (const element of this._doc?.querySelectorAll(`[${REPLACED_PLAYER_BUTTON_ATTRIBUTE}]`) ?? []) {
				element.removeAttribute(REPLACED_PLAYER_BUTTON_ATTRIBUTE);
			}
			this._doc = null;
		}

		// The phone player hides its controls by a class on itself. The rows of
		// buttons hide with it on their own, except the middle one our transport
		// buttons sit in, so those follow the class; while hidden, taps go through.
		_addStyle(doc) {
			if (doc.getElementById(PLAYER_BUTTON_STYLE_ID)) return;
			const style = doc.createElement('style');
			style.id = PLAYER_BUTTON_STYLE_ID;
			style.textContent = `
				:is(${SELECTORS.MOBILE_PLAYER}) ${SELECTORS.MOBILE_MIDDLE_CONTROLS} > [${PLAYER_BUTTON_ATTRIBUTE}] {
					transition: opacity ${MOBILE_CONTROLS_FADE_MS}ms;
				}
				:is(${SELECTORS.MOBILE_PLAYER}):not(.${MOBILE_CONTROLS_SHOWN_CLASS}) ${SELECTORS.MOBILE_MIDDLE_CONTROLS} > [${PLAYER_BUTTON_ATTRIBUTE}] {
					opacity: 0 !important; pointer-events: none !important;
				}`;
			(doc.head ?? doc.documentElement).append(style);
		}

		/**
		 * Shows or hides the button for `key`. A hidden button gives the player's
		 * own button it replaces back.
		 */
		setShown(key, shown) {
			if (shown) this._hiddenKeys.delete(key);
			else this._hiddenKeys.add(key);
			const element = this._elements.get(key);
			if (element) element.style.display = shown ? '' : 'none';
			if (this._doc) this._hideReplaced();
		}

		/** The live element for `key`, for showing state such as disabled or a count. */
		element(key) {
			return this._elements.get(key) ?? null;
		}

		_ensure() {
			const anchors = this._doc ? Site.controlBarAnchors(this._doc) : null;
			if (!anchors) return;
			let created = false;
			for (const spec of this._buttons) {
				let element = this._elements.get(spec.key);
				if (!element) {
					element = this._create(spec);
					if (this._hiddenKeys.has(spec.key)) element.style.display = 'none';
					this._elements.set(spec.key, element);
					created = true;
				}
				if (!this._isPlaced(element, spec, anchors)) this._place(element, spec, anchors);
				this._sizeLikeNeighbours(element);
			}
			this._hideReplaced();
			if (created) this._onAdded();
		}

		/**
		 * The phone player sizes its own buttons by their classes, which these do
		 * not have, and lays its icons out of the flow, so a button of ours can end
		 * up with no height at all and cannot be tapped. Such a button takes the
		 * height of one of the player's buttons in the same row and is made square.
		 * Hidden ones are left alone, and so is any button that already has a size.
		 * Only the phone player needs this.
		 */
		_sizeLikeNeighbours(element) {
			// The desktop player sizes every button itself, and a neighbour measured
			// mid-layout there can be far too big.
			if (!Site.isMobilePlayer(this._doc)) return;
			if (element.style.display === 'none' || element.getBoundingClientRect().height >= 1) return;
			const neighbour = [...(element.parentElement?.children ?? [])].find(
				sibling =>
					sibling.classList.contains(SELECTORS.PLAYER_BUTTON_CLASS) &&
					!sibling.hasAttribute(PLAYER_BUTTON_ATTRIBUTE) &&
					sibling.getBoundingClientRect().height >= 1
			);
			const height = neighbour?.getBoundingClientRect().height;
			if (!height) return;
			Object.assign(element.style, { width: `${height}px`, height: `${height}px` });
		}

		// Hidden by a stylesheet rather than inline styles, so the player showing
		// the button again on its own cannot bring it back.
		_hideReplaced() {
			const replacing = this._buttons.filter(spec => spec.replaces);
			if (replacing.length === 0) return;
			if (!this._doc.getElementById(REPLACED_PLAYER_BUTTON_STYLE_ID)) {
				const style = this._doc.createElement('style');
				style.id = REPLACED_PLAYER_BUTTON_STYLE_ID;
				style.textContent = `[${REPLACED_PLAYER_BUTTON_ATTRIBUTE}] { display: none !important; }`;
				(this._doc.head ?? this._doc.documentElement).append(style);
			}
			for (const spec of replacing) {
				spec.replaces(this._doc)?.toggleAttribute(REPLACED_PLAYER_BUTTON_ATTRIBUTE, !this._hiddenKeys.has(spec.key));
			}
		}

		// The play anchor may be missing in some layouts; those buttons then join the right-hand group.
		/**
		 * A button's `mobilePlacement`, when it has one, replaces its placement and
		 * `follows` in the phone player, whose controls are laid out differently.
		 */
		_anchorFor({ placement, follows, mobilePlacement }, anchors) {
			const ownPlacement = anchors.isMobile && mobilePlacement ? mobilePlacement : placement;
			const followed = follows && !(anchors.isMobile && mobilePlacement) ? this._elements.get(follows) : null;
			if (followed?.isConnected) return { node: followed, before: false };
			if (ownPlacement === PLAYER_BUTTON_PLACEMENT.BEFORE_FULLSCREEN || !anchors.play) {
				return { node: anchors.fullscreen, before: true };
			}
			return { node: anchors.play, before: ownPlacement === PLAYER_BUTTON_PLACEMENT.BEFORE_PLAY };
		}

		_isPlaced(element, spec, anchors) {
			const { node, before } = this._anchorFor(spec, anchors);
			if (!element.isConnected || element.parentNode !== node.parentNode) return false;
			const anchorFollows = Boolean(element.compareDocumentPosition(node) & Node.DOCUMENT_POSITION_FOLLOWING);
			return before ? anchorFollows : !anchorFollows;
		}

		_place(element, spec, anchors) {
			const { node, before } = this._anchorFor(spec, anchors);
			if (before) node.before(element);
			else node.after(element);
		}

		_create({ key, label, icon, onClick }) {
			const iconHolder = Dom.create('div', { className: SELECTORS.PLAYER_ICON_CLASS });
			iconHolder.innerHTML = icon;
			const element = Dom.create('div', {
				className: SELECTORS.PLAYER_BUTTON_CLASS,
				attrs: { [PLAYER_BUTTON_ATTRIBUTE]: key, 'aria-label': label, role: 'button' },
				children: [iconHolder],
			});
			Object.assign(element.style, { pointerEvents: 'auto', position: 'relative' });
			let activatedAt = 0;
			const activate = event => {
				// The player toggles playback on any click inside its controls.
				event.preventDefault();
				event.stopImmediatePropagation();
				// A tap is followed by the browser's own click; one press, one action.
				if (Date.now() - activatedAt < PLAYER_TAP_CLICK_GRACE_MS) return;
				activatedAt = Date.now();
				if (element.getAttribute('aria-disabled') !== 'true') onClick();
			};
			element.addEventListener('click', activate);
			this._activators.set(key, activate);
			this._borrowFullscreenTooltip(element, () => element.getAttribute('aria-label'));
			return element;
		}

		/** Which of this set's visible buttons is at (x, y), with its activator, or null. */
		buttonAt(x, y) {
			for (const [key, element] of this._elements) {
				if (!element.isConnected || !isShownOnScreen(element)) continue;
				const box = element.getBoundingClientRect();
				if (x >= box.left && x <= box.right && y >= box.top && y <= box.bottom) {
					return { key, activate: this._activators.get(key) };
				}
			}
			return null;
		}

		// The player draws one tooltip per control from its data-text attribute;
		// borrowing the fullscreen button's keeps ours consistent with the rest.
		_borrowFullscreenTooltip(element, labelOf) {
			element.addEventListener('mouseenter', () => {
				const fullscreen = Site.controlBarAnchors(element.ownerDocument)?.fullscreen;
				if (!fullscreen) return;
				const original = fullscreen.getAttribute('data-text');
				fullscreen.setAttribute('data-text', labelOf());
				fullscreen.dispatchEvent(new MouseEvent('mouseenter', { bubbles: true }));
				setTimeout(() => fullscreen.setAttribute('data-text', original), CONFIG.TIMING.PLAYER_TOOLTIP_RESTORE_MS);
			});
			element.addEventListener('mouseleave', () => {
				Site.controlBarAnchors(element.ownerDocument)?.fullscreen.dispatchEvent(new MouseEvent('mouseleave', { bubbles: true }));
			});
		}
	}

	/** Adds a download button to the player's control bar on watch pages. */
	class DownloadButton {
		constructor() {
			this._downloading = false;
			this._pill = null;
			this._sizeWatcher = new ResizeObserver(() => this._fitPlayerIcon());
			this._buttons = new PlayerButtonSet(
				[
					{
						key: DOWNLOAD_BUTTON_KEY,
						label: 'Download this video',
						icon: downloadPlayerIconHtml(),
						placement: PLAYER_BUTTON_PLACEMENT.BEFORE_FULLSCREEN,
						onClick: () => this._download(),
					},
				],
				{ onAdded: () => this._watchPlayerIconSize() }
			);
		}

		/**
		 * Follows the size of the fullscreen button's icon, which the player sets
		 * per device and changes in fullscreen, so the glyph always matches it.
		 * Controls are rebuilt with new elements, so this re-runs when they are.
		 */
		_watchPlayerIconSize() {
			this._sizeWatcher.disconnect();
			const reference = this._referenceIcon();
			if (reference) this._sizeWatcher.observe(reference);
			this._fitPlayerIcon();
		}

		_referenceIcon() {
			return Site.controlBarAnchors(document)?.fullscreen.querySelector(`.${SELECTORS.PLAYER_ICON_CLASS}`) ?? null;
		}

		/** Gives the glyph's holder the reference icon's box and scales the glyph to it. */
		_fitPlayerIcon() {
			const glyph = this._buttons.element(DOWNLOAD_BUTTON_KEY)?.querySelector(`.${SELECTORS.SITE_ICONS.DOWNLOAD}`);
			const reference = this._referenceIcon();
			const box = reference?.getBoundingClientRect();
			// The path, not its <svg>: on phones the <svg> fills a far larger box.
			const drawn = reference?.querySelector('path')?.getBoundingClientRect();
			if (!glyph || !box?.height || !drawn?.height) return;
			Object.assign(glyph.parentElement.style, {
				width: `${box.width}px`,
				height: `${box.height}px`,
				display: 'flex',
				alignItems: 'center',
				justifyContent: 'center',
			});
			// Phones' controls are never larger than desktop's, so neither is the glyph.
			const size = `${Math.min(Math.round(drawn.height * DOWNLOAD_PLAYER_ICON_SCALE), DOWNLOAD_PLAYER_ICON_SIZE_PX)}px`;
			Object.assign(glyph.style, { width: size, height: size, fontSize: size });
		}

		enable() {
			if (!Site.isWatchPage()) return;
			this._buttons.attach(document);
			this._placePill();
		}

		disable() {
			this._sizeWatcher.disconnect();
			this._buttons.detach();
			this._pill?.remove();
			this._pill = null;
		}

		_createPillIcon() {
			const icon = Dom.iconFont(SELECTORS.SITE_ICONS.DOWNLOAD, DOWNLOAD_PILL_ICON_SIZE_PX);
			icon.style.marginRight = `${DOWNLOAD_PILL_ICON_GAP_PX}px`;
			return icon;
		}

		/** A "Download" pill in the row under the player, right after Share. */
		_placePill() {
			if (this._pill?.isConnected) return;
			const spot = Site.underPlayerDownloadSpot();
			if (!spot) return;
			this._pill ??= spot.layout === 'mobile' ? this._createMobilePill() : this._createPill();
			spot.anchor[spot.position](this._pill);
		}

		/**
		 * Takes the site's pill classes for their look. The click stays here: the
		 * site's handlers for that row read data attributes this pill does not have.
		 */
		_createPill() {
			const label = 'Download this video';
			const item = Dom.create('div', {
				className: 'tab-menu-item tooltipTrig',
				attrs: { role: 'button', tabindex: '0', 'aria-label': label, 'data-title': label },
				children: [this._createPillIcon(), Dom.create('span', { text: 'Download' })],
			});
			Dom.onActivate(item, event => {
				event.stopPropagation();
				this._download();
			});
			return Dom.create('div', { className: 'tab-menu-wrapper-cell videoCtaPill', children: [item] });
		}

		/** The phone row's pills are bare buttons with just an icon, like its Share. */
		_createMobilePill() {
			const label = 'Download this video';
			const button = Dom.create('button', {
				className: SITE_MOBILE_PILL_CLASSES.join(' '),
				attrs: { type: 'button', 'aria-label': label },
				children: [Dom.iconFont(SELECTORS.SITE_ICONS.DOWNLOAD, DOWNLOAD_PILL_ICON_SIZE_PX)],
			});
			button.addEventListener('click', event => {
				event.stopPropagation();
				this._download();
			});
			return button;
		}

		/** Tries each quality from the best down until one can be fetched. */
		async _downloadBestAvailable(toast) {
			const filename = `${sanitizeFilename(Site.videoTitle())}.mp4`;
			const failures = [];
			for (const { quality, url } of await resolveVideoCandidates()) {
				toast.update(quality ? `Downloading ${quality}p...` : 'Downloading...');
				try {
					await downloadToFile(url, filename, (received, total) => toast.update(formatProgress(received, total)));
					return;
				} catch (error) {
					failures.push(`${quality || '?'}p: ${error.message}`);
					Log.warn('DownloadButton', `${quality || '?'}p failed (${error.message}), trying the next quality`);
				}
			}
			throw new Error(`every quality failed (${failures.join(', ')})`);
		}

		async _download() {
			if (this._downloading) return;
			this._downloading = true;
			const toast = new Toast();
			toast.update('Finding highest quality stream...');
			try {
				await this._downloadBestAvailable(toast);
				toast.update('Download started');
				toast.dismissAfter(CONFIG.TIMING.TOAST_SUCCESS_MS);
			} catch (error) {
				Log.error('DownloadButton', error);
				toast.update('Download failed - check console');
				toast.dismissAfter(CONFIG.TIMING.TOAST_FAILURE_MS);
			} finally {
				this._downloading = false;
			}
		}
	}

	/** Tints a playlist item red the moment its delete button is clicked, before the site removes it. */
	const PlaylistDeleteMarker = {
		PENDING_CLASS: 'phpro-delete-pending',

		install() {
			Dom.addStyle(
				`
				li.${PlaylistDeleteMarker.PENDING_CLASS} { position: relative; }
				li.${PlaylistDeleteMarker.PENDING_CLASS}::after {
					content: ''; position: absolute; inset: 0; background-color: red;
					opacity: 0.5; pointer-events: none; z-index: 1000;
				}
				`,
				'phpro-delete-marker-style'
			);
			document.addEventListener('click', event => {
				const deleteButton = event.target?.closest?.(SELECTORS.PLAYLIST_DELETE_BUTTON);
				deleteButton?.closest('li')?.classList.add(PlaylistDeleteMarker.PENDING_CLASS);
			});
		},
	};

	/**
	 * Watches video lists for items added by infinite scroll. Filtering of new
	 * items runs straight away so hidden items never flash; the heavier pass
	 * (sorting, re-scoping) is throttled.
	 */
	class VideoListObserver {
		constructor({ onItemsAdded, onListsChanged }) {
			this._onItemsAdded = onItemsAdded;
			this._onListsChanged = onListsChanged;
			this._observer = null;
			this._roots = [];
			this._lastItemCount = 0;
			this._scheduleStructuralCheck = throttle(() => this._structuralCheck(), CONFIG.TIMING.OBSERVER_THROTTLE_MS);
		}

		/** (Re)connects, scoped to the current video lists or to <body> when none exist yet. */
		connect() {
			this.disconnect();
			const lists = Dom.queryAll(SELECTORS.VIDEO_LISTS);
			this._roots = lists.length > 0 ? lists : [document.body];
			this._lastItemCount = Site.countItemsIn(this._roots);
			this._observer = new MutationObserver(records => this._onMutations(records));
			for (const root of this._roots) this._observer.observe(root, { childList: true, subtree: true });
			Log.debug(`VideoListObserver: watching ${lists.length > 0 ? `${lists.length} list(s)` : 'body'}`);
		}

		disconnect() {
			this._observer?.disconnect();
			this._observer = null;
		}

		_onMutations(records) {
			try {
				const added = Site.itemsWithin(records.flatMap(record => Array.from(record.addedNodes)));
				if (added.length > 0) this._onItemsAdded(added);
				this._scheduleStructuralCheck();
			} catch (error) {
				Log.error('VideoListObserver', error);
			}
		}

		_structuralCheck() {
			if (!this._observer) return;
			const unobserved = Dom.queryAll(SELECTORS.VIDEO_LISTS).filter(list => !this._roots.includes(list));
			if (unobserved.length > 0) {
				this.connect();
				this._onListsChanged();
				return;
			}
			// Our own sorting moves items without changing the count; only a real
			// count change is worth a new pass, which also prevents a sort loop.
			const count = Site.countItemsIn(this._roots);
			if (count === this._lastItemCount) return;
			this._lastItemCount = count;
			this._onListsChanged();
		}
	}

	// =====================================================================
	// 4b. Queue
	//
	// The queue lives in localStorage, shared by every tab on this origin.
	// Which tab plays it is a Web Lock held by that tab; requests between tabs
	// travel as localStorage writes, heard by the other tabs as 'storage' events.
	//
	// Moving to the next video loads its watch page, just as clicking its
	// thumbnail does, and the queue then plays that page's own <video>. Browsers
	// that carry a click on this site over to the next page keep allowing
	// sound; elsewhere the video starts muted with a note to unmute.
	// =====================================================================

	const QUEUE = CONFIG.QUEUE;
	const QUEUE_TIMING = QUEUE.TIMING;
	const STATUS_MS = QUEUE.STATUS_MS;
	const MS_PER_SECOND = 1000;
	// HTMLMediaElement.readyState once the duration is known.
	const HAVE_METADATA = 1;

	function isQueueItem(item) {
		return Boolean(item) && typeof item.viewkey === 'string' && item.viewkey.length > 0 && typeof item.id === 'string';
	}

	/** A queue item for a video, with a fresh id. */
	function toQueueItem({ viewkey, title, uploader, duration }) {
		return {
			viewkey,
			title: title || 'Untitled video',
			uploader: uploader || '',
			duration: Number.isFinite(duration) ? duration : null,
			id: createId(),
		};
	}

	/**
	 * The shared queue state. Edits apply to the in-memory copy right away so the
	 * UI stays synchronous, then are replayed onto the freshly read stored state
	 * under a Web Lock and written. Replaying under the lock is what keeps two
	 * tabs editing at the same moment from overwriting each other.
	 * Emits 'queue:changed' on the bus whenever what it shows may have changed.
	 */
	class QueueStore {
		constructor(bus) {
			this._bus = bus;
			this._cache = null;
			this._viewkeys = new Set();
			// Edits applied to the cache but not yet written, in order.
			this._pending = [];
			this._committing = false;
		}

		/** Current state: what is stored plus this tab's edits still on their way. */
		load() {
			if (this._cache) return this._cache;
			const state = this._readStored();
			for (const edit of this._pending) edit(state);
			this._setCache(state);
			return state;
		}

		/**
		 * Applies `edit` now and queues it to be written. Edits run again on
		 * whatever is stored by commit time, so they must only change the state
		 * they are given and must not create ids or other values inside.
		 */
		mutate(edit) {
			// With nothing in flight, read fresh so the edit sees other tabs' latest writes.
			if (this._pending.length === 0) this.invalidate();
			const state = this.load();
			edit(state);
			this._setCache(state);
			this._pending.push(edit);
			this._scheduleCommit();
			this._bus.emit('queue:changed');
		}

		/** Writes pending edits right away, for when the page is going and a lock grant would come too late. */
		flush() {
			this._commit();
		}

		invalidate() {
			this._cache = null;
		}

		/** Another tab wrote the state. */
		reloadFromOtherTab() {
			this.invalidate();
			this._bus.emit('queue:changed');
		}

		get queue() {
			return [...this.load().queue];
		}

		get history() {
			return [...this.load().history];
		}

		/** Whether the queue plays in any tab, in which case its head is the playing video. */
		get playing() {
			return this.load().playing;
		}

		isQueued(viewkey) {
			this.load();
			return this._viewkeys.has(viewkey);
		}

		peekFirst() {
			return this.load().queue[0] ?? null;
		}

		markPlaying() {
			this.mutate(state => {
				state.playing = true;
				state.movingUntil = 0;
			});
		}

		/**
		 * Stopped, but expected back by `until` (an epoch ms): the playing tab is
		 * loading the next video's page, which starts the queue again.
		 */
		markMovingOn(until) {
			this.mutate(state => {
				state.playing = false;
				state.movingUntil = until;
			});
		}

		markStopped() {
			this.mutate(state => {
				state.playing = false;
				state.movingUntil = 0;
			});
		}

		setQueue(items) {
			const replacement = [...items];
			this.mutate(state => {
				state.queue = [...replacement];
			});
		}

		/** Removes and returns the head this tab saw. */
		shiftQueue() {
			const head = this.peekFirst();
			if (head) {
				this.mutate(state => {
					if (state.queue[0]?.id === head.id) state.queue.shift();
				});
			}
			return head;
		}

		removeItem(id) {
			this.mutate(state => {
				state.queue = state.queue.filter(item => item.id !== id);
			});
		}

		removeViewkey(viewkey) {
			this.mutate(state => {
				state.queue = state.queue.filter(item => item.viewkey !== viewkey);
			});
		}

		/** Moves the item at `from` to `to`, found by id so a concurrent edit cannot move the wrong one. */
		reorder(from, to) {
			const item = this.load().queue[from];
			if (from === to || !item) return;
			this.mutate(state => {
				const at = state.queue.findIndex(candidate => candidate.id === item.id);
				if (at === -1) return;
				state.queue.splice(at, 1);
				state.queue.splice(Math.min(to, state.queue.length), 0, item);
			});
		}

		/** Adds a video to the end. Returns false when it was already queued. */
		add(meta) {
			if (this.isQueued(meta.viewkey)) return false;
			const item = toQueueItem(meta);
			this.mutate(state => {
				if (!state.queue.some(existing => existing.viewkey === item.viewkey)) state.queue.push(item);
			});
			return true;
		}

		/**
		 * Makes a video play next, moving it if already queued. The head is the
		 * video being watched while the queue plays, while it moves on to the next
		 * page, and while the head is simply the page the user is on, so in those
		 * cases the video goes right after it. In front of it, the head would play
		 * again once the queue got to it. Decided on the stored state at commit
		 * time: a tab that has not yet seen another tab start playing would
		 * otherwise put it in front of the playing video.
		 */
		playNext(meta) {
			const item = toQueueItem(meta);
			const watching = Site.currentViewkey();
			this.mutate(state => {
				const headIsWatched = Boolean(watching) && state.queue[0]?.viewkey === watching;
				const headInUse = state.playing || state.movingUntil > Date.now() || headIsWatched;
				const keepHead = headInUse && state.queue.length > 0;
				if (keepHead && state.queue[0].viewkey === item.viewkey) return;
				state.queue = state.queue.filter(existing => existing.viewkey !== item.viewkey);
				state.queue.splice(keepHead ? 1 : 0, 0, item);
			});
		}

		/** Puts an item back at the front, for going to the previous video. */
		unshift(item) {
			this.mutate(state => {
				state.queue.unshift(item);
			});
		}

		pushHistory(item) {
			const entry = { ...item, id: createId() };
			this.mutate(state => {
				state.history.push(entry);
				if (state.history.length > QUEUE.HISTORY_MAX) state.history.shift();
			});
		}

		/** Removes and returns the newest history entry this tab saw. */
		popHistory() {
			const history = this.load().history;
			const last = history[history.length - 1] ?? null;
			if (last) {
				this.mutate(state => {
					if (state.history[state.history.length - 1]?.id === last.id) state.history.pop();
				});
			}
			return last;
		}

		_setCache(state) {
			this._cache = state;
			this._viewkeys = new Set(state.queue.map(item => item.viewkey));
		}

		_readStored() {
			const blank = { queue: [], history: [], playing: false, movingUntil: 0 };
			try {
				const stored = JSON.parse(SafeLocalStorage.get(QUEUE.STORAGE.STATE));
				if (!stored || typeof stored !== 'object') return blank;
				return {
					queue: Array.isArray(stored.queue) ? stored.queue.filter(isQueueItem) : [],
					history: Array.isArray(stored.history) ? stored.history.filter(isQueueItem) : [],
					playing: stored.playing === true,
					movingUntil: Number.isFinite(stored.movingUntil) ? stored.movingUntil : 0,
				};
			} catch (error) {
				Log.warn('QueueStore.read', error);
				return blank;
			}
		}

		_writeStored(state) {
			SafeLocalStorage.set(QUEUE.STORAGE.STATE, JSON.stringify(state));
		}

		_scheduleCommit() {
			if (this._committing) return;
			// Without Web Locks two tabs can still race, but the queue keeps working.
			if (!navigator.locks) {
				this._commit();
				return;
			}
			this._committing = true;
			navigator.locks
				.request(QUEUE.LOCKS.STATE, () => this._commit())
				.catch(error => {
					Log.warn('QueueStore.commit', error);
					// Some browsers refuse the lock's result to a userscript; the edits still have to be saved.
					this._commit();
				})
				.finally(() => {
					this._committing = false;
					if (this._pending.length > 0) this._scheduleCommit();
				});
		}

		/** Replays pending edits onto the stored state and writes it. Runs inside the lock, or at unload. */
		_commit() {
			if (this._pending.length === 0) return;
			const shown = JSON.stringify(this._cache);
			const state = this._readStored();
			for (const edit of this._pending.splice(0)) edit(state);
			this._writeStored(state);
			this._setCache(state);
			// Another tab's edit landed in between, so what this tab showed is out of date.
			if (JSON.stringify(state) !== shown) this._bus.emit('queue:changed');
		}
	}

	/**
	 * Which tab plays the queue. The playing tab holds a Web Lock; starting in
	 * another tab steals it, which tells the old tab to stop. While the shared
	 * playing flag is set, the other tabs wait in line for the lock: being
	 * granted it means the playing tab vanished without stopping (a crash), and
	 * the waiting tab clears the stale flag.
	 */
	class PlayingTab {
		constructor(store, { onLost, onSettled }) {
			this._store = store;
			this._onLost = onLost;
			this._onSettled = onSettled;
			this._held = false;
			this._release = null;
			this._claim = 0;
			this._watching = false;
		}

		/**
		 * Takes playback, from another tab if one has it: the newest start wins.
		 * Called before the playing flag is written, so the lock is held by the
		 * time other tabs see the flag and line up behind it.
		 */
		claim() {
			if (this._held) return;
			this._held = true;
			const claim = ++this._claim;
			if (!navigator.locks) return;
			navigator.locks
				.request(QUEUE.LOCKS.PLAYBACK, { steal: true }, () => {
					// Released before the lock was granted: let it go straight away.
					if (claim !== this._claim || !this._held) return undefined;
					return new Promise(resolve => {
						this._release = resolve;
					});
				})
				.catch(error => {
					if (error.name === 'AbortError' && claim === this._claim) this._lost();
				});
		}

		release() {
			if (!this._held) return;
			this._held = false;
			this._claim++;
			this._release?.();
			this._release = null;
		}

		/** Lines up for the lock while another tab plays, to notice if it vanishes. */
		watchOwner() {
			if (!navigator.locks || this._held || this._watching || !this._store.playing) return;
			this._watching = true;
			// A stolen lock passes straight to the thief, so being granted it means
			// nobody plays. The flag is read under the state lock, behind any write
			// the playing tab made before letting go, so only a crash leaves it set.
			navigator.locks
				.request(QUEUE.LOCKS.PLAYBACK, () =>
					navigator.locks.request(QUEUE.LOCKS.STATE, () => {
						this._store.invalidate();
						if (this._held || !this._store.playing) return;
						Log.warn('Queue', 'the tab playing the queue closed without stopping it; clearing the playing flag');
						this._store.markStopped();
					})
				)
				.catch(error => Log.warn('PlayingTab.watchOwner', error))
				.finally(() => {
					this._watching = false;
					this._onSettled();
				});
		}

		_lost() {
			this._held = false;
			this._release = null;
			this._onLost();
		}
	}

	/**
	 * Where each queued video was left. The site's player does not resume on its
	 * own, so positions are stored here. Positions near either end are dropped,
	 * and only the newest MAX_ENTRIES are kept.
	 */
	class QueuePositions {
		get(viewkey) {
			const entry = viewkey ? this._load()[viewkey] : null;
			return entry ? entry.t : null;
		}

		save(viewkey, seconds, duration) {
			if (!viewkey || !Number.isFinite(seconds) || !Number.isFinite(duration) || duration <= 0) return;
			const { MIN_SECONDS, END_GAP_SECONDS, MAX_ENTRIES } = QUEUE.POSITIONS;
			const saved = this._load();
			if (seconds < MIN_SECONDS || duration - seconds < END_GAP_SECONDS) delete saved[viewkey];
			else saved[viewkey] = { t: Math.floor(seconds), ts: Date.now() };
			const keys = Object.keys(saved);
			if (keys.length > MAX_ENTRIES) {
				keys
					.sort((a, b) => saved[a].ts - saved[b].ts)
					.slice(0, keys.length - MAX_ENTRIES)
					.forEach(oldest => delete saved[oldest]);
			}
			SafeLocalStorage.set(QUEUE.STORAGE.POSITIONS, JSON.stringify(saved));
		}

		_load() {
			try {
				const saved = JSON.parse(SafeLocalStorage.get(QUEUE.STORAGE.POSITIONS));
				return saved && typeof saved === 'object' ? saved : {};
			} catch {
				return {};
			}
		}
	}

	/**
	 * Media key handlers for the queue. The site's player registers its own
	 * handlers as it starts and the last registration wins, so ours are applied again shortly after, and optionally
	 * on an interval.
	 */
	class QueueMediaSession {
		constructor(settings, { handlers }) {
			this._settings = settings;
			this._handlers = handlers;
			this._refreshTimer = null;
			this._catchUpTimer = null;
			this._registeredAt = 0;
		}

		register() {
			const apply = () => this._applyHandlers(this._handlers);
			apply();
			this._clearTimers();
			this._catchUpTimer = setTimeout(apply, QUEUE_TIMING.MEDIA_SESSION_DELAY_MS);
			if (this._settings.get('queueMediaSessionRefresh')) {
				this._refreshTimer = setInterval(apply, this._settings.get('queueMediaSessionInterval') * MS_PER_SECOND);
			}
		}

		/** register(), at most once per throttle window, for events that come in bursts. */
		registerThrottled() {
			if (Date.now() - this._registeredAt < QUEUE_TIMING.MEDIA_SESSION_THROTTLE_MS) return;
			this._registeredAt = Date.now();
			this.register();
		}

		unregister() {
			this._clearTimers();
			this._applyHandlers(Object.fromEntries(Object.keys(this._handlers).map(action => [action, null])));
		}

		setMetadata(item) {
			const session = this._session();
			if (!session) return;
			try {
				session.metadata = new MediaMetadata({
					title: item.title,
					artist: item.uploader || 'Pornhub',
					album: QUEUE.MEDIA_SESSION_ALBUM,
				});
			} catch (error) {
				Log.debug(`media session metadata failed: ${error}`);
			}
		}

		/**
		 * Only ever 'playing' or 'paused'. 'none' tells the browser there is no
		 * session at all, which can drop the tab's media controls mid-video.
		 */
		setPlaybackState(isPlaying) {
			const session = this._session();
			if (!session) return;
			try {
				session.playbackState = isPlaying ? 'playing' : 'paused';
			} catch (error) {
				Log.debug(`media session state failed: ${error}`);
			}
		}

		_applyHandlers(handlers) {
			const session = this._session();
			if (!session) return;
			for (const [action, handler] of Object.entries(handlers)) {
				try {
					session.setActionHandler(action, handler);
				} catch (error) {
					Log.debug(`setActionHandler(${action}) failed: ${error}`);
				}
			}
		}

		/** Null where the browser has no Media Session API. */
		_session() {
			return navigator.mediaSession ?? null;
		}

		_clearTimers() {
			clearInterval(this._refreshTimer);
			clearTimeout(this._catchUpTimer);
			this._refreshTimer = null;
			this._catchUpTimer = null;
		}
	}

	/**
	 * Plays the queue in this tab: goes to the head's watch page, plays and
	 * watches that page's <video> for the end, and goes on to the next page. Reports to the UI only through the bus:
	 * 'queue:changed' when something shown changed, 'queue:status' with a
	 * message, and 'queue:video' with each video element it takes over.
	 */
	class QueuePlayer {
		constructor({ settings, store, positions, playingTab, bus }) {
			this._settings = settings;
			this._store = store;
			// The queue item this page plays, for its listed duration.
			this._item = null;
			this._positions = positions;
			this._playingTab = playingTab;
			this._bus = bus;

			/** Whether this tab plays the queue. */
			this.playing = false;
			// What the user wants: true after a pause from any control or from the
			// player itself, false after a play or any queue move.
			this._pauseIntent = false;
			// When the queue move in flight started, or 0 when none is.
			this._navigatingSince = 0;
			this._consecutiveSkips = 0;
			this._endPoll = null;
			this._seekCheck = null;
			this._video = null;
			this._viewkey = null;
			this._attachedAt = 0;
			this._listeners = null;
			this._waitTimers = {};
			this._waitGeneration = 0;

			this._mediaSession = new QueueMediaSession(settings, {
				handlers: {
					nexttrack: () => {
						this._status('Skipping...', STATUS_MS.SHORT);
						this.skip();
					},
					previoustrack: () => {
						this._status('Going to previous...', STATUS_MS.SHORT);
						this.previous();
					},
					// Claimed as well so the session stays complete; an incomplete one
					// can lose the hardware keys to another tab or app.
					play: () => this.setPaused(false),
					pause: () => this.setPaused(true),
				},
			});
		}

		/** Starts the queue in this tab. Anywhere but the head's watch page, it first goes there. */
		start() {
			if (!this._settings.get('queueEnabled')) return;
			const head = this._store.peekFirst();
			if (!head) {
				this._status('Queue is empty', STATUS_MS.SHORT);
				return;
			}
			if (Site.currentViewkey() !== head.viewkey) {
				this._goTo(head);
				return;
			}
			this.playing = true;
			this._navigatingSince = 0;
			this._consecutiveSkips = 0;
			this._playingTab.claim();
			this._pauseIntent = false;
			this._store.markPlaying();
			this._leaveCurrent();
			this._item = head;
			this._waitForVideo();
		}

		/**
		 * Stops the queue in this tab. With `handedOver`, another tab has taken
		 * playback and owns the shared flags, so they are left alone.
		 */
		stop({ handedOver = false } = {}) {
			this._waitGeneration++;
			this._clearWaitTimers();
			this._pauseIntent = false;
			this.playing = false;
			this._navigatingSince = 0;
			// The flag before the lock: a waiting tab granted the lock must find it cleared.
			if (!handedOver) this._store.markStopped();
			this._playingTab.release();
			this._clearEndPoll();
			this._detach();
			this._mediaSession.unregister();
			this._changed();
			this._status(handedOver ? 'Queue moved to another tab' : 'Queue stopped');
		}

		/** Another tab took playback. */
		handOver() {
			if (this.playing) this.stop({ handedOver: true });
		}

		isNavigating() {
			return this._navInFlight();
		}

		/** Pauses or resumes the queue video in this tab. */
		setPaused(paused) {
			if (!this.playing) return;
			this._pauseIntent = paused;
			const video = this._pageVideo();
			if (video && !video.ended) {
				if (paused && !video.paused) video.pause();
				else if (!paused && video.paused) this._play(video);
			}
			this._changed();
			this._mediaSession.setPlaybackState(!paused);
		}

		skip() {
			if (this.playing) this.advance();
		}

		advance() {
			// End detection and the skip controls can each fire in separate tasks;
			// the guard keeps two of them from shifting the queue twice.
			if (this._blockedByNav('advance')) return;
			const current = this._store.shiftQueue();
			if (current) this._store.pushHistory(current);
			const next = this._store.peekFirst();
			if (!next) {
				this._leaveCurrent();
				this.stop();
				return;
			}
			this._navigateTo(next);
		}

		previous() {
			if (!this.playing || this._blockedByNav('previous')) return;
			if (this._restartCurrent()) return;
			const previous = this._store.popHistory();
			if (!previous) {
				this._status('No previous video', STATUS_MS.SHORT);
				this._mediaSession.register();
				return;
			}
			const restored = { ...previous, id: createId() };
			this._store.unshift(restored);
			this._navigateTo(restored);
		}

		/** Starts the queue from the most recently played video. Returns false when there is none. */
		startFromPrevious() {
			const previous = this._store.popHistory();
			if (!previous) return false;
			this._store.unshift({ ...previous, id: createId() });
			this.start();
			return true;
		}

		/**
		 * Picks the queue back up on a page this tab loaded while playing it: the
		 * next video's page, or the same page after a reload. Only when the page
		 * shows the head and no other tab started playing meanwhile; starting here
		 * would take playback from that tab.
		 */
		resumeAfterReload() {
			const wasPlaying = SafeSessionStorage.get(QUEUE.STORAGE.RESUME_AFTER_RELOAD) === '1';
			const headingTo = this._takeHeadingTo();
			SafeSessionStorage.remove(QUEUE.STORAGE.RESUME_AFTER_RELOAD);
			if (!wasPlaying) return;
			const head = this._store.peekFirst();
			if (this._store.playing) {
				Log.info('Queue: another tab is playing, not resuming');
				return;
			}
			if (head && Site.currentViewkey() !== head.viewkey && this._wasDiverted(headingTo, head)) {
				Log.info('Queue: landed on another video than the queue went to, going to the queue head');
				this._goTo(head, { retry: true });
				return;
			}
			if (!head || Site.currentViewkey() !== head.viewkey) {
				Log.info('Queue: not on the queue head after reload, not resuming');
				// This tab told the others it was moving on; it is not, so the
				// queue counts as stopped now rather than when that note runs out.
				this._store.markStopped();
				return;
			}
			this.start();
		}

		/**
		 * The site's own autoplay can go to a related video as one ends, at the
		 * same moment the queue goes to its next one, and the later of the two
		 * wins. Landing elsewhere than the queue went is that race, not the user
		 * choosing another video, so the queue goes on to its video, once: a
		 * second miss means something keeps sending the tab away.
		 */
		_wasDiverted(headingTo, head) {
			return headingTo?.viewkey === head.viewkey && !headingTo.retry;
		}

		_takeHeadingTo() {
			const raw = SafeSessionStorage.get(QUEUE.STORAGE.HEADING_TO);
			SafeSessionStorage.remove(QUEUE.STORAGE.HEADING_TO);
			try {
				return raw ? JSON.parse(raw) : null;
			} catch {
				return null;
			}
		}

		/**
		 * Loads `item`'s watch page in this tab, the same page a click on its
		 * thumbnail opens, and leaves a note for that page to play it.
		 */
		_goTo(item, { retry = false } = {}) {
			SafeSessionStorage.set(QUEUE.STORAGE.RESUME_AFTER_RELOAD, '1');
			SafeSessionStorage.set(QUEUE.STORAGE.HEADING_TO, JSON.stringify({ viewkey: item.viewkey, retry }));
			// Told to every tab before the page changes, including when the queue
			// starts here from a page that was not playing it, so none of them
			// offers to start it while this one is on its way.
			this._store.markMovingOn(Date.now() + QUEUE_TIMING.PAGE_MOVE_GRACE_MS);
			this._store.flush();
			window.location.assign(Site.watchUrl(item.viewkey));
		}

		/** The page is going: remember to resume, and hand the queue back to the other tabs. */
		prepareForUnload() {
			if (this.playing) {
				this._savePosition();
				SafeSessionStorage.set(QUEUE.STORAGE.RESUME_AFTER_RELOAD, '1');
				this._store.markMovingOn(Date.now() + QUEUE_TIMING.PAGE_MOVE_GRACE_MS);
			}
			this._store.flush();
			this._playingTab.release();
		}

		// ---- Shared plumbing ------------------------------------------------

		_status(text, duration = STATUS_MS.NORMAL) {
			this._bus.emit('queue:status', { text, duration });
		}

		_changed() {
			this._bus.emit('queue:changed');
		}

		/**
		 * Time-bounded reentrancy guard for the stretch between asking for the
		 * next page and this page going away, where a second advance would drop an
		 * unseen video. Past NAV_GUARD_MS the move has failed (the browser kept
		 * this page), so the guard expires rather than waiting for an unload that
		 * is not coming.
		 */
		_navInFlight() {
			if (!this._navigatingSince) return false;
			if (Date.now() - this._navigatingSince <= QUEUE_TIMING.NAV_GUARD_MS) return true;
			Log.warn('Queue', 'navigation guard expired, releasing');
			this._navigatingSince = 0;
			return false;
		}

		_blockedByNav(action) {
			if (!this._navInFlight()) return false;
			this._status('Still loading, try again', STATUS_MS.BRIEF);
			Log.debug(`Queue ${action}: a move is in flight, ignoring`);
			return true;
		}

		/**
		 * Teardown shared by every move. Detaching matters as much as clearing the
		 * poll: a still-attached pause handler would read the old player stopping
		 * as a user pause and keep the next video from starting.
		 */
		_leaveCurrent() {
			this._detach();
			this._clearEndPoll();
			this._changed();
		}

		/** Moves to `item`. A move is a request to play, so any pause is dropped. */
		_navigateTo(item) {
			this._navigatingSince = Date.now();
			this._pauseIntent = false;
			this._leaveCurrent();
			this._goTo(item);
		}

		_pageVideo() {
			return Site.videoIn(document);
		}

		// ---- Waiting for the page's video ------------------------------------

		_clearWaitTimers() {
			const timers = this._waitTimers;
			clearInterval(timers.poll);
			clearTimeout(timers.early);
			clearTimeout(timers.fallback);
			this._waitTimers = {};
		}

		/**
		 * Waits for the head's <video> to appear on the page, then hands it to
		 * _onVideoReady, or skips the video when it never shows up. Waits can
		 * overlap, so each gets a generation number and a superseded wait's
		 * timers do nothing when they fire.
		 */
		_waitForVideo() {
			if (!this.playing) return;
			const generation = ++this._waitGeneration;
			this._clearWaitTimers();
			const head = this._store.peekFirst();
			if (!head) {
				this.stop();
				return;
			}
			if (this._videoReadyFor(head.viewkey)) {
				this._onVideoReady(this._pageVideo(), head);
				return;
			}
			this._armWaitTimers(head, () => generation !== this._waitGeneration);
		}

		_videoReadyFor(viewkey) {
			return this.playing && Site.currentViewkey() === viewkey && Boolean(this._pageVideo());
		}

		_armWaitTimers(head, superseded) {
			const timers = this._waitTimers;
			let settled = false;
			let pressedPlay = false;
			const settle = () => {
				if (settled || superseded()) return false;
				settled = true;
				this._clearWaitTimers();
				return true;
			};

			timers.poll = setInterval(() => {
				if (superseded()) return;
				if (!this.playing) {
					this._clearWaitTimers();
					return;
				}
				if (this._videoReadyFor(head.viewkey)) {
					if (settle()) this._onVideoReady(this._pageVideo(), head);
					return;
				}
				if (!pressedPlay) pressedPlay = Site.pressPlay(document);
			}, QUEUE_TIMING.WAIT_POLL_MS);

			timers.early = setTimeout(() => {
				if (!this.playing || this._pageVideo() || this._store.queue.length <= 1) return;
				if (settle()) this._skipUnplayable('Video unavailable, skipping');
			}, QUEUE_TIMING.UNAVAILABLE_GRACE_MS);

			timers.fallback = setTimeout(() => {
				if (!this.playing || !settle()) return;
				Log.warn('Queue', `timed out waiting for the video after ${QUEUE_TIMING.NAV_TIMEOUT_MS} ms`);
				if (this._store.queue.length > 1) this._skipUnplayable('Video failed to load, skipping');
				else this.stop();
			}, QUEUE_TIMING.NAV_TIMEOUT_MS);
		}

		/** Like advance() but without history, since the video was never seen. */
		_skipUnplayable(reason) {
			if (!this.playing) return;
			this._consecutiveSkips++;
			if (this._consecutiveSkips >= QUEUE.MAX_CONSECUTIVE_SKIPS) {
				Log.warn('Queue', 'several videos in a row would not load; stopping instead of skipping more');
				this.stop();
				this._status('Several videos would not load, queue stopped', STATUS_MS.LONGER);
				return;
			}
			this._status(`${reason}...`, STATUS_MS.MEDIUM);
			this._navigatingSince = 0;
			this._store.shiftQueue();
			this._leaveCurrent();
			const next = this._store.peekFirst();
			if (!next) {
				this.stop();
				return;
			}
			// Rate-limited so a run of dead videos cannot spin, and re-checked
			// because the queue may be stopped meanwhile.
			setTimeout(() => {
				if (this.playing) this._goTo(next);
			}, QUEUE_TIMING.SKIP_UNPLAYABLE_MS);
		}

		_onVideoReady(video, item) {
			// Before the early return below, or the guard would stay closed and
			// ignore every later skip and previous.
			this._navigatingSince = 0;
			this._consecutiveSkips = 0;
			this._mediaSession.register();
			if (video === this._video) return;
			this._attach(video);
			this._scheduleEndPoll(video);
			this._mediaSession.setMetadata(item);
			this._bus.emit('queue:video', video);
			if (this._pauseIntent) return;
			this._startPlayback(video);
		}

		// ---- Starting playback ---------------------------------------------

		_startPlayback(video) {
			// The phone player loads its stream only once it is started, and a play()
			// made before that is cancelled by the load, leaving its own display stuck
			// on the loading animation. So it is started through its own button first.
			if (Site.isMobilePlayer() && video.readyState < HAVE_METADATA) {
				this._startOnceStreamLoads(video);
				return;
			}
			this._startNow(video);
		}

		_startNow(video) {
			if (this._settings.get('queueRestartFromBeginning')) this._playFromStart(video);
			else this._playFromSavedPosition(video);
		}

		_startOnceStreamLoads(video) {
			Log.info('Queue: starting the phone player through its own play button');
			Site.pressPlay(document);
			const controller = new AbortController();
			let timer = null;
			const proceed = () => {
				controller.abort();
				clearTimeout(timer);
				if (video !== this._video || !this.playing || this._pauseIntent) return;
				this._startNow(video);
			};
			for (const type of ['loadedmetadata', 'loadeddata', 'canplay']) {
				video.addEventListener(type, proceed, { signal: controller.signal });
			}
			// If the player never loads on its own, the plain attempt is the best left.
			timer = setTimeout(proceed, QUEUE_TIMING.STREAM_WAIT_MS);
		}

		/**
		 * Runs `callback` once the video's own stream is loaded. A preroll plays in
		 * the same <video> first, and seeking it would run the ad to its end, which
		 * then reads as this video ending.
		 */
		_whenMainVideoLoaded(video, callback) {
			const isReady = () => video.readyState >= HAVE_METADATA && !this._looksLikeAd(video);
			if (isReady()) {
				callback();
				return;
			}
			const controller = new AbortController();
			const check = () => {
				if (video !== this._video) {
					controller.abort();
					return;
				}
				if (!isReady()) return;
				controller.abort();
				callback();
			};
			for (const type of ['loadedmetadata', 'durationchange']) {
				video.addEventListener(type, check, { signal: controller.signal });
			}
		}

		_playFromSavedPosition(video) {
			const saved = this._positions.get(this._viewkey);
			if (saved !== null) {
				this._whenMainVideoLoaded(video, () => {
					if (Math.abs(video.currentTime - saved) > QUEUE_TIMING.RESTORE_TOLERANCE_S) video.currentTime = saved;
				});
			}
			this._play(video);
		}

		_playFromStart(video) {
			this._whenMainVideoLoaded(video, () => {
				if (video.currentTime <= QUEUE_TIMING.RESTART_SKIP_UNDER_S) return;
				video.currentTime = 0;
				this._holdAtStart(video);
			});
			this._play(video);
		}

		/**
		 * Undoes jumps for a short while after a restart, in case the player
		 * resumes on its own. Normal playback advances at about wall-clock speed,
		 * so a jump well beyond the real time that passed is the player's seek.
		 */
		_holdAtStart(video) {
			let attempts = 0;
			let lastTime = video.currentTime;
			let lastWall = Date.now();
			const reassert = () => {
				if (!this.playing || video.ended || ++attempts > QUEUE_TIMING.RESTART_REASSERT_TRIES) return;
				const time = video.currentTime;
				const wall = Date.now();
				const realSeconds = (wall - lastWall) / MS_PER_SECOND;
				if (time - lastTime > realSeconds + QUEUE_TIMING.RESUME_SEEK_SLACK_S) {
					video.currentTime = 0;
					lastTime = 0;
				} else {
					lastTime = time;
				}
				lastWall = wall;
				setTimeout(reassert, QUEUE_TIMING.RESTART_REASSERT_MS);
			};
			setTimeout(reassert, QUEUE_TIMING.RESTART_REASSERT_MS);
		}

		_play(video) {
			this._tryPlay(video);
			this._retryPlayOnceLoaded(video);
		}

		_tryPlay(video) {
			const soundAllowed = navigator.userActivation?.hasBeenActive ?? true;
			const wantsSound = this._wantsSound();
			// The phone player is the one that leaves an attempt for sound hanging
			// on a page nobody has touched yet, so there it starts muted at once.
			if (!soundAllowed && !video.muted && Site.isMobilePlayer()) {
				video.muted = true;
				if (wantsSound) this._reportSoundBlockedUntilUnmuted(video);
			}
			Log.info(`Queue: starting playback (sound allowed: ${soundAllowed}, muted: ${video.muted}, ready state: ${video.readyState})`);
			setTimeout(() => this._logPlaybackState(video), QUEUE_TIMING.PLAY_STATE_LOG_MS);
			video.play().catch(error => {
				Log.info(`Queue: play() refused (${error?.name})`);
				if (error?.name !== 'NotAllowedError') {
					this._pressPlayIfPaused(video);
					return;
				}
				// The browser blocks sound until the page has been clicked; playing
				// muted keeps the queue moving until the user unmutes.
				video.muted = true;
				video
					.play()
					.then(() => {
						if (wantsSound) this._reportSoundBlockedUntilUnmuted(video);
					})
					.catch(() => this._pressPlayIfPaused(video));
			});
		}

		/** False when the user asked for silence, which makes a "sound was blocked" note wrong. */
		_wantsSound() {
			const keepsMuted = this._settings.get('syncVolume') && this._settings.get('savedMuted') === true;
			const siteKeepsMuted = Site.readPlayerVolumePrefs().muted === true;
			return !this._settings.get('muteByDefault') && !keepsMuted && !siteKeepsMuted;
		}

		_logPlaybackState(video) {
			if (video !== this._video) return;
			Log.info(
				`Queue: playback state after start (paused: ${video.paused}, ready state: ${video.readyState}, time: ${video.currentTime.toFixed(1)}, muted: ${video.muted})`
			);
		}

		/** The note stays up until the user unmutes, since only that fixes it. */
		_reportSoundBlockedUntilUnmuted(video) {
			this._status('Sound was blocked by the browser. Click the video to unmute.', STATUS_MS.STICKY);
			const controller = new AbortController();
			const { signal } = controller;
			// Unmuting ends the note with a confirmation. Any other touch of the page
			// ends it too: the browser allows sound from then on, so the note is stale,
			// and a user who then mutes on purpose should not be told sound was blocked.
			video.addEventListener(
				'volumechange',
				() => {
					if (video.muted) return;
					controller.abort();
					this._status('Sound on', STATUS_MS.BRIEF);
				},
				{ signal }
			);
			for (const type of ['pointerdown', 'keydown']) {
				document.addEventListener(
					type,
					() => {
						controller.abort();
						this._status('', 0);
					},
					{ signal, capture: true, once: true }
				);
			}
		}

		_pressPlayIfPaused(video) {
			if (video.paused) Site.pressPlay(document);
		}

		/**
		 * The phone player only loads its stream once it is started, and then may
		 * pause the element again when the browser held back playback. So after
		 * the first attempt the queue tries again as data arrives, a few times and
		 * only just after the page loaded, and never over a tap of the user's.
		 */
		_retryPlayOnceLoaded(video) {
			this._playRetries = 0;
			const controller = new AbortController();
			const retry = () => {
				const stale = video !== this._video || !this.playing || Date.now() - this._attachedAt > QUEUE_TIMING.PLAY_RETRY_WINDOW_MS;
				if (stale || this._playRetries >= QUEUE_TIMING.PLAY_RETRY_MAX) {
					controller.abort();
					return;
				}
				if (!video.paused || this._looksLikeAd(video) || GestureTracker.isRecent(QUEUE_TIMING.PLAY_RETRY_USER_QUIET_MS)) return;
				this._playRetries++;
				this._pauseIntent = false;
				this._tryPlay(video);
			};
			for (const type of ['loadeddata', 'canplay', 'pause']) video.addEventListener(type, retry, { signal: controller.signal });
		}

		// ---- Watching the video --------------------------------------------

		/** A preroll plays in the same element; one much shorter than the listed video is not the video. */
		_looksLikeAd(video) {
			// Videos queued before their length was known still get it from the page.
			const expected = this._item?.duration ?? Site.watchPageDuration();
			if (!expected || !Number.isFinite(video.duration) || video.duration <= 0) return false;
			const tolerance = Math.max(QUEUE.AD_SHORTER_BY.MIN_S, expected * QUEUE.AD_SHORTER_BY.RATIO);
			return expected - video.duration > tolerance;
		}

		/** The single gate for every "video ended, advance" path. */
		_shouldAdvance(video) {
			if (this._looksLikeAd(video)) {
				Log.debug('Queue: a preroll ended, not advancing');
				return false;
			}
			return this._store.peekFirst()?.viewkey === Site.currentViewkey();
		}

		/** True when the video has ended, or is stopped within the end threshold. */
		_atEnd(video) {
			if (video.ended) return true;
			const duration = video.duration;
			return (
				Number.isFinite(duration) &&
				duration > 0 &&
				video.paused &&
				duration - video.currentTime <= QUEUE_TIMING.END_THRESHOLD_S
			);
		}

		/**
		 * Safety net for paths that never fire 'ended'. Sleeps until END_POLL_LEAD_S
		 * before the end, then checks every END_POLL_TICK_MS.
		 */
		_scheduleEndPoll(video) {
			this._clearEndPoll();
			if (!this.playing || !video) return;
			const nextDelay = () => {
				const left = video.duration - video.currentTime;
				return Number.isFinite(left) && left > QUEUE_TIMING.END_POLL_SLEEP_ABOVE_S
					? (left - QUEUE_TIMING.END_POLL_LEAD_S) * MS_PER_SECOND
					: QUEUE_TIMING.END_POLL_TICK_MS;
			};
			const check = () => {
				if (!this.playing) return;
				if (this._pauseIntent || !this._atEnd(video)) {
					this._endPoll = setTimeout(check, this._pauseIntent ? QUEUE_TIMING.END_POLL_TICK_MS : nextDelay());
					return;
				}
				if (!this._shouldAdvance(video)) {
					this._endPoll = setTimeout(check, QUEUE_TIMING.END_POLL_TICK_MS);
					return;
				}
				this._advanceFromEvent('end poll');
			};
			this._endPoll = setTimeout(check, nextDelay());
		}

		_clearEndPoll() {
			clearTimeout(this._endPoll);
			clearTimeout(this._seekCheck);
			this._endPoll = null;
		}

		_advanceFromEvent(reason) {
			Log.debug(`Queue: advancing (${reason})`);
			this._status('Next video...');
			this.advance();
		}

		_attach(video) {
			this._detach();
			this._listeners = new AbortController();
			const { signal } = this._listeners;
			const on = (type, handler) => video.addEventListener(type, handler, { signal });
			this._video = video;
			this._viewkey = Site.currentViewkey();
			this._attachedAt = Date.now();
			this._watchPosition(on);
			this._watchPause(on, video);
			this._watchEnd(on, video);
			this._watchMediaSession(on);
		}

		_detach() {
			this._savePosition();
			this._listeners?.abort();
			this._listeners = null;
			this._video = null;
			this._viewkey = null;
		}

		/** Never during an ad, whose clock is the ad's. */
		_savePosition() {
			const video = this._video;
			if (!video || !this._viewkey || this._looksLikeAd(video)) return;
			this._positions.save(this._viewkey, video.currentTime, video.duration);
		}

		_watchPosition(on) {
			let lastSave = 0;
			on('timeupdate', () => {
				const now = Date.now();
				if (now - lastSave < QUEUE_TIMING.POSITION_SAVE_MS) return;
				lastSave = now;
				this._savePosition();
			});
			on('pause', () => this._savePosition());
		}

		/** Turns pauses and plays made in the site's player itself into the queue's pause intent. */
		_watchPause(on, video) {
			on('pause', () => {
				if (!this.playing || video.ended || this._pauseIntent || this._looksLikeAd(video)) return;
				// A jump to the end often stops a hair short of the duration without
				// 'ended', which would otherwise read as a manual pause and stall the queue.
				const left = video.duration - video.currentTime;
				if (Number.isFinite(left) && left <= QUEUE_TIMING.END_THRESHOLD_S && this._shouldAdvance(video)) {
					this._advanceFromEvent('paused at the end');
					return;
				}
				// The player pauses its element itself while it starts up.
				if (Date.now() - this._attachedAt < QUEUE_TIMING.EARLY_PAUSE_GRACE_MS) return;
				this._pauseIntent = true;
				this._changed();
				this._mediaSession.setPlaybackState(false);
			});

			on('play', () => {
				if (!this.playing) return;
				this._pauseIntent = false;
				if (!this._endPoll) this._scheduleEndPoll(video);
				this._changed();
				this._mediaSession.setPlaybackState(true);
			});
		}

		_watchEnd(on, video) {
			on('ended', () => {
				if (this.playing && this._shouldAdvance(video)) this._advanceFromEvent('ended');
			});

			// A seek changes how long the end poll should sleep; it would otherwise not
			// wake for minutes. After a short settle, also check whether the seek
			// landed at the end without 'ended' firing.
			on('seeked', () => {
				if (!this.playing) return;
				this._scheduleEndPoll(video);
				const viewkey = this._viewkey;
				clearTimeout(this._seekCheck);
				this._seekCheck = setTimeout(() => {
					if (!this.playing || this._viewkey !== viewkey || this._pauseIntent) return;
					if (this._atEnd(video) && this._shouldAdvance(video)) this._advanceFromEvent('seeked to the end');
				}, QUEUE_TIMING.SEEK_SETTLE_MS);
			});

			on('durationchange', () => {
				if (this.playing && Number.isFinite(video.duration)) this._scheduleEndPoll(video);
			});

			// Cheaper than waiting for the poll tick. Only acts on 'ended': an earlier
			// threshold would move on while seconds still remained.
			on('timeupdate', () => {
				if (!this.playing || this._pauseIntent || !Number.isFinite(video.duration)) return;
				if (video.duration - video.currentTime > QUEUE_TIMING.END_WINDOW_S) return;
				if (video.ended && this._shouldAdvance(video)) this._advanceFromEvent('timeupdate at the end');
			});
		}

		// 'playing' fires when output actually starts, which is the earliest point
		// some browsers hold an OS media session again after the site's player started.
		_watchMediaSession(on) {
			on('playing', () => {
				if (!this.playing) return;
				this._mediaSession.registerThrottled();
				const head = this._store.peekFirst();
				if (head) this._mediaSession.setMetadata(head);
				this._mediaSession.setPlaybackState(true);
			});
		}

		/**
		 * Rewinds to 0 when the video is past PREV_RESTART_AFTER_S, the way Previous
		 * works in a music player. Returns false when Previous should move instead.
		 */
		_restartCurrent() {
			const video = this._video;
			if (!video || video.ended || this._looksLikeAd(video)) return false;
			if (!(video.currentTime > QUEUE_TIMING.PREV_RESTART_AFTER_S)) return false;
			video.currentTime = 0;
			this._status('Restarted', STATUS_MS.BRIEF);
			return true;
		}
	}

	function countOf(count, noun) {
		return `${count} ${noun}${count === 1 ? '' : 's'}`;
	}

	/**
	 * Everything the queue UI may read or do, so the UI never reaches into the
	 * store or the player itself.
	 */
	class QueueController {
		constructor({ store, player, bus }) {
			this._store = store;
			this._player = player;
			this._bus = bus;
		}

		/** What the queue UI shows. */
		snapshot() {
			const state = this._store.load();
			return {
				queue: [...state.queue],
				historyCount: state.history.length,
				playingAnywhere: state.playing,
				// Epoch ms until which a tab moving to the next video still counts as playing.
				movingUntil: state.movingUntil,
				playingHere: this._player.playing,
				navigating: this._player.isNavigating(),
			};
		}

		isQueued(viewkey) {
			return this._store.isQueued(viewkey);
		}

		/** The video this page shows, or null off watch pages. */
		currentVideo() {
			return Site.watchPageMeta();
		}

		/** The box the video plays in, or null off watch pages. */
		playerArea() {
			return Site.isWatchPage() ? Site.playerContainer() : null;
		}

		/** The document whose player shows the video, or null off watch pages. */
		playerDocument() {
			return Site.isWatchPage() ? document : null;
		}

		add(meta) {
			return this._store.add(meta);
		}

		removeItem(id) {
			this._store.removeItem(id);
		}

		removeViewkey(viewkey) {
			this._store.removeViewkey(viewkey);
		}

		playNext(meta) {
			this._store.playNext(meta);
		}

		reorder(from, to) {
			this._store.reorder(from, to);
		}

		/** How many videos wait behind the playing one. Shuffle and clear leave the playing video alone. */
		waitingCount() {
			return this._waitingPart().waiting.length;
		}

		/** Returns how many videos were shuffled. */
		shuffleWaiting() {
			const { playing, waiting } = this._waitingPart();
			if (waiting.length < 2) return 0;
			for (let index = waiting.length - 1; index > 0; index--) {
				const swap = Math.floor(Math.random() * (index + 1));
				[waiting[index], waiting[swap]] = [waiting[swap], waiting[index]];
			}
			this._store.setQueue([...playing, ...waiting]);
			return waiting.length;
		}

		clearWaiting() {
			this._store.setQueue(this._waitingPart().playing);
		}

		/** Skips to the next video, or starts the queue when it is not playing here. */
		next() {
			if (this._player.playing) this._player.skip();
			else this.start();
		}

		/** Stops the queue when it plays in this tab. The video itself plays on. */
		stop() {
			if (this._player.playing) this._player.stop();
		}

		/** Goes back, or starts the queue from the last video played when it is not playing here. */
		previous() {
			if (this._player.playing) {
				this._player.previous();
				return;
			}
			if (!this._player.startFromPrevious()) this._say('No previous video');
		}

		/** Starts the queue in this tab, going to the first video's page when needed. */
		start() {
			if (this._store.queue.length === 0) {
				this._say('Queue is empty');
				return;
			}
			this._player.start();
		}

		_say(text) {
			this._bus.emit('queue:status', { text, duration: STATUS_MS.SHORT });
		}

		_waitingPart() {
			const queue = this._store.queue;
			const live = this._store.playing && queue.length > 0;
			return { playing: live ? queue.slice(0, 1) : [], waiting: live ? queue.slice(1) : queue };
		}
	}

	// =====================================================================
	// 5. UI
	//
	// Two surfaces: the slide-in quick menu (opened by the ☰ Menu button)
	// with the switches, buttons and dropdowns the user picked, and the
	// settings window with every setting, one tab per area.
	// =====================================================================

	const UI_IDS = {
		STYLES: 'phpro-ui-style',
		PANEL: 'phpro-panel',
		MENU_BUTTON: 'phpro-menu-button',
		SETTINGS: 'phpro-settings',
		SORT_SELECT: 'phpro-sort-select',
		QUICK_SORT_SELECT: 'phpro-qm-sort-select',
	};

	const UI_CLASSES = {
		TRANSPARENT: 'phpro-transparent',
		ON_RIGHT: 'phpro-on-right',
		OFFSCREEN: 'phpro-panel--offscreen',
		FADED: 'phpro-faded',
		DRAGGING: 'phpro-dragging',
		ANIMATE_POSITION: 'phpro-animate-position',
		BUTTON_FLASH: 'phpro-btn--flash',
		BUTTON_RUNNING: 'phpro-btn--running',
	};

	// Marks UI where horizontal touch drags are part of the control and must
	// not be read as a swipe to close the panel.
	const NO_SWIPE_ATTRIBUTE = 'data-phpro-no-swipe';

	const TOGGLE_LABELS = {
		autoConfirmAge: 'Auto-confirm age',
		redirectToEnglish: 'Always use English',
		transparency: 'Enable transparency',
		menuOnRight: 'Menu on the right',
		swipeToOpen: 'Swipe to open',
		sortWithinPlaylists: 'Sort within playlists',
		muteByDefault: 'Mute by default',
		blockAutoplay: 'Prevent autoplay',
		syncVolume: 'Sync volume between tabs',
		hideCursor: 'Hide cursor on video',
		downloadButton: 'Enable download button',
		hideWatched: 'Hide watched videos',
		hidePaid: 'Hide paid content',
		hideVR: 'Hide VR videos',
		hideAI: 'Hide AI-generated videos',
		hideShorts: 'Hide Shorts section',
		enforceSearchDuration: 'Default duration search',
		hideDurationOutOfRange: 'Hide videos by duration',
		queueEnabled: 'Enable queue',
		queueRestartFromBeginning: 'Always restart from beginning',
		queueMediaSessionRefresh: 'Keep media keys working',
		queueShortcuts: 'Keyboard shortcuts',
	};

	const SORT_SELECT_LABEL = 'Auto-sort:';

	const SORT_OPTIONS = [
		{ value: 'none', label: 'Off' },
		{ value: 'duration', label: 'By duration' },
		{ value: 'award', label: 'By award' },
		{ value: 'views', label: 'By views' },
	];

	const THUMB_SIDE_OPTIONS = [
		{ value: 'left', label: 'Top left' },
		{ value: 'right', label: 'Top right' },
	];

	const SHORTCUT_LABELS = {
		queueShortcutAdd: 'Add or remove this video:',
		queueShortcutNext: 'Next video:',
		queueShortcutPrev: 'Previous video:',
	};

	// Quick-menu toggles are identified by their storage key, which is how
	// earlier versions stored the picks.
	const QUICK_MENU_TOGGLES = Object.keys(TOGGLE_LABELS);
	const toggleNameForQuickMenuId = id => QUICK_MENU_TOGGLES.find(name => SETTINGS_SCHEMA[name].storageKey === id);

	// Quick-menu item ids are persisted, so they keep their historical values.
	const QUICK_ACTION_IDS = {
		SORT_DURATION: 'action_sortDuration',
		SORT_VIEWS: 'action_sortViews',
		SORT_AWARD: 'action_sortAward',
		AUTOSCROLL: 'action_autoscroll',
		SCROLL_TOP: 'action_scrollTop',
		PLAY_QUEUE: 'action_playQueue',
	};
	const QUICK_MENU_SORT_SELECT_ID = 'dropdown_sortMode';

	const KEYWORD_FILTERS = [
		{
			settingName: 'hideWords',
			inputId: 'inputFilterWords',
			label: 'Hide videos matching:',
			chipClass: 'phpro-chip--hide',
			ariaVerb: 'filter',
		},
		{
			settingName: 'showWords',
			inputId: 'inputShowWords',
			label: 'Show only matching:',
			chipClass: 'phpro-chip--show',
			ariaVerb: 'show-only',
		},
	];

	/*
	 * The settings window: tabs, each with groups of rows. A row is a setting
	 * name (a switch) or { widget }. `showIf` on a group or row lists settings
	 * of which at least one must be on for it to show, so options that do
	 * nothing right now stay out of the way.
	 */
	const SETTINGS_TABS = [
		{
			title: 'General',
			groups: [
				{ rows: ['autoConfirmAge', 'redirectToEnglish'] },
				{ title: 'Menu', rows: ['transparency', 'menuOnRight', 'swipeToOpen'] },
			],
		},
		{
			title: 'Player',
			groups: [{ rows: ['muteByDefault', 'blockAutoplay', 'syncVolume', 'hideCursor', 'downloadButton'] }],
		},
		{
			title: 'Queue',
			groups: [
				{ rows: ['queueEnabled'] },
				{
					title: 'Playback',
					showIf: ['queueEnabled'],
					rows: [
						'queueRestartFromBeginning',
						'queueMediaSessionRefresh',
						{ widget: 'queueMediaSessionInterval', showIf: ['queueMediaSessionRefresh'] },
					],
				},
				{ title: 'Thumbnails', showIf: ['queueEnabled'], rows: [{ widget: 'queueThumbSide' }] },
				{
					title: 'Keyboard',
					showIf: ['queueEnabled'],
					rows: ['queueShortcuts', { widget: 'queueShortcutKeys', showIf: ['queueShortcuts'] }],
				},
			],
		},
		{
			title: 'Feed',
			groups: [
				{ title: 'Sorting', rows: [{ widget: 'sortSelect' }, 'sortWithinPlaylists'] },
				{ title: 'Hide', rows: ['hideWatched', 'hidePaid', 'hideVR', 'hideAI', 'hideShorts'] },
				{
					title: 'Duration',
					rows: [
						'enforceSearchDuration',
						'hideDurationOutOfRange',
						{ widget: 'durationRange', showIf: ['enforceSearchDuration', 'hideDurationOutOfRange'] },
					],
				},
				{ title: 'Keywords', rows: [{ widget: 'keywordFilters' }] },
			],
		},
		{ title: 'Quick menu', groups: [{ rows: [{ widget: 'quickMenuChooser' }] }] },
	];

	const GEAR_ICON_SVG = `<svg viewBox="0 0 20 20" width="14" height="14" aria-hidden="true" focusable="false">
		<circle cx="10" cy="10" r="5.4" fill="orange"/>
		${[0, 60, 120, 180, 240, 300]
			.map(angle => `<rect x="8.3" y="0.8" width="3.4" height="5" rx="0.6" fill="orange" transform="rotate(${angle} 10 10)"/>`)
			.join('')}
		<circle cx="10" cy="10" r="2.3" fill="#161616"/>
	</svg>`;

	const UI_STYLES = `
		.phpro-surface [hidden] { display: none !important; }

		/* Quick menu (slide-in) */
		#${UI_IDS.PANEL} {
			position: fixed; top: 40px; left: 5px; width: 280px; padding: 15px; max-height: 90vh;
			background-color: black; z-index: 999999999; border-radius: 10px; border: 1px solid orange;
			box-sizing: border-box; overflow-y: auto; font-family: Arial, sans-serif; font-size: 13px;
			box-shadow: 0 8px 25px rgba(0,0,0,0.8); transform: translateX(0);
			transition: transform ${CONFIG.TIMING.PANEL_SLIDE_MS}ms cubic-bezier(0.25, 0.1, 0.25, 1);
			scrollbar-color: orange transparent; scrollbar-width: thin;
		}
		#${UI_IDS.PANEL}[hidden] { display: none !important; }
		#${UI_IDS.PANEL}.${UI_CLASSES.ON_RIGHT} { left: auto; right: 5px; }
		#${UI_IDS.PANEL}.${UI_CLASSES.OFFSCREEN} { transform: translateX(-110%); }
		#${UI_IDS.PANEL}.${UI_CLASSES.ON_RIGHT}.${UI_CLASSES.OFFSCREEN} { transform: translateX(110%); }
		#${UI_IDS.PANEL}.${UI_CLASSES.TRANSPARENT} {
			background-color: rgba(0,0,0,0.3); backdrop-filter: blur(1.5rem); -webkit-backdrop-filter: blur(1.5rem);
		}
		#${UI_IDS.PANEL}::-webkit-scrollbar { width: 6px; }
		#${UI_IDS.PANEL}::-webkit-scrollbar-track { background: transparent; }
		#${UI_IDS.PANEL}::-webkit-scrollbar-thumb { background-color: orange; border-radius: 3px; }
		.phpro-category-header {
			color: orange; background-color: #1e1e1e; margin: 0 0 12px; display: block; font-size: 16px;
			padding: 10px; border-radius: 4px; text-transform: uppercase; border-left: 3px solid transparent;
		}
		/* A tint alone disappears against a black page, so transparent mode adds an orange edge. */
		#${UI_IDS.PANEL}.${UI_CLASSES.TRANSPARENT} .phpro-category-header {
			background-color: rgba(0,0,0,0.65); border-left-color: orange;
		}
		.phpro-quick-empty { color: #999; margin: 0 0 12px; line-height: 1.4; }

		/* Settings window */
		#${UI_IDS.SETTINGS} {
			position: fixed; inset: 0; z-index: 1000000000; display: flex; align-items: center; justify-content: center;
			background-color: rgba(0,0,0,0.55); font-family: Arial, sans-serif; font-size: 13px;
		}
		#${UI_IDS.SETTINGS}[hidden] { display: none !important; }
		.phpro-settings-window {
			width: min(420px, 94vw); height: min(600px, 88vh); display: flex; flex-direction: column;
			box-sizing: border-box; background-color: black; border: 1px solid orange; border-radius: 10px;
			box-shadow: 0 8px 25px rgba(0,0,0,0.8); color: white; overflow: hidden;
		}
		.phpro-settings-header {
			display: flex; align-items: center; justify-content: space-between; padding: 12px 14px 0;
			color: orange; font-weight: bold; text-transform: uppercase; letter-spacing: 0.05em;
		}
		.phpro-settings-close {
			width: 28px; height: 28px; padding: 0; border: none; border-radius: 50%; background: none; color: white;
			cursor: pointer; font: bold 20px/1 Arial, sans-serif;
		}
		.phpro-settings-close:hover { color: orange; }
		.phpro-tabs {
			display: flex; gap: 2px; padding: 8px 10px 0; border-bottom: 1px solid #333; overflow-x: auto;
			flex-shrink: 0; scrollbar-width: none;
		}
		.phpro-tab {
			padding: 8px 9px; border: none; border-bottom: 2px solid transparent; background: none; color: #aaa;
			cursor: pointer; font: bold 12px Arial, sans-serif; white-space: nowrap;
		}
		.phpro-tab:hover { color: white; }
		.phpro-tab[aria-selected="true"] { color: orange; border-bottom-color: orange; }
		.phpro-tab-panel {
			flex: 1; min-height: 0; overflow-y: auto; padding: 4px 16px 16px;
			scrollbar-color: orange transparent; scrollbar-width: thin;
		}
		.phpro-group-title {
			margin: 16px 0 10px; color: #999; font-size: 11px; font-weight: bold; text-transform: uppercase;
			letter-spacing: 0.08em;
		}
		.phpro-group:first-child > .phpro-group-title { margin-top: 12px; }
		.phpro-group:first-child > :first-child:not(.phpro-group-title) { margin-top: 14px; }

		/* Switches: state is driven entirely by aria-checked. */
		.phpro-toggle-row { display: flex; align-items: center; gap: 12px; margin-bottom: 10px; width: 100%; }
		.phpro-toggle-row--switch-right { flex-direction: row-reverse; justify-content: space-between; }
		.phpro-toggle-track {
			position: relative; width: 40px; height: 20px; box-sizing: content-box; background-color: #666;
			border-radius: 20px; cursor: pointer; transition: background-color 0.2s; flex-shrink: 0; border: 1px solid white;
		}
		.phpro-toggle-track[aria-checked="true"] { background-color: orange; }
		.phpro-toggle-track:focus-visible { outline: 2px solid orange; outline-offset: 2px; }
		.phpro-toggle-thumb {
			position: absolute; left: 2px; top: 50%; transform: translateY(-50%); width: 16px; height: 16px;
			background-color: white; border-radius: 50%; transition: left 0.2s; box-shadow: 0 1px 3px rgba(0,0,0,0.3);
		}
		.phpro-toggle-track[aria-checked="true"] .phpro-toggle-thumb { left: 22px; }
		.phpro-toggle-label { color: white; font-size: 13px; line-height: 1.4; cursor: pointer; }

		/* Buttons */
		.phpro-btn {
			display: block; width: 100%; margin: 0 0 10px; padding: 8px 12px; background-color: black;
			color: white; border: 1px solid white; border-radius: 10px; cursor: pointer; transition: all 0.3s;
			font-size: 13px; font-family: inherit; box-sizing: border-box;
		}
		.phpro-btn:hover { color: orange; border-color: orange; }
		.${UI_CLASSES.TRANSPARENT} .phpro-btn:not(.phpro-btn--primary) { background-color: rgba(0,0,0,0.45); }
		.phpro-btn--primary {
			margin: 10px 0 0; padding: 10px 12px; background-color: orange; color: black;
			border-color: orange; font-weight: bold; transition: all 0.25s;
		}
		.phpro-btn--primary:hover { background-color: black; color: orange; }
		.phpro-btn--primary + .phpro-btn { margin-top: 10px; }
		.phpro-btn.${UI_CLASSES.BUTTON_RUNNING} { background-color: red !important; border-color: red !important; color: white; }

		/* Label left, control right */
		.phpro-select-row {
			display: flex; align-items: center; justify-content: space-between; margin-bottom: 10px; width: 100%; gap: 10px;
		}
		.phpro-select-row label { color: white; font-size: 13px; white-space: nowrap; flex-shrink: 0; }
		/* Fixed-width controls (key bindings, numbers) line up on the right edge;
		   dropdowns still stretch to fill the row. */
		.phpro-select-row > :last-child { margin-left: auto; }
		.phpro-select {
			flex: 1; background-color: #222; color: white; border: 1px solid #666; border-radius: 6px;
			padding: 4px 8px; font-size: 13px; cursor: pointer; outline: none; min-width: 0;
		}
		.phpro-select:focus { border-color: orange; }
		.phpro-select option { background-color: #222; color: white; }
		.phpro-number-input {
			width: 56px; background-color: #222; color: white; border: 1px solid #666; border-radius: 6px;
			padding: 4px 6px; font-size: 13px; text-align: center; font-family: inherit;
		}
		.phpro-number-input:focus { outline: none; border-color: orange; }
		.phpro-key-btn {
			min-width: 110px; background-color: #222; color: white; border: 1px solid #666; border-radius: 6px;
			padding: 4px 10px; font-size: 13px; cursor: pointer; white-space: nowrap; font-family: inherit;
		}
		.phpro-key-btn:hover { border-color: orange; }
		.phpro-key-btn--recording { border-color: orange; background-color: #7a3b00; }

		/* Text fields and keyword chips */
		.phpro-field { margin-top: 10px; width: 100%; display: flex; flex-direction: column; }
		.phpro-field-label { color: white; display: block; margin-bottom: 6px; font-size: 13px; }
		.phpro-field-label--spaced { margin-bottom: 10px; }
		.phpro-text-input {
			display: block; padding: 8px 12px; border: 1px solid #666; border-radius: 5px; font-size: 14px;
			background-color: #222; color: white; width: 100%; box-sizing: border-box;
		}
		.phpro-chip-list { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 8px; }
		.phpro-chip {
			display: inline-flex; align-items: center; padding: 4px 10px; border-radius: 20px; font-size: 13px;
			font-weight: bold; white-space: nowrap; box-shadow: 0 2px 4px rgba(0,0,0,0.3);
		}
		.phpro-chip--hide { background-color: #ff9800; color: black; }
		.phpro-chip--show { background-color: #1565c0; color: white; }
		.phpro-chip-text { margin-right: 6px; }
		.phpro-chip-remove { cursor: pointer; font-size: 16px; font-weight: bold; line-height: 1; padding: 0 2px; }

		/* Duration range slider */
		.phpro-duration-slider-wrap { width: 100%; }
		.phpro-duration-slider { position: relative; height: 16px; margin: 0 9px; }
		.phpro-duration-slider-track {
			position: absolute; top: 50%; left: 0; right: 0; height: 3px; background-color: #555;
			border-radius: 2px; transform: translateY(-50%);
		}
		.phpro-duration-slider-range {
			position: absolute; top: 50%; height: 3px; background-color: orange; border-radius: 2px; transform: translateY(-50%);
		}
		.phpro-duration-slider-thumb {
			position: absolute; top: 50%; width: 16px; height: 16px; border-radius: 50%; background-color: white;
			border: 2px solid orange; transform: translate(-50%, -50%); cursor: pointer; touch-action: none; z-index: 2;
		}
		.phpro-duration-slider-thumb:focus-visible { outline: 2px solid orange; outline-offset: 2px; }
		.phpro-duration-slider-labels {
			display: flex; justify-content: space-between; margin: 8px 1px 0; font-size: 11px; color: #999;
		}

		/* Quick-menu picker */
		.phpro-chooser-intro { margin: 14px 0 4px; color: #bbb; line-height: 1.4; }
		.phpro-checkbox-row {
			display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-bottom: 8px;
			font-size: 13px; color: white; cursor: pointer;
		}
		.phpro-checkbox {
			appearance: none; -webkit-appearance: none; width: 18px; height: 18px; margin: 0; flex-shrink: 0;
			border: 2px solid #666; border-radius: 6px; background-color: #222; cursor: pointer; position: relative;
			transition: background-color 0.2s, border-color 0.2s;
		}
		.phpro-checkbox:hover { border-color: orange; }
		.phpro-checkbox:checked { background-color: orange; border-color: orange; }
		.phpro-checkbox:checked::after {
			content: ''; position: absolute; left: 5px; top: 1px; width: 4px; height: 9px;
			border: solid black; border-width: 0 2px 2px 0; transform: rotate(45deg);
		}
		.phpro-checkbox:focus-visible { outline: 2px solid orange; outline-offset: 2px; }

		/* Floating menu button */
		#${UI_IDS.MENU_BUTTON} {
			position: fixed; left: 12px; top: 12px; font-size: 13px; color: orange; cursor: grab; z-index: 999999998;
			padding: 8px 15px; background-color: rgba(0,0,0,0.9); border: 2px solid orange; border-radius: 9999px;
			font-weight: bold; font-family: Arial, sans-serif; user-select: none; -webkit-user-select: none;
			box-shadow: 0 4px 15px rgba(0,0,0,0.7); transition: background-color 0.25s, opacity 0.6s;
			white-space: nowrap; display: inline-flex; align-items: center; justify-content: center;
			box-sizing: border-box; touch-action: none;
		}
		#${UI_IDS.MENU_BUTTON}:hover { background-color: #7a3b00; }
		#${UI_IDS.MENU_BUTTON}.${UI_CLASSES.TRANSPARENT} {
			background-color: rgba(0,0,0,0.3); backdrop-filter: blur(1.5rem); -webkit-backdrop-filter: blur(1.5rem);
		}
		#${UI_IDS.MENU_BUTTON}.${UI_CLASSES.TRANSPARENT}:hover { background-color: rgba(122,59,0,0.5); }
		#${UI_IDS.MENU_BUTTON}.${UI_CLASSES.FADED} { opacity: 0.15; }
		#${UI_IDS.MENU_BUTTON}.${UI_CLASSES.ANIMATE_POSITION} {
			transition: left 0.6s cubic-bezier(0.25, 0.1, 0.25, 1), top 0.6s cubic-bezier(0.25, 0.1, 0.25, 1), opacity 0.25s;
		}
		#${UI_IDS.MENU_BUTTON}.${UI_CLASSES.DRAGGING} { cursor: grabbing; transition: none; }

		/* Declared last so the brief click flash wins over every resting and hover background. */
		.phpro-surface .phpro-btn.${UI_CLASSES.BUTTON_FLASH} { background-color: orange !important; transition: none; }
	`;

	// ---- Positioning helpers -------------------------------------------

	function clampToViewport(left, top, width, height, margin) {
		return {
			left: clamp(left, margin, window.innerWidth - width - margin),
			top: clamp(top, margin, window.innerHeight - height - margin),
		};
	}

	/**
	 * Floating elements are saved as distances from their nearest edges rather
	 * than absolute coordinates, so they land in the same corner at any viewport size.
	 */
	const EdgeAnchor = {
		fromRect(rect) {
			const distances = {
				left: rect.left,
				right: window.innerWidth - rect.right,
				top: rect.top,
				bottom: window.innerHeight - rect.bottom,
			};
			return {
				horizontal: distances.left < distances.right ? 'left' : 'right',
				vertical: distances.top < distances.bottom ? 'top' : 'bottom',
				hDistance: Math.min(distances.left, distances.right),
				vDistance: Math.min(distances.top, distances.bottom),
			};
		},

		toPosition(anchor, width, height, margin) {
			const left = anchor.horizontal === 'left' ? anchor.hDistance : window.innerWidth - width - anchor.hDistance;
			const top = anchor.vertical === 'top' ? anchor.vDistance : window.innerHeight - height - anchor.vDistance;
			return clampToViewport(left, top, width, height, margin);
		},
	};

	function placeAt(element, { left, top }) {
		element.style.left = `${left}px`;
		element.style.top = `${top}px`;
		element.style.right = 'auto';
		element.style.bottom = 'auto';
	}

	/**
	 * Makes `element` draggable by `handle` with pointer events, so mouse, pen
	 * and touch share one path. A drag swallows the click that follows it, so
	 * dropping a button does not also activate it.
	 */
	function makeDraggable({ element, handle = element, thresholds, margin, shouldIgnore = () => false, onDragEnd }) {
		let drag = null;
		let suppressNextClick = false;

		handle.addEventListener('pointerdown', event => {
			if (event.button !== 0 || shouldIgnore(event)) return;
			const rect = element.getBoundingClientRect();
			drag = {
				pointerId: event.pointerId,
				startX: event.clientX,
				startY: event.clientY,
				rect,
				threshold: event.pointerType === 'touch' ? thresholds.touch : thresholds.mouse,
				moved: false,
			};
			handle.setPointerCapture?.(event.pointerId);
		});

		handle.addEventListener('pointermove', event => {
			if (!drag || event.pointerId !== drag.pointerId) return;
			const dx = event.clientX - drag.startX;
			const dy = event.clientY - drag.startY;
			if (!drag.moved) {
				if (Math.abs(dx) <= drag.threshold && Math.abs(dy) <= drag.threshold) return;
				drag.moved = true;
				element.classList.add(UI_CLASSES.DRAGGING);
			}
			placeAt(
				element,
				clampToViewport(drag.rect.left + dx, drag.rect.top + dy, drag.rect.width, drag.rect.height, margin)
			);
		});

		const finish = event => {
			if (!drag || event.pointerId !== drag.pointerId) return;
			const moved = drag.moved;
			drag = null;
			element.classList.remove(UI_CLASSES.DRAGGING);
			if (!moved) return;
			suppressNextClick = true;
			// Cleared on the next task in case the release produced no click.
			setTimeout(() => {
				suppressNextClick = false;
			}, 0);
			onDragEnd?.();
		};
		handle.addEventListener('pointerup', finish);
		handle.addEventListener('pointercancel', finish);

		handle.addEventListener(
			'click',
			event => {
				if (!suppressNextClick) return;
				suppressNextClick = false;
				event.preventDefault();
				event.stopImmediatePropagation();
			},
			true
		);
	}

	// ---- Components (each binds itself to the settings it shows) --------

	/**
	 * A switch with its label. The settings window puts the switch on the right,
	 * like its other controls; the quick menu keeps it on the left.
	 */
	function createToggleSwitch(settings, scope, name, { switchSide = 'left' } = {}) {
		const label = TOGGLE_LABELS[name];
		const track = Dom.create('div', {
			className: 'phpro-toggle-track',
			attrs: { role: 'switch', tabindex: '0', 'aria-label': label },
			children: [Dom.create('div', { className: 'phpro-toggle-thumb' })],
		});
		const labelElement = Dom.create('span', { className: 'phpro-toggle-label', text: label });

		const render = () => track.setAttribute('aria-checked', String(settings.get(name)));
		render();
		scope.add(settings.onChange(name, render));

		const toggle = () => settings.toggle(name);
		Dom.onActivate(track, toggle);
		labelElement.addEventListener('click', toggle);

		const className = switchSide === 'right' ? 'phpro-toggle-row phpro-toggle-row--switch-right' : 'phpro-toggle-row';
		return Dom.create('div', { className, children: [track, labelElement] });
	}

	function createActionButton({ label, onClick, modifiers = [] }) {
		const button = Dom.create('button', {
			className: ['phpro-btn', ...modifiers].join(' '),
			text: label,
			attrs: { type: 'button' },
		});
		button.addEventListener('click', () => {
			button.classList.add(UI_CLASSES.BUTTON_FLASH);
			setTimeout(() => button.classList.remove(UI_CLASSES.BUTTON_FLASH), CONFIG.TIMING.BUTTON_FLASH_MS);
			onClick();
		});
		return button;
	}

	function labelledRow(id, label, control) {
		return Dom.create('div', {
			className: 'phpro-select-row',
			children: [Dom.create('label', { text: label, attrs: { for: id } }), control],
		});
	}

	/** A dropdown bound to one enum setting. */
	function createSelect(settings, scope, { id, label, settingName, options }) {
		const select = Dom.create('select', {
			id,
			className: 'phpro-select',
			children: options.map(option => Dom.create('option', { text: option.label, attrs: { value: option.value } })),
		});
		const render = () => {
			select.value = settings.get(settingName);
		};
		render();
		scope.add(settings.onChange(settingName, render));
		select.addEventListener('change', () => {
			if (!settings.set(settingName, select.value)) render();
		});
		return labelledRow(id, label, select);
	}

	/** A whole-number field bound to one setting, clamped to [min, max]. */
	function createNumberField(settings, scope, { id, label, settingName, min, max }) {
		const input = Dom.create('input', {
			id,
			className: 'phpro-number-input',
			attrs: { type: 'number', min: String(min), max: String(max), step: '1' },
		});
		const render = () => {
			input.value = String(settings.get(settingName));
		};
		render();
		scope.add(settings.onChange(settingName, render));
		input.addEventListener('change', () => {
			const value = clamp(Math.round(Number(input.value)), min, max);
			if (Number.isFinite(value)) settings.set(settingName, value);
			// Also when nothing changed, so a clamped or invalid entry shows the stored value.
			render();
		});
		return labelledRow(id, label, input);
	}

	const KeyCombos = {
		_MODIFIER_CODE: /^(Control|Alt|Shift|Meta|OS)(Left|Right)?$/,

		isModifier(event) {
			return KeyCombos._MODIFIER_CODE.test(event.code);
		},

		/** 'Ctrl+Alt+Shift+Meta' (the ones held) plus the key's code, or null when no modifier is held. */
		of(event) {
			if (!event.code || KeyCombos.isModifier(event)) return null;
			const modifiers = [];
			if (event.ctrlKey) modifiers.push('Ctrl');
			if (event.altKey) modifiers.push('Alt');
			if (event.shiftKey) modifiers.push('Shift');
			if (event.metaKey) modifiers.push('Meta');
			// A bare key would fire while typing anywhere on the site.
			return modifiers.length > 0 ? [...modifiers, event.code].join('+') : null;
		},

		/** 'Alt+KeyQ' as 'Alt + Q'. */
		pretty(combo) {
			return combo
				.split('+')
				.map(part => part.replace(/^Key(?=[A-Z]$)/, '').replace(/^Digit/, ''))
				.join(' + ');
		},
	};

	/**
	 * A key-binding button: click it, then press the new combination. Esc or
	 * clicking away cancels. A combination bound to another action is refused
	 * rather than silently taken from it.
	 */
	function createShortcutField(settings, scope, { id, label, settingName, otherSettings }) {
		const button = Dom.create('button', { id, className: 'phpro-key-btn', attrs: { type: 'button' } });
		let stopRecording = null;

		const show = () => {
			button.classList.remove('phpro-key-btn--recording');
			button.textContent = KeyCombos.pretty(settings.get(settingName));
		};
		const cancel = () => {
			stopRecording?.();
			stopRecording = null;
			show();
		};
		// Registered on window in the capture phase, so it runs before the queue's
		// own shortcuts and the site's player keys and stops them from seeing the press.
		const onKey = event => {
			event.preventDefault();
			event.stopImmediatePropagation();
			if (event.code === 'Escape') return cancel();
			if (KeyCombos.isModifier(event)) return undefined;
			const combo = KeyCombos.of(event);
			if (!combo) {
				button.textContent = 'Needs a modifier';
				return undefined;
			}
			if (otherSettings.some(other => settings.get(other) === combo)) {
				button.textContent = 'Already in use';
				return undefined;
			}
			settings.set(settingName, combo);
			return cancel();
		};

		button.addEventListener('click', () => {
			if (stopRecording) return cancel();
			button.classList.add('phpro-key-btn--recording');
			button.textContent = 'Press keys...';
			window.addEventListener('keydown', onKey, true);
			stopRecording = () => window.removeEventListener('keydown', onKey, true);
			return undefined;
		});
		button.addEventListener('blur', () => {
			if (stopRecording) cancel();
		});
		show();
		scope.add(settings.onChange(settingName, () => {
			if (!stopRecording) show();
		}));
		return labelledRow(id, label, button);
	}

	function createKeywordFilter(settings, scope, { settingName, inputId, label, chipClass, ariaVerb }) {
		const input = Dom.create('input', {
			id: inputId,
			className: 'phpro-text-input',
			attrs: { type: 'text', placeholder: 'Type word(s) and press Enter or , to add' },
		});
		const chipList = Dom.create('div', { className: 'phpro-chip-list' });

		const createChip = word => {
			const remove = Dom.create('span', {
				className: 'phpro-chip-remove',
				text: '×',
				attrs: { role: 'button', tabindex: '0', 'aria-label': `Remove ${ariaVerb} word ${word}` },
			});
			Dom.onActivate(remove, event => {
				event.stopPropagation();
				settings.set(settingName, settings.get(settingName).filter(existing => existing !== word));
			});
			return Dom.create('div', {
				className: `phpro-chip ${chipClass}`,
				children: [Dom.create('span', { className: 'phpro-chip-text', text: word }), remove],
			});
		};

		const render = () => chipList.replaceChildren(...settings.get(settingName).map(createChip));
		render();
		scope.add(settings.onChange(settingName, render));

		const commit = () => {
			const typed = parseWordList(input.value);
			if (typed.length === 0) {
				input.value = '';
				return;
			}
			const merged = [...new Set([...settings.get(settingName), ...typed])];
			// Keeps the stored list small enough to live in a cookie.
			if (Codecs.wordList.encode(merged).length > CONFIG.LIMITS.FILTER_WORDS_MAX_LENGTH) {
				input.setCustomValidity('The word list is full. Remove a word first.');
				input.reportValidity();
				return;
			}
			input.value = '';
			settings.set(settingName, merged);
		};
		input.addEventListener('input', () => input.setCustomValidity(''));
		input.addEventListener('keydown', event => {
			if (event.key !== 'Enter' && event.key !== ',') return;
			event.preventDefault();
			commit();
		});
		input.addEventListener('blur', commit);

		return Dom.create('div', {
			className: 'phpro-field',
			children: [
				Dom.create('label', { className: 'phpro-field-label', text: label, attrs: { for: inputId } }),
				input,
				chipList,
			],
		});
	}

	/** Two-thumb slider over fixed minute stops. The outer stops mean "no bound". */
	function createDurationRange(settings, scope) {
		const stops = CONFIG.UI.DURATION_STOPS_MIN;
		const lastIndex = stops.length - 1;

		const createThumb = label =>
			Dom.create('div', {
				className: 'phpro-duration-slider-thumb',
				attrs: {
					role: 'slider',
					tabindex: '0',
					'aria-label': label,
					'aria-valuemin': String(stops[0]),
					'aria-valuemax': String(stops[lastIndex]),
				},
			});
		const thumbs = { min: createThumb('Minimum duration'), max: createThumb('Maximum duration') };
		const range = Dom.create('div', { className: 'phpro-duration-slider-range' });
		const slider = Dom.create('div', {
			className: 'phpro-duration-slider',
			attrs: { [NO_SWIPE_ATTRIBUTE]: '' },
			children: [Dom.create('div', { className: 'phpro-duration-slider-track' }), range, thumbs.min, thumbs.max],
		});
		const labels = Dom.create('div', {
			className: 'phpro-duration-slider-labels',
			children: stops.map((stop, index) => Dom.create('span', { text: index === lastIndex ? `${stop}+` : String(stop) })),
		});

		const indexes = { min: 0, max: lastIndex };
		const nearestIndex = minutes =>
			stops.reduce((best, stop, index) => (Math.abs(stop - minutes) < Math.abs(stops[best] - minutes) ? index : best), 0);

		const render = () => {
			const percent = index => (index / lastIndex) * 100;
			thumbs.min.style.left = `${percent(indexes.min)}%`;
			thumbs.max.style.left = `${percent(indexes.max)}%`;
			range.style.left = `${percent(indexes.min)}%`;
			range.style.width = `${percent(indexes.max) - percent(indexes.min)}%`;
			thumbs.min.setAttribute('aria-valuenow', String(stops[indexes.min]));
			thumbs.max.setAttribute('aria-valuenow', String(stops[indexes.max]));
		};

		const readFromSettings = () => {
			const min = settings.get('minDuration');
			const max = settings.get('maxDuration');
			indexes.max = max === null ? lastIndex : nearestIndex(max);
			indexes.min = Math.min(min === null ? 0 : nearestIndex(min), indexes.max);
			render();
		};

		const moveThumb = (which, index) => {
			if (which === 'min') indexes.min = clamp(index, 0, indexes.max);
			else indexes.max = clamp(index, indexes.min, lastIndex);
			render();
		};

		const commit = () => {
			// Both values are computed first: each set() can trigger readFromSettings().
			const min = indexes.min === 0 ? null : stops[indexes.min];
			const max = indexes.max === lastIndex ? null : stops[indexes.max];
			settings.set('minDuration', min);
			settings.set('maxDuration', max);
		};

		const indexFromClientX = clientX => {
			const rect = slider.getBoundingClientRect();
			return Math.round(clamp((clientX - rect.left) / rect.width, 0, 1) * lastIndex);
		};

		for (const [which, thumb] of Object.entries(thumbs)) {
			let dragging = false;
			thumb.addEventListener('pointerdown', event => {
				event.preventDefault();
				dragging = true;
				thumb.setPointerCapture?.(event.pointerId);
			});
			thumb.addEventListener('pointermove', event => {
				if (dragging) moveThumb(which, indexFromClientX(event.clientX));
			});
			const endDrag = () => {
				if (!dragging) return;
				dragging = false;
				commit();
			};
			thumb.addEventListener('pointerup', endDrag);
			thumb.addEventListener('pointercancel', endDrag);
			thumb.addEventListener('keydown', event => {
				if (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight') return;
				event.preventDefault();
				moveThumb(which, indexes[which] + (event.key === 'ArrowLeft' ? -1 : 1));
				commit();
			});
		}

		readFromSettings();
		scope.add(settings.onChange('minDuration', readFromSettings));
		scope.add(settings.onChange('maxDuration', readFromSettings));

		return Dom.create('div', {
			className: 'phpro-field',
			children: [
				Dom.create('label', { className: 'phpro-field-label phpro-field-label--spaced', text: 'Duration in min:' }),
				Dom.create('div', { className: 'phpro-duration-slider-wrap', children: [slider, labels] }),
			],
		});
	}

	function setQuickMenuItem(settings, id, include) {
		const ids = settings.get('quickMenuItems').filter(existing => existing !== id);
		if (include) ids.push(id);
		settings.set('quickMenuItems', ids);
	}

	/** Checkboxes for what the quick menu shows. Items appear in the order they were picked. */
	function createQuickMenuChooser(settings, scope, quickActions) {
		const container = Dom.create('div', {
			children: [
				Dom.create('p', {
					className: 'phpro-chooser-intro',
					text: 'Pick what the ☰ Menu button shows. New picks go to the bottom.',
				}),
			],
		});
		const checkboxes = new Map();

		const addGroup = (title, items) => {
			container.append(Dom.create('div', { className: 'phpro-group-title', text: title }));
			for (const { id, label } of items) {
				const checkbox = Dom.create('input', { className: 'phpro-checkbox', attrs: { type: 'checkbox' } });
				checkbox.addEventListener('change', () => setQuickMenuItem(settings, id, checkbox.checked));
				checkboxes.set(id, checkbox);
				container.append(
					Dom.create('label', {
						className: 'phpro-checkbox-row',
						children: [Dom.create('span', { text: label }), checkbox],
					})
				);
			}
		};
		addGroup(
			'Buttons and dropdowns',
			[{ id: QUICK_MENU_SORT_SELECT_ID, label: 'Auto-sort dropdown' }, ...quickActions.map(({ id, label }) => ({ id, label }))]
		);
		addGroup(
			'Switches',
			QUICK_MENU_TOGGLES.map(name => ({ id: SETTINGS_SCHEMA[name].storageKey, label: TOGGLE_LABELS[name] }))
		);
		container.append(
			createActionButton({
				label: 'Restore the default picks',
				onClick: () => settings.set('quickMenuItems', [...DEFAULT_QUICK_MENU_ITEMS]),
			})
		);

		const render = () => {
			const selected = new Set(settings.get('quickMenuItems'));
			for (const [id, checkbox] of checkboxes) checkbox.checked = selected.has(id);
		};
		render();
		scope.add(settings.onChange('quickMenuItems', render));
		return container;
	}

	// ---- Panels ----------------------------------------------------------

	/** The slide-in quick menu opened by the ☰ Menu button, showing the items the user picked. */
	class QuickMenuPanel {
		constructor(settings, scope, { bus, quickActions, openSettings, onOpenChange }) {
			this._settings = settings;
			this._scope = scope;
			this._bus = bus;
			this._quickActions = quickActions;
			this._openSettings = openSettings;
			this._onOpenChange = onOpenChange;
			// Holds the subscriptions of the current items, dropped on every rebuild.
			this._itemScope = new DisposableScope();
			this._element = null;
			this._body = null;
			this._isOpen = false;
			this._autoscrollRunning = false;
		}

		get element() {
			return this._element;
		}

		get isOpen() {
			return this._isOpen;
		}

		contains(target) {
			return Boolean(this._element?.contains(target));
		}

		mount() {
			this._body = Dom.create('div');
			this._element = Dom.create('div', {
				id: UI_IDS.PANEL,
				className: `phpro-surface ${UI_CLASSES.OFFSCREEN}`,
				attrs: { role: 'dialog', 'aria-label': 'Quick menu' },
				children: [
					Dom.create('div', { className: 'phpro-category-header', text: 'Quick menu' }),
					this._body,
					createActionButton({ label: 'All settings', onClick: () => this._openSettings(), modifiers: ['phpro-btn--primary'] }),
					createActionButton({ label: 'Close menu', onClick: () => this.close() }),
				],
			});
			this._element.hidden = true;
			// Appended to <html> rather than <body> so it survives the site replacing <body>.
			document.documentElement.append(this._element);

			this._render();
			this._scope.add(this._settings.onChange('quickMenuItems', () => this._render()));
			// Kept outside the item scope: autoscroll can start or stop while the menu is rebuilt.
			this._scope.add(
				this._bus.on('autoscroll:state', ({ isRunning }) => {
					this._autoscrollRunning = isRunning;
					this._renderAutoscrollButton();
				})
			);
		}

		/**
		 * Slides in from the right edge when `onRight`, from the left otherwise.
		 * The ☰ Menu button uses the menuOnRight setting; a swipe passes the edge
		 * it started at.
		 */
		open({ onRight = this._settings.get('menuOnRight') } = {}) {
			if (this._isOpen) return;
			const panel = this._element;
			// Render off-screen first, then slide in two frames later; without the
			// paint in between the browser skips the transition.
			panel.style.transition = 'none';
			panel.classList.toggle(UI_CLASSES.ON_RIGHT, onRight);
			panel.classList.add(UI_CLASSES.OFFSCREEN);
			panel.hidden = false;
			requestAnimationFrame(() =>
				requestAnimationFrame(() => {
					panel.style.transition = '';
					panel.classList.remove(UI_CLASSES.OFFSCREEN);
				})
			);
			this._isOpen = true;
			this._onOpenChange(true);
		}

		close() {
			if (!this._isOpen) return;
			this._element.classList.add(UI_CLASSES.OFFSCREEN);
			this._isOpen = false;
			setTimeout(() => {
				// A quick re-open during the slide-out must not be hidden again.
				if (!this._isOpen) this._element.hidden = true;
			}, CONFIG.TIMING.PANEL_SLIDE_MS + CONFIG.TIMING.PANEL_HIDE_GRACE_MS);
			this._onOpenChange(false);
		}

		toggle() {
			if (this._isOpen) this.close();
			else this.open();
		}

		/** Which edge the menu is on, or last slid out to. */
		get isOnRight() {
			return this._element.classList.contains(UI_CLASSES.ON_RIGHT);
		}

		_render() {
			this._itemScope.dispose();
			this._autoscrollButton = null;
			const items = this._settings
				.get('quickMenuItems')
				.map(id => this._createItem(id))
				.filter(Boolean);
			if (items.length === 0) {
				items.push(
					Dom.create('p', {
						className: 'phpro-quick-empty',
						text: 'Nothing picked yet. Choose what shows here under All settings, Quick menu.',
					})
				);
			}
			this._body.replaceChildren(...items);
		}

		// Returns null for ids that match nothing, such as items removed in a later version.
		_createItem(id) {
			if (id === QUICK_MENU_SORT_SELECT_ID) {
				return createSelect(this._settings, this._itemScope, {
					id: UI_IDS.QUICK_SORT_SELECT,
					label: SORT_SELECT_LABEL,
					settingName: 'sortMode',
					options: SORT_OPTIONS,
				});
			}
			const toggleName = toggleNameForQuickMenuId(id);
			if (toggleName) return createToggleSwitch(this._settings, this._itemScope, toggleName);
			const action = this._quickActions.find(candidate => candidate.id === id);
			if (!action) return null;
			const button = createActionButton({ label: action.label, onClick: action.run });
			if (id === QUICK_ACTION_IDS.AUTOSCROLL) {
				this._autoscrollButton = button;
				this._renderAutoscrollButton();
			}
			return button;
		}

		_renderAutoscrollButton() {
			const button = this._autoscrollButton;
			if (!button) return;
			button.textContent = this._autoscrollRunning ? 'Stop autoscroll' : 'Start autoscroll';
			button.classList.toggle(UI_CLASSES.BUTTON_RUNNING, this._autoscrollRunning);
		}
	}

	/** Every setting, in a window with one tab per area. Built once; tabs only switch visibility. */
	class SettingsWindow {
		constructor(settings, scope, { quickActions }) {
			this._settings = settings;
			this._scope = scope;
			this._quickActions = quickActions;
			this._overlay = null;
			this._tabs = [];
		}

		get isOpen() {
			return Boolean(this._overlay && !this._overlay.hidden);
		}

		contains(target) {
			return Boolean(this._overlay?.contains(target));
		}

		mount() {
			const close = Dom.create('button', {
				className: 'phpro-settings-close',
				text: '×',
				attrs: { type: 'button', 'aria-label': 'Close settings' },
			});
			close.addEventListener('click', () => this.close());
			const tabStrip = Dom.create('div', { className: 'phpro-tabs', attrs: { role: 'tablist' } });
			const panels = SETTINGS_TABS.map((tab, index) => {
				const button = Dom.create('button', {
					className: 'phpro-tab',
					text: tab.title,
					attrs: { type: 'button', role: 'tab', id: `phpro-tab-${index}` },
				});
				const panel = Dom.create('div', {
					className: 'phpro-tab-panel',
					attrs: { role: 'tabpanel', 'aria-labelledby': `phpro-tab-${index}` },
					children: tab.groups.map(group => this._buildGroup(group)),
				});
				button.addEventListener('click', () => this._selectTab(tab.title));
				tabStrip.append(button);
				this._tabs.push({ title: tab.title, button, panel });
				return panel;
			});

			this._overlay = Dom.create('div', {
				id: UI_IDS.SETTINGS,
				className: 'phpro-surface',
				children: [
					Dom.create('div', {
						className: 'phpro-settings-window',
						attrs: { role: 'dialog', 'aria-label': 'Settings' },
						children: [
							Dom.create('div', {
								className: 'phpro-settings-header',
								children: [Dom.create('span', { text: 'Settings' }), close],
							}),
							tabStrip,
							...panels,
						],
					}),
				],
			});
			this._overlay.addEventListener('pointerdown', event => {
				if (event.target === this._overlay) this.close();
			});
			this._overlay.hidden = true;
			this._selectTab(SETTINGS_TABS[0].title);
			document.documentElement.append(this._overlay);
		}

		/** Opens the window, on `tabTitle` when given, otherwise on the tab last shown. */
		open(tabTitle) {
			if (tabTitle) this._selectTab(tabTitle);
			this._overlay.hidden = false;
		}

		close() {
			if (this._overlay) this._overlay.hidden = true;
		}

		_selectTab(title) {
			for (const tab of this._tabs) {
				const selected = tab.title === title;
				tab.button.setAttribute('aria-selected', String(selected));
				tab.panel.hidden = !selected;
			}
		}

		_buildGroup({ title, rows, showIf }) {
			const group = Dom.create('div', { className: 'phpro-group' });
			if (title) group.append(Dom.create('div', { className: 'phpro-group-title', text: title }));
			for (const row of rows) group.append(this._buildRow(row));
			this._showOnlyIf(group, showIf);
			return group;
		}

		_buildRow(row) {
			if (typeof row === 'string') return createToggleSwitch(this._settings, this._scope, row, { switchSide: 'right' });
			const element = Dom.create('div', { children: [this._createWidget(row.widget)] });
			this._showOnlyIf(element, row.showIf);
			return element;
		}

		/** Hides `element` unless at least one of the named settings is on, following their changes. */
		_showOnlyIf(element, names) {
			if (!names) return;
			const render = () => {
				element.hidden = !names.some(name => this._settings.get(name));
			};
			render();
			for (const name of names) this._scope.add(this._settings.onChange(name, render));
		}

		_createWidget(name) {
			switch (name) {
				case 'sortSelect':
					return createSelect(this._settings, this._scope, {
						id: UI_IDS.SORT_SELECT,
						label: SORT_SELECT_LABEL,
						settingName: 'sortMode',
						options: SORT_OPTIONS,
					});
				case 'durationRange':
					return createDurationRange(this._settings, this._scope);
				case 'keywordFilters': {
					const fragment = document.createDocumentFragment();
					for (const filter of KEYWORD_FILTERS) fragment.append(createKeywordFilter(this._settings, this._scope, filter));
					return fragment;
				}
				case 'queueThumbSide':
					return createSelect(this._settings, this._scope, {
						id: 'phq-thumb-side-select',
						label: 'Queue button:',
						settingName: 'queueThumbSide',
						options: THUMB_SIDE_OPTIONS,
					});
				case 'queueMediaSessionInterval': {
					const { MIN, MAX } = QUEUE.MEDIA_SESSION_INTERVAL_S;
					return createNumberField(this._settings, this._scope, {
						id: 'phq-media-session-interval',
						label: 'Re-check every (seconds):',
						settingName: 'queueMediaSessionInterval',
						min: MIN,
						max: MAX,
					});
				}
				case 'queueShortcutKeys':
					return this._createShortcutFields();
				case 'quickMenuChooser':
					return createQuickMenuChooser(this._settings, this._scope, this._quickActions);
				default:
					throw new Error(`Unknown settings widget "${name}"`);
			}
		}

		_createShortcutFields() {
			const fragment = document.createDocumentFragment();
			for (const settingName of SHORTCUT_SETTINGS) {
				fragment.append(
					createShortcutField(this._settings, this._scope, {
						id: `phq-${settingName}`,
						label: SHORTCUT_LABELS[settingName],
						settingName,
						otherSettings: SHORTCUT_SETTINGS.filter(other => other !== settingName),
					})
				);
			}
			return fragment;
		}
	}

	/** The draggable "☰ Menu" button that opens the quick menu. */
	class MenuButton {
		constructor(settings, scope, { onActivate, isPanelOpen }) {
			this._settings = settings;
			this._scope = scope;
			this._onActivate = onActivate;
			this._isPanelOpen = isPanelOpen;
			this._element = null;
			this._fadeTimer = null;
		}

		get element() {
			return this._element;
		}

		contains(target) {
			return Boolean(this._element?.contains(target));
		}

		mount() {
			const margin = CONFIG.UI.MENU_BUTTON_EDGE_MARGIN_PX;
			this._element = Dom.create('div', {
				id: UI_IDS.MENU_BUTTON,
				text: '☰ Menu',
				attrs: { role: 'button', tabindex: '0', 'aria-label': 'Open Pornhub Pro-ish settings' },
			});
			Dom.onActivate(this._element, () => this._onActivate());
			makeDraggable({
				element: this._element,
				thresholds: { mouse: CONFIG.UI.DRAG_THRESHOLD_MOUSE_PX, touch: CONFIG.UI.DRAG_THRESHOLD_TOUCH_PX },
				margin,
				onDragEnd: () => this._snapAndSave(),
			});
			this._element.addEventListener('pointerenter', () => this.cancelFade());
			this._element.addEventListener('pointerleave', () => this.scheduleFade());
			document.documentElement.append(this._element);

			// Re-applied after layout and fonts settle, since both change the button's size.
			this._restorePosition(false);
			requestAnimationFrame(() => this._restorePosition(false));
			window.addEventListener('load', () => this._restorePosition(false), { once: true });
			window.addEventListener(
				'resize',
				debounce(() => this._restorePosition(true), CONFIG.TIMING.RESIZE_DEBOUNCE_MS)
			);
			this._scope.add(
				this._settings.onChange('menuButtonPosition', ({ source }) => {
					if (source === ChangeSource.SYNC) this._restorePosition(true);
				})
			);
			this._scope.add(this._settings.onChange('swipeToOpen', () => this.scheduleFade()));
			this.scheduleFade();
		}

		/** In swipe-to-open mode the button fades out of the way after a while. */
		scheduleFade() {
			this.cancelFade();
			if (!this._settings.get('swipeToOpen')) return;
			this._fadeTimer = setTimeout(() => {
				if (!this._isPanelOpen()) this._element?.classList.add(UI_CLASSES.FADED);
			}, CONFIG.TIMING.MENU_BUTTON_FADE_DELAY_MS);
		}

		cancelFade() {
			clearTimeout(this._fadeTimer);
			this._fadeTimer = null;
			this._element?.classList.remove(UI_CLASSES.FADED);
		}

		_restorePosition(animate) {
			const button = this._element;
			const margin = CONFIG.UI.MENU_BUTTON_EDGE_MARGIN_PX;
			const anchor = this._settings.get('menuButtonPosition');
			const position = anchor
				? EdgeAnchor.toPosition(anchor, button.offsetWidth, button.offsetHeight, margin)
				: { left: margin, top: margin };
			button.classList.toggle(UI_CLASSES.ANIMATE_POSITION, animate);
			placeAt(button, position);
		}

		_snapAndSave() {
			const button = this._element;
			const rect = button.getBoundingClientRect();
			const margin = CONFIG.UI.MENU_BUTTON_EDGE_MARGIN_PX;
			const snap = CONFIG.UI.MENU_BUTTON_SNAP_MARGIN_PX;
			const maxLeft = window.innerWidth - rect.width - margin;
			const maxTop = window.innerHeight - rect.height - margin;
			let { left, top } = rect;
			if (left < snap) left = margin;
			else if (left > maxLeft - snap + margin) left = maxLeft;
			if (top < snap) top = margin;
			else if (top > maxTop - snap + margin) top = maxTop;

			button.classList.remove(UI_CLASSES.ANIMATE_POSITION);
			placeAt(button, { left, top });
			this._settings.set('menuButtonPosition', EdgeAnchor.fromRect(button.getBoundingClientRect()));
		}
	}

	/** Edge swipe to open the panel and swipe back to close it, on touch screens. */
	class SwipeGestures {
		constructor(settings, panel) {
			this._settings = settings;
			this._panel = panel;
		}

		install() {
			let start = null;
			document.addEventListener(
				'touchstart',
				event => {
					const touch = event.touches[0];
					start = touch ? { x: touch.clientX, y: touch.clientY } : null;
				},
				{ passive: true }
			);
			document.addEventListener(
				'touchend',
				event => {
					const touch = event.changedTouches[0];
					if (!start || !touch) return;
					const origin = start;
					start = null;
					const dx = touch.clientX - origin.x;
					const dy = touch.clientY - origin.y;
					if (Math.abs(dx) < CONFIG.UI.SWIPE_MIN_PX || Math.abs(dy) > Math.abs(dx)) return;
					if (event.target.closest?.(`[${NO_SWIPE_ATTRIBUTE}]`)) return;
					this._onHorizontalSwipe(origin.x, dx, event.target);
				},
				{ passive: true }
			);
		}

		/**
		 * A swipe in from either edge opens the menu from that edge; a swipe on the
		 * open menu back toward its edge closes it.
		 */
		_onHorizontalSwipe(originX, dx, target) {
			// In fullscreen the edges belong to the player and the queue panel.
			if (Dom.fullscreenElement(document)) return;
			if (this._panel.isOpen) {
				const towardMenuEdge = this._panel.isOnRight ? dx > 0 : dx < 0;
				if (this._panel.contains(target) && towardMenuEdge) this._panel.close();
				return;
			}
			if (!this._settings.get('swipeToOpen')) return;
			const edge = CONFIG.UI.SWIPE_EDGE_PX;
			if (originX <= edge && dx > 0) this._panel.open({ onRight: false });
			else if (originX >= window.innerWidth - edge && dx < 0) this._panel.open({ onRight: true });
		}
	}

	function createQuickActions(actions) {
		return [
			{ id: QUICK_ACTION_IDS.SORT_DURATION, label: 'Sort by duration manually', run: () => actions.sortNow('duration') },
			{ id: QUICK_ACTION_IDS.SORT_VIEWS, label: 'Sort by views manually', run: () => actions.sortNow('views') },
			{ id: QUICK_ACTION_IDS.SORT_AWARD, label: 'Put award first manually', run: () => actions.sortNow('award') },
			{ id: QUICK_ACTION_IDS.AUTOSCROLL, label: 'Start/stop autoscroll', run: actions.toggleAutoscroll },
			{ id: QUICK_ACTION_IDS.SCROLL_TOP, label: 'Scroll to top of the page', run: actions.scrollToTop },
			{ id: QUICK_ACTION_IDS.PLAY_QUEUE, label: 'Play queue', run: actions.playQueue },
		];
	}

	/**
	 * Owns the menu button, the quick menu and the settings window, and the
	 * interactions between them. Talks to the rest of the script only through
	 * Settings, the bus and `actions`.
	 */
	class MenuUI {
		constructor(settings, bus, actions) {
			this._settings = settings;
			this._scope = new DisposableScope();
			const quickActions = createQuickActions(actions);

			this._settingsWindow = new SettingsWindow(settings, this._scope, { quickActions });
			this._quickMenu = new QuickMenuPanel(settings, this._scope, {
				bus,
				quickActions,
				openSettings: () => this.openSettings(),
				onOpenChange: open => (open ? this._button.cancelFade() : this._button.scheduleFade()),
			});
			this._button = new MenuButton(settings, this._scope, {
				onActivate: () => this._quickMenu.toggle(),
				isPanelOpen: () => this._quickMenu.isOpen,
			});
		}

		mount() {
			Dom.addStyle(UI_STYLES, UI_IDS.STYLES);
			this._quickMenu.mount();
			this._settingsWindow.mount();
			this._button.mount();
			this._bindAppearance();
			this._bindDismissal();
			new SwipeGestures(this._settings, this._quickMenu).install();
		}

		/** Opens the settings window, on `tabTitle` when given (the queue panel opens it on Queue). */
		openSettings(tabTitle) {
			this._quickMenu.close();
			this._settingsWindow.open(tabTitle);
		}

		_bindAppearance() {
			const applyTransparency = () => {
				const transparent = this._settings.get('transparency');
				this._quickMenu.element.classList.toggle(UI_CLASSES.TRANSPARENT, transparent);
				this._button.element.classList.toggle(UI_CLASSES.TRANSPARENT, transparent);
			};
			applyTransparency();
			this._scope.add(this._settings.onChange('transparency', applyTransparency));
		}

		_bindDismissal() {
			document.addEventListener('pointerdown', event => {
				if (!this._quickMenu.isOpen) return;
				const target = event.target;
				if (this._quickMenu.contains(target) || this._button.contains(target) || this._settingsWindow.contains(target)) return;
				this._quickMenu.close();
			});
			// One press closes one layer: the settings window first, then the quick menu.
			document.addEventListener('keydown', event => {
				if (event.key !== 'Escape') return;
				if (this._settingsWindow.isOpen) this._settingsWindow.close();
				else this._quickMenu.close();
			});
		}
	}

	// ---- Playlist editing ---------------------------------------------

	const PLAYLIST_LIST_VIEW_CLASS = 'phpro-playlist-list-view';
	const PLAYLIST_REMOVE_CLASS = 'phpro-playlist-remove';
	const PLAYLIST_REMOVE_ICON_SIZE_PX = 16;
	const LIST_THUMB = Object.freeze({ WIDTH_PX: 160, HEIGHT_PX: 90 });
	const PLAYLIST_ROW = `${SELECTORS.PLAYLIST_EDIT_LIST} > ${SELECTORS.PLAYLIST_VIDEO_ITEM}`;

	// Each sort's labels for descending, then ascending. Pressing the active
	// sort again flips it.
	const PLAYLIST_SORTS = [
		{ key: 'views', labels: ['Most viewed', 'Least viewed'] },
		{ key: 'duration', labels: ['Longest', 'Shortest'] },
		{ key: 'newest', labels: ['Newest upload', 'Oldest upload'] },
	];

	// The site's own button classes, so the tools match its Clear buttons.
	const SITE_BUTTON_CLASSES = ['buttonBase', 'greyButton', 'light'];
	const SITE_ACTIVE_BUTTON_CLASS = 'orangeButton';

	const PLAYLIST_EDIT_STYLES = `
		.phpro-playlist-tools { display: none; flex-wrap: wrap; align-items: center; gap: 8px; margin: 10px 0 14px; }
		html.${PLAYLIST_EDITING_CLASS} .phpro-playlist-tools { display: flex; }
		.phpro-playlist-tools-label { color: #ccc; font: bold 13px Arial, sans-serif; margin-right: 2px; }
		.phpro-playlist-tools-gap { flex: 1 1 auto; }
		.phpro-playlist-tools-hint { flex-basis: 100%; color: #999; font: 12px Arial, sans-serif; }

		/* The site's remove button is a bare square with an X. */
		.remove-from-playlist-icon button.${PLAYLIST_REMOVE_CLASS} {
			width: 32px !important; height: 32px !important; padding: 0 !important; border: none !important;
			border-radius: 50% !important; background: rgba(0,0,0,0.78) !important; color: white !important;
			display: flex !important; align-items: center; justify-content: center; cursor: pointer;
			box-shadow: 0 2px 6px rgba(0,0,0,0.5); transition: background-color 0.15s;
		}
		.remove-from-playlist-icon button.${PLAYLIST_REMOVE_CLASS}:hover { background: #e53935 !important; }

		/* List view: one row per video while editing. The site lays the list out as a
		   grid of cards, so the list itself becomes a single column, and the thumbnail
		   gets a fixed box instead of the card styles it normally fills. */
		html.${PLAYLIST_EDITING_CLASS}.${PLAYLIST_LIST_VIEW_CLASS} ${SELECTORS.PLAYLIST_EDIT_LIST} {
			display: flex !important; flex-direction: column !important; gap: 6px; width: 100% !important;
			grid-template-columns: none !important;
		}
		html.${PLAYLIST_EDITING_CLASS}.${PLAYLIST_LIST_VIEW_CLASS} ${SELECTORS.PLAYLIST_EDIT_LIST} > li {
			width: 100% !important; max-width: none !important; height: auto !important; min-height: 0 !important;
			float: none !important; margin: 0 !important; grid-column: 1 / -1;
		}
		html.${PLAYLIST_EDITING_CLASS}.${PLAYLIST_LIST_VIEW_CLASS} ${PLAYLIST_ROW} .wrap {
			display: flex !important; align-items: center; gap: 14px; width: auto !important; height: auto !important;
			min-height: 0 !important; padding: 6px 10px 6px 6px !important; box-sizing: border-box;
			border-radius: 8px; background-color: rgba(255,255,255,0.05);
		}
		html.${PLAYLIST_EDITING_CLASS}.${PLAYLIST_LIST_VIEW_CLASS} ${PLAYLIST_ROW} .phimage {
			flex: 0 0 ${LIST_THUMB.WIDTH_PX}px; width: ${LIST_THUMB.WIDTH_PX}px !important; height: ${LIST_THUMB.HEIGHT_PX}px !important;
			margin: 0 !important; padding: 0 !important; position: relative !important; overflow: hidden;
			border-radius: 6px; order: 1;
		}
		html.${PLAYLIST_EDITING_CLASS}.${PLAYLIST_LIST_VIEW_CLASS} ${PLAYLIST_ROW} .phimage > a {
			display: block !important; position: absolute !important; inset: 0 !important;
			width: 100% !important; height: 100% !important; padding: 0 !important; margin: 0 !important;
		}
		html.${PLAYLIST_EDITING_CLASS}.${PLAYLIST_LIST_VIEW_CLASS} ${PLAYLIST_ROW} .phimage img {
			position: absolute !important; inset: 0 !important; width: 100% !important; height: 100% !important;
			object-fit: cover; opacity: 1 !important; visibility: visible !important; transform: none !important;
		}
		html.${PLAYLIST_EDITING_CLASS}.${PLAYLIST_LIST_VIEW_CLASS} ${PLAYLIST_ROW} .thumbnail-info-wrapper {
			flex: 1 1 auto; min-width: 0; width: auto !important; height: auto !important; margin: 0 !important; order: 2;
		}
		html.${PLAYLIST_EDITING_CLASS}.${PLAYLIST_LIST_VIEW_CLASS} ${PLAYLIST_ROW} .title {
			white-space: normal !important; word-break: normal !important; overflow-wrap: anywhere;
		}
		html.${PLAYLIST_EDITING_CLASS}.${PLAYLIST_LIST_VIEW_CLASS} ${PLAYLIST_ROW} .remove-from-playlist-icon {
			position: static !important; order: 3; flex: none; margin: 0 !important;
		}
	`;

	/**
	 * While a playlist is being edited: sort buttons and a list view switch
	 * above the videos, and round trash buttons in place of the site's X boxes.
	 * Sorting only reorders the list; the site's Save keeps it.
	 */
	class PlaylistEditTools {
		constructor(settings, bus, { sort, restoreOrder }) {
			this._settings = settings;
			this._bus = bus;
			this._sort = sort;
			this._restoreOrder = restoreOrder;
			this._active = null;
			this._buttons = new Map();
		}

		mount() {
			const list = Site.editablePlaylist();
			if (!list) return;
			Dom.addStyle(PLAYLIST_EDIT_STYLES, 'phpro-playlist-edit-style');
			list.before(this._createToolbar());
			// The site rebuilds the remove buttons inside each card when editing
			// starts, so changes anywhere in the list are watched, not only new cards.
			const decorateSoon = coalesceToMicrotask(() => this._decorateRemoveButtons(list));
			new MutationObserver(decorateSoon).observe(list, { childList: true, subtree: true });
			this._decorateRemoveButtons(list);
			this._applyListView();
			this._settings.onChange('playlistListView', () => this._applyListView());
			this._bus.on('playlist:editing', ({ isEditing }) => {
				if (!isEditing) return;
				this._setActive(null);
				this._decorateRemoveButtons(list);
			});
		}

		_createToolbar() {
			const sortButtons = PLAYLIST_SORTS.map(sort => {
				const button = this._createButton(sort.labels[0], () => this._onSort(sort));
				this._buttons.set(sort.key, { button, sort });
				return button;
			});
			const original = this._createButton('Original order', () => {
				this._restoreOrder();
				this._setActive(null);
			});
			this._viewButton = this._createButton('', () => this._settings.toggle('playlistListView'));
			return Dom.create('div', {
				className: 'phpro-playlist-tools',
				children: [
					Dom.create('span', { className: 'phpro-playlist-tools-label', text: 'Sort:' }),
					...sortButtons,
					original,
					Dom.create('span', { className: 'phpro-playlist-tools-gap' }),
					this._viewButton,
					Dom.create('span', {
						className: 'phpro-playlist-tools-hint',
						text: 'Press Save to keep the new order.',
					}),
				],
			});
		}

		_createButton(label, onClick) {
			const button = Dom.create('button', { className: SITE_BUTTON_CLASSES.join(' '), text: label, attrs: { type: 'button' } });
			button.addEventListener('click', event => {
				// The site's own handlers on this part of the page are not meant for these buttons.
				event.stopPropagation();
				onClick();
			});
			return button;
		}

		_onSort(sort) {
			const descending = this._active?.key === sort.key ? !this._active.descending : true;
			this._sort(sort.key, descending);
			this._setActive({ key: sort.key, descending });
		}

		/** Highlights the sort in use and labels it with its direction; null clears it. */
		_setActive(active) {
			this._active = active;
			for (const [key, { button, sort }] of this._buttons) {
				const isActive = active?.key === key;
				button.textContent = isActive && !active.descending ? sort.labels[1] : sort.labels[0];
				button.classList.toggle(SITE_ACTIVE_BUTTON_CLASS, isActive);
				button.classList.toggle('greyButton', !isActive);
				button.setAttribute('aria-pressed', String(isActive));
			}
		}

		_applyListView() {
			const listView = this._settings.get('playlistListView');
			document.documentElement.classList.toggle(PLAYLIST_LIST_VIEW_CLASS, listView);
			this._viewButton.textContent = listView ? 'Card view' : 'List view';
		}

		/**
		 * Checks for the glyph rather than for a marker class: the site may put its
		 * X back into a button this already changed.
		 */
		_decorateRemoveButtons(list) {
			const glyphSelector = `.${SELECTORS.SITE_ICONS.DELETE}`;
			for (const button of Site.playlistRemoveButtons(list)) {
				if (button.classList.contains(PLAYLIST_REMOVE_CLASS) && button.querySelector(glyphSelector)) continue;
				button.classList.add(PLAYLIST_REMOVE_CLASS);
				button.setAttribute('aria-label', button.title || 'Remove from playlist');
				button.replaceChildren(Dom.iconFont(SELECTORS.SITE_ICONS.DELETE, PLAYLIST_REMOVE_ICON_SIZE_PX));
			}
		}
	}

	// =====================================================================
	// 5b. Queue UI
	//
	// The queue lives in the video player: a Queue button in the player's
	// controls opens a panel that slides out of the video's right edge, and
	// previous and next buttons sit either side of the player's play button.
	// Reads and acts on the queue only through the QueueController, and hears
	// about changes only through the bus.
	// =====================================================================

	const QUEUE_UI_STYLE_ID = 'phq-ui-style';
	// On <html> while the queue is switched off. Hiding beats tearing down: the
	// queue can be switched back on without a reload.
	const QUEUE_DISABLED_CLASS = 'phq-disabled';

	// The site player's own glyphs, copied from its control bar: next and play
	// as it draws them, previous as its next mirrored.
	const SITE_PLAYER_GLYPHS = {
		previous: { viewBox: '0 0 100 100', path: 'M20 50 100 100V0zM0 0h12.5v100H0z' },
		next: { viewBox: '0 0 100 100', path: 'm80 50-80 50v-100zm20-50h-12.5v100h12.5z' },
		play: { viewBox: '0 0 87.5 100', path: 'm0 0v100l87.5-50z' },
	};

	function sitePlayerGlyphSvg(name, sizePx, color) {
		const { viewBox, path } = SITE_PLAYER_GLYPHS[name];
		return `<svg width="${sizePx}" height="${sizePx}" viewBox="${viewBox}" fill="${color}" aria-hidden="true"><path d="${path}"/></svg>`;
	}

	// Thumbnail button glyphs on the queue icon's 24 px grid, with its 2.6 round
	// stroke, each centred on (12, 12) so every state sits in the middle of the
	// round button.
	const THUMB_GLYPH_PATHS = {
		check:
			'<path d="M5.5 12.25 9.8 16.55 18.5 7.45" stroke="currentColor" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round"/>',
		remove:
			'<g transform="translate(0 -0.5)" stroke="currentColor" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round">' +
			'<path d="M4.5 7.5h15M10 4.8h4"/>' +
			'<path d="M6.8 7.5l.9 11a1.8 1.8 0 0 0 1.8 1.7h5a1.8 1.8 0 0 0 1.8-1.7l.9-11"/></g>',
		next:
			'<g transform="translate(-0.45 0)" fill="currentColor" stroke="currentColor" stroke-linejoin="round">' +
			'<path d="M5 7.5 11 12 5 16.5z" stroke-width="1.2"/><path d="M11 7.5 17 12 11 16.5z" stroke-width="1.2"/>' +
			'<path d="M19.2 7v10" stroke-width="2.6" stroke-linecap="round"/></g>',
	};
	const THUMB_GLYPH_SIZE_PX = 20;
	// The queue icon's three lines outweigh its triangle, so centred by its
	// outline it still looks left-heavy in the round button. About 2 px at 20 px.
	const THUMB_ADD_OPTICAL_SHIFT = 2.4;

	/**
	 * A thumbnail button glyph, THUMB_GLYPH_SIZE_PX square. Adding uses the
	 * queue icon, as every "add to queue" control does. The trash can is drawn
	 * here rather than taken from the site's icon font, whose own styling
	 * overrides the button's colour.
	 */
	function thumbGlyph(name) {
		if (name === 'add') {
			return Dom.svg(queueIconSvg(THUMB_GLYPH_SIZE_PX, 'currentColor', { opticalShiftX: THUMB_ADD_OPTICAL_SHIFT }));
		}
		return Dom.svg(
			`<svg viewBox="0 0 24 24" width="${THUMB_GLYPH_SIZE_PX}" height="${THUMB_GLYPH_SIZE_PX}" fill="none" aria-hidden="true">${THUMB_GLYPH_PATHS[name]}</svg>`
		);
	}

	// The three confirmations share the check, told apart by the button's colour.
	const THUMB_STATES = {
		idle: { tip: 'Add to queue (right-click: play next)', tone: 'add', glyph: 'add' },
		added: { tip: 'Added!', tone: 'add', glyph: 'check' },
		queued: { tip: 'In the queue, click to remove', tone: 'remove', glyph: 'remove' },
		removed: { tip: 'Removed from the queue', tone: 'remove', glyph: 'check' },
		next: { tip: 'Playing next!', tone: 'next', glyph: 'check' },
	};


	// On the panel's edge layer while it shows as a sheet over the page.
	const QUEUE_SHEET_CLASS = 'phq-edge--sheet';
	const QUEUE_SHEET_MAX_HEIGHT_VH = 75;

	// Clicks inside these never count as "clicked away" for the panel.
	const QUEUE_UI_SELECTOR = `#phq-panel, .phq-modal-overlay, [${PLAYER_BUTTON_ATTRIBUTE}="queue-panel"]`;

	const PANEL_CLOSE_ICON_SIZE_PX = 14;
	const CURRENT_BUTTON_ICON_SIZE_PX = 14;
	const QUEUE_ROW_DELETE_ICON_SIZE_PX = 16;

	// Player-bar icons, white like the player's own. The queue icon is original to
	// this script; previous and next are the player's own glyphs.
	const PLAYER_ICON_SIZE_PX = 22;
	// The shift centres the drawing's outline (lines and triangle with their
	// strokes) on the 24 px box, which the plain coordinates leave low and left.
	const QUEUE_ICON_CENTRE_SHIFT = Object.freeze({ X: 0.25, Y: -0.55 });
	/**
	 * `cropUnits` trims that much off every side of the 24 px drawing area. The
	 * player sizes its control icons itself and its own glyphs fill their area
	 * edge to edge, so the queue icon needs its margin gone to look as large.
	 */
	const queueIconSvg = (sizePx, color, { opticalShiftX = 0, cropUnits = 0 } = {}) => `
		<svg width="${sizePx}" height="${sizePx}" viewBox="${cropUnits} ${cropUnits} ${24 - 2 * cropUnits} ${24 - 2 * cropUnits}" fill="none" aria-hidden="true">
			<g transform="translate(${QUEUE_ICON_CENTRE_SHIFT.X + opticalShiftX} ${QUEUE_ICON_CENTRE_SHIFT.Y})">
				<path d="M3 6h14M3 12h9M3 18h9" stroke="${color}" stroke-width="2.6" stroke-linecap="round"/>
				<path d="M15 12.2v7.6l6.2-3.8z" fill="${color}" stroke="${color}" stroke-width="1.2" stroke-linejoin="round"/>
			</g>
		</svg>`;
	const PLAYER_QUEUE_ICON_CROP_UNITS = 2;
	const PLAYER_QUEUE_SVG = queueIconSvg(PLAYER_ICON_SIZE_PX, '#ffffff', { cropUnits: PLAYER_QUEUE_ICON_CROP_UNITS });
	// Matches the size the player draws its own play and next glyphs at.
	const PLAYER_GLYPH_SIZE_PX = 18;

	const MOBILE_TRANSPORT = Object.freeze({ BUTTON_PX: 56, ICON_PX: 26, GAP_PX: 12 });

	const PLAYER_BUTTON_KEYS = Object.freeze({
		PANEL: 'queue-panel',
		PREVIOUS: 'queue-previous',
		STOP: 'queue-stop',
		NEXT: 'queue-next',
	});

	// The player has no stop glyph of its own; a filled square in the style of its
	// play glyph, with a margin so it weighs about the same as the triangle.
	const PLAYER_STOP_SVG = `<svg width="${PLAYER_GLYPH_SIZE_PX}" height="${PLAYER_GLYPH_SIZE_PX}" viewBox="-12 -12 124 124" fill="#ffffff" aria-hidden="true"><rect width="100" height="100" rx="8"/></svg>`;
	const DISABLED_PLAYER_BUTTON_OPACITY = '0.35';

	const QUEUE_UI_STYLES = `
		/* Off the icon's corner. The font comes from the player's controls, as its time display's does. */
		[data-phq-badge] {
			position: absolute; top: -5px; right: -7px; min-width: 18px; height: 18px; padding: 0 4px;
			box-sizing: border-box; border-radius: 9px; background-color: orange; color: black;
			font-family: inherit; font-size: 12px; font-weight: bold; line-height: 18px;
			text-align: center; pointer-events: none;
		}
		[data-phq-badge][hidden] { display: none; }
		.phq-surface [hidden] { display: none !important; }
		html.${QUEUE_DISABLED_CLASS} :is(.phq-edge, #phq-status, #phq-thumb-btn, #phq-play-pill, [data-phq-menu-item]) {
			display: none !important;
		}
		html.${PLAYLIST_EDITING_CLASS} :is(#phq-thumb-btn, #phq-play-pill) { display: none !important; }
		/* Phone player: previous, stop and next sit beside the big play button, bare like it is. */
		:is(${SELECTORS.MOBILE_PLAYER}) ${SELECTORS.MOBILE_MIDDLE_CONTROLS}:has(> [${PLAYER_BUTTON_ATTRIBUTE}]) {
			display: flex !important; align-items: center; justify-content: center; gap: ${MOBILE_TRANSPORT.GAP_PX}px;
		}
		:is(${SELECTORS.MOBILE_PLAYER}) ${SELECTORS.MOBILE_MIDDLE_CONTROLS}:has(> [${PLAYER_BUTTON_ATTRIBUTE}]) > * {
			position: relative !important; inset: auto !important; transform: none !important; margin: 0 !important;
		}
		:is(${SELECTORS.MOBILE_PLAYER}) ${SELECTORS.MOBILE_MIDDLE_CONTROLS} > [${PLAYER_BUTTON_ATTRIBUTE}] {
			width: ${MOBILE_TRANSPORT.BUTTON_PX}px !important; height: ${MOBILE_TRANSPORT.BUTTON_PX}px !important;
			display: flex; align-items: center; justify-content: center;
		}
		:is(${SELECTORS.MOBILE_PLAYER}) ${SELECTORS.MOBILE_MIDDLE_CONTROLS} > [${PLAYER_BUTTON_ATTRIBUTE}] svg {
			width: ${MOBILE_TRANSPORT.ICON_PX}px !important; height: ${MOBILE_TRANSPORT.ICON_PX}px !important;
		}
		/* Phones: the panel as a sheet from the bottom of the screen, over a dimmed page. */
		.phq-edge.${QUEUE_SHEET_CLASS} {
			position: fixed; inset: 0; z-index: 999999990; transition: background-color 0.28s;
		}
		.phq-edge.${QUEUE_SHEET_CLASS}:has(#phq-panel.phq-panel--open) {
			background-color: rgba(0,0,0,0.55); pointer-events: auto;
		}
		.phq-edge.${QUEUE_SHEET_CLASS} #phq-panel,
		.phq-edge.${QUEUE_SHEET_CLASS} #phq-panel.phq-panel--left {
			top: auto; right: 0; bottom: 0; left: 0; width: 100%; max-height: ${QUEUE_SHEET_MAX_HEIGHT_VH}vh;
			border: none; border-top: 1px solid orange; border-radius: 14px 14px 0 0;
			padding-bottom: env(safe-area-inset-bottom); box-shadow: 0 -8px 25px rgba(0,0,0,0.6);
			transform: translateY(100%);
		}
		.phq-edge.${QUEUE_SHEET_CLASS} #phq-panel.phq-panel--open { transform: translateY(0); }
		/* Without hover it would pop up on taps; the three-dot menu adds to the queue there. */
		@media (hover: none) { #phq-thumb-btn { display: none !important; } }

		/* Panel: slides out of the right edge of the video. The edge layer clips it
		   to the video's box and lets clicks through everywhere else. */
		.phq-edge { position: absolute; inset: 0; overflow: hidden; pointer-events: none; z-index: 1000; }
		#phq-panel {
			position: absolute; top: 0; right: 0; bottom: 0; width: min(340px, 70%); display: flex; flex-direction: column;
			box-sizing: border-box; background-color: rgba(0,0,0,0.92); border-left: 1px solid orange;
			box-shadow: -8px 0 25px rgba(0,0,0,0.6); color: white; font: 13px Arial, sans-serif;
			transform: translateX(100%); pointer-events: none; transition: transform 0.28s cubic-bezier(.32,.72,0,1);
		}
		#phq-panel.phq-panel--open { transform: translateX(0); pointer-events: auto; }
		#phq-panel.phq-panel--left {
			right: auto; left: 0; border-left: none; border-right: 1px solid orange;
			box-shadow: 8px 0 25px rgba(0,0,0,0.6); transform: translateX(-100%);
		}
		#phq-panel.phq-panel--left.phq-panel--open { transform: translateX(0); }
		#phq-panel .phq-panel-header {
			display: flex; justify-content: space-between; align-items: center; padding: 8px 10px;
			border-bottom: 1px solid rgba(255,255,255,0.1); flex-shrink: 0;
		}
		#phq-panel .phq-panel-title {
			justify-self: start; display: inline-flex; align-items: center; gap: 6px; padding: 2px 4px; border: none;
			border-radius: 4px; background: none; color: orange; cursor: pointer; font: bold 13px Arial, sans-serif;
			text-transform: uppercase; letter-spacing: 0.05em;
		}
		#phq-panel .phq-panel-title:hover { background-color: rgba(255,165,0,0.15); }
		#phq-panel .phq-close-btn {
			justify-self: end; width: 24px; height: 24px; padding: 0; border: none; border-radius: 50%; background: none;
			color: white; cursor: pointer; display: flex; align-items: center; justify-content: center;
		}
		#phq-panel .phq-close-btn:hover { color: orange; }
		#phq-panel .phq-current {
			flex-shrink: 0; margin: 8px 10px 0; padding: 7px 10px; border: 1px solid orange; border-radius: 9999px;
			background-color: black; color: orange; cursor: pointer; font: bold 12px Arial, sans-serif;
			display: flex; align-items: center; justify-content: center; gap: 6px;
		}
		#phq-panel .phq-current:hover { background-color: #7a3b00; }
		#phq-panel .phq-current--confirm, #phq-panel .phq-current--confirm:hover { background-color: orange; color: black; }
		#phq-panel .phq-note { flex-shrink: 0; padding: 8px 12px 0; color: #9ecbff; font-size: 12px; }
		#phq-panel .phq-section-label {
			font-size: 10px; font-weight: bold; letter-spacing: 0.1em; text-transform: uppercase; color: #999;
		}
		#phq-panel .phq-now-playing {
			flex-shrink: 0; padding: 10px 12px; border-bottom: 1px solid rgba(255,255,255,0.1);
			background-color: rgba(255,165,0,0.06);
		}
		#phq-panel .phq-now-playing-title {
			margin-top: 6px; display: flex; align-items: center; gap: 8px; font-weight: bold; overflow: hidden;
			white-space: nowrap;
		}
		#phq-panel .phq-now-playing-text { overflow: hidden; text-overflow: ellipsis; }
		#phq-panel .phq-bars { display: inline-flex; align-items: flex-end; gap: 2px; height: 14px; flex-shrink: 0; }
		#phq-panel .phq-bars span { display: block; width: 3px; border-radius: 2px; background-color: orange; animation: phq-bar 0.9s ease-in-out infinite alternate; }
		#phq-panel .phq-bars span:nth-child(1) { height: 5px; }
		#phq-panel .phq-bars span:nth-child(2) { height: 11px; animation-delay: 0.18s; }
		#phq-panel .phq-bars span:nth-child(3) { height: 7px; animation-delay: 0.36s; }
		#phq-panel .phq-bars span:nth-child(4) { height: 13px; animation-delay: 0.09s; }
		@keyframes phq-bar { from { opacity: 0.45; transform: scaleY(0.35); } to { opacity: 1; transform: scaleY(1); } }
		#phq-panel .phq-up-next { flex-shrink: 0; display: flex; align-items: center; gap: 8px; padding: 9px 12px 3px; }
		#phq-panel .phq-queue-actions { margin-left: auto; display: flex; gap: 8px; }
		#phq-panel .phq-mini-btn {
			padding: 3px 10px; border: 1px solid rgba(255,255,255,0.25); border-radius: 9999px; background: none;
			color: #ddd; cursor: pointer; font: 12px Arial, sans-serif;
		}
		#phq-panel .phq-mini-btn:hover { border-color: orange; color: orange; }
		#phq-panel .phq-mini-btn--danger:hover { border-color: #ff6b6b; color: #ff6b6b; }
		#phq-panel .phq-list { flex: 1; min-height: 0; overflow-y: auto; padding: 4px 0 8px; scrollbar-color: orange transparent; scrollbar-width: thin; }
		#phq-panel .phq-item {
			position: relative; display: flex; align-items: center; gap: 6px; margin: 2px 6px; padding: 7px 10px 7px 6px;
			border-radius: 8px;
		}
		#phq-panel .phq-item:hover { background-color: rgba(255,255,255,0.07); }
		#phq-panel .phq-item:focus-visible { outline: 2px solid orange; outline-offset: -2px; }
		#phq-panel .phq-item--dragging { opacity: 0.35; }
		#phq-panel .phq-item--drop-above::before, #phq-panel .phq-item--drop-below::after {
			content: ''; position: absolute; left: 6px; right: 6px; height: 2px; border-radius: 2px;
			background-color: orange; pointer-events: none;
		}
		#phq-panel .phq-item--drop-above::before { top: -1px; }
		#phq-panel .phq-item--drop-below::after { bottom: -1px; }
		#phq-panel .phq-item-handle { flex-shrink: 0; padding: 0 2px; color: #777; cursor: grab; user-select: none; }
		#phq-panel .phq-item-title {
			flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: #ddd; cursor: grab;
			user-select: none;
		}
		#phq-panel .phq-item-remove {
			flex-shrink: 0; display: inline-flex; padding: 0 2px; border: none; background: none; color: #777;
			cursor: pointer; line-height: 0;
		}
		#phq-panel .phq-item-remove:hover { color: #ff6b6b; }
		#phq-panel .phq-item-handle { touch-action: none; }
		/* Fingers: bigger grips and buttons to grab, and room between rows. */
		@media (pointer: coarse) {
			#phq-panel .phq-item { padding: 4px 4px 4px 0; }
			#phq-panel .phq-item-handle { padding: 12px 14px; font-size: 18px; }
			#phq-panel .phq-item-title { padding: 8px 0; }
			#phq-panel .phq-item-remove { padding: 12px 14px; }
			#phq-panel .phq-mini-btn { padding: 8px 16px; }
			#phq-panel .phq-close-btn { width: 40px; height: 40px; }
		}
		#phq-panel .phq-empty { padding: 24px 16px; text-align: center; color: #999; }

		/* Status pill */
		#phq-status {
			position: fixed; left: 20px; bottom: ${QUEUE.STATUS_PILL_BOTTOM_PX}px; padding: 6px 14px; border-radius: 9999px;
			border: 1px solid orange; background-color: rgba(0,0,0,0.88); color: white; font: bold 12px Arial, sans-serif;
			pointer-events: none; opacity: 0; z-index: 999999992; transition: opacity 0.35s;
		}
		#phq-status.phq-status--visible { opacity: 1; }

		/* Confirm dialog */
		.phq-modal-overlay {
			position: fixed; inset: 0; z-index: 999999995; display: flex; align-items: center; justify-content: center;
			background-color: rgba(0,0,0,0.55);
		}
		.phq-modal {
			width: min(380px, 92vw); padding: 16px; display: flex; flex-direction: column; gap: 12px;
			background-color: black; border: 1px solid orange; border-radius: 10px; color: white;
			font: 13px Arial, sans-serif; box-shadow: 0 8px 25px rgba(0,0,0,0.8);
		}
		.phq-modal-title { color: orange; font-weight: bold; text-transform: uppercase; }
		.phq-modal-actions { display: flex; justify-content: flex-end; gap: 8px; }
		.phq-modal-btn {
			padding: 7px 12px; border: 1px solid white; border-radius: 10px; background-color: black; color: white;
			cursor: pointer; font: bold 13px Arial, sans-serif;
		}
		.phq-modal-btn:hover { color: orange; border-color: orange; }
		.phq-modal-btn--danger { background-color: #c62828; border-color: #c62828; }
		.phq-modal-btn--danger:hover { color: white; border-color: white; }

		/* Thumbnail button */
		#phq-thumb-btn {
			--phq-tone: 255,152,0; position: fixed; top: 0; left: 0; z-index: 999999989;
			width: ${QUEUE.THUMB_BUTTON.SIZE_PX}px; height: ${QUEUE.THUMB_BUTTON.SIZE_PX}px; padding: 0;
			display: flex; align-items: center; justify-content: center; border-radius: 50%;
			border: 2px solid rgba(var(--phq-tone),0.7); color: rgb(var(--phq-tone)); cursor: pointer;
			background: linear-gradient(rgba(var(--phq-tone),0.15), rgba(var(--phq-tone),0.15)), rgba(0,0,0,0.9);
			box-shadow: 0 2px 8px rgba(0,0,0,0.5); opacity: 0; pointer-events: none; transform: translateY(-4px);
			transition: opacity 0.25s ease, transform 0.25s ease, color 0.2s ease, border-color 0.2s ease, background 0.2s ease;
		}
		#phq-thumb-btn[data-tone="remove"] { --phq-tone: 229,57,53; }
		#phq-thumb-btn[data-tone="next"] { --phq-tone: 30,136,229; }
		#phq-thumb-btn.phq-thumb-btn--visible { opacity: 1; pointer-events: auto; transform: translateY(0); }
		@keyframes phq-glyph-pop {
			from { opacity: 0; transform: scale(0.4) rotate(-30deg); }
			70% { opacity: 1; transform: scale(1.12) rotate(0deg); }
			to { transform: scale(1); }
		}
		#phq-thumb-btn > .phq-glyph-pop { animation: phq-glyph-pop 0.28s ease-out; }
		@media (prefers-reduced-motion: reduce) { #phq-thumb-btn > .phq-glyph-pop { animation: none; } }
		/* Every glyph in the same square box, so none sits on a text baseline. */
		#phq-thumb-btn > * { display: block; width: ${THUMB_GLYPH_SIZE_PX}px; height: ${THUMB_GLYPH_SIZE_PX}px; }

		/* Items added to the site's three-dot menu take its own link styling. */
		[data-phq-menu-item] { cursor: pointer; }
		[data-phq-menu-item] .icon { display: inline-flex; vertical-align: middle; }

		/* Play pill */
		#phq-play-pill {
			position: fixed; right: ${QUEUE.PLAY_PILL_EDGE_PX}px; bottom: ${QUEUE.STATUS_PILL_BOTTOM_PX}px; z-index: 999999991;
			display: flex; align-items: center; gap: 2px; padding: 4px; border: 2px solid orange; border-radius: 9999px;
			background-color: rgba(0,0,0,0.9); box-shadow: 0 4px 15px rgba(0,0,0,0.6); font: 13px Arial, sans-serif;
		}
		#phq-play-pill[hidden],
		html:has(.${QUEUE_SHEET_CLASS} #phq-panel.phq-panel--open) #phq-play-pill { display: none; }
		.phq-play-pill-start {
			display: flex; align-items: center; gap: 8px; padding: 0 8px 0 0; border: none; background: none;
			color: white; font: inherit; cursor: pointer;
		}
		.phq-play-pill-start:hover { color: orange; }
		.phq-play-pill-icon {
			width: 26px; height: 26px; border-radius: 50%; background-color: orange; color: black;
			display: flex; align-items: center; justify-content: center;
		}
		/* A triangle's visual centre sits left of its box's centre. */
		.phq-play-pill-icon svg { margin-left: 2px; }
		.phq-play-pill-count { color: orange; font-weight: bold; }
		.phq-play-pill-dismiss {
			display: flex; padding: 4px; border: none; border-radius: 50%; background: none; color: #999; cursor: pointer;
		}
		.phq-play-pill-dismiss:hover { color: white; }
	`;

	/** A short message in the corner of the page. STATUS_MS.STICKY keeps it until the next one. */
	class QueueStatusPill {
		constructor() {
			this._element = null;
			this._timer = null;
		}

		mount() {
			this._element = Dom.create('div', { id: 'phq-status', attrs: { role: 'status' } });
			document.documentElement.append(this._element);
		}

		show(text, durationMs = STATUS_MS.NORMAL) {
			this._element.textContent = text;
			this._element.classList.add('phq-status--visible');
			clearTimeout(this._timer);
			if (Number.isFinite(durationMs)) {
				this._timer = setTimeout(() => this._element.classList.remove('phq-status--visible'), durationMs);
			}
		}
	}

	/** A small confirm dialog. `buttons` are { label, danger, onClick }. */
	function askQueueQuestion({ title, text, buttons }) {
		const overlay = Dom.create('div', { className: 'phq-modal-overlay phq-surface' });
		const close = () => overlay.remove();
		overlay.addEventListener('pointerdown', event => {
			if (event.target === overlay) close();
		});
		overlay.addEventListener('keydown', event => {
			if (event.key === 'Escape') close();
		});
		const actions = buttons.map(({ label, danger, onClick }) => {
			const button = Dom.create('button', {
				className: danger ? 'phq-modal-btn phq-modal-btn--danger' : 'phq-modal-btn',
				text: label,
				attrs: { type: 'button' },
			});
			button.addEventListener('click', () => {
				onClick?.();
				close();
			});
			return button;
		});
		overlay.append(
			Dom.create('div', {
				className: 'phq-modal',
				attrs: { role: 'alertdialog', 'aria-label': title },
				children: [
					Dom.create('div', { className: 'phq-modal-title', text: title }),
					Dom.create('div', { text }),
					Dom.create('div', { className: 'phq-modal-actions', children: actions }),
				],
			})
		);
		document.documentElement.append(overlay);
		actions[0]?.focus();
	}

	/**
	 * The queue list, sliding out of the right edge of the video: add this
	 * video, Now playing, Shuffle, Clear and reordering.
	 */
	class QueuePanel {
		constructor(settings, queue, { openSettings, status }) {
			this._settings = settings;
			this._queue = queue;
			this._openSettings = openSettings;
			this._status = status;
			this._open = false;
			this._autocloseTimer = null;
			this._dragFrom = null;
			this._confirmation = null;
			this._confirmationTimer = null;
			this._side = 'right';
		}

		get isOpen() {
			return this._open;
		}

		mount() {
			const gearIcon = Dom.create('span');
			gearIcon.innerHTML = GEAR_ICON_SVG;
			const settingsButton = Dom.create('button', {
				className: 'phq-panel-title',
				attrs: { type: 'button', title: 'Open settings' },
				children: [gearIcon, Dom.create('span', { text: 'Queue' })],
			});
			settingsButton.addEventListener('click', event => {
				event.stopPropagation();
				this.toggle(false);
				this._openSettings();
			});
			const close = Dom.create('button', {
				className: 'phq-close-btn',
				attrs: { type: 'button', 'aria-label': 'Close', title: 'Close' },
				children: [Dom.iconFont(SELECTORS.SITE_ICONS.CLOSE, PANEL_CLOSE_ICON_SIZE_PX)],
			});
			close.addEventListener('click', () => this.toggle(false));

			this._currentButton = Dom.create('button', { className: 'phq-current', attrs: { type: 'button' } });
			this._currentButton.addEventListener('click', () => this.toggleCurrent());
			this._currentButton.addEventListener('contextmenu', event => {
				event.preventDefault();
				this._playCurrentNext();
			});
			this._elsewhereNote = Dom.create('div', {
				className: 'phq-note',
				text: 'The queue is playing in another tab. Playing it here moves it to this tab.',
			});

			this._nowPlayingText = Dom.create('span', { className: 'phq-now-playing-text' });
			const bars = Dom.create('span', { className: 'phq-bars', children: [1, 2, 3, 4].map(() => Dom.create('span')) });
			this._nowPlaying = Dom.create('div', {
				className: 'phq-now-playing',
				children: [
					Dom.create('div', { className: 'phq-section-label', text: 'Now playing' }),
					Dom.create('div', { className: 'phq-now-playing-title', children: [bars, this._nowPlayingText] }),
				],
			});

			const miniButton = (label, tip, extraClass, onClick) => {
				const button = Dom.create('button', {
					className: `phq-mini-btn ${extraClass}`.trim(),
					text: label,
					attrs: { type: 'button', title: tip },
				});
				button.addEventListener('click', onClick);
				return button;
			};
			this._upNext = Dom.create('div', {
				className: 'phq-up-next',
				children: [
					Dom.create('span', { className: 'phq-section-label', text: 'Up next' }),
					Dom.create('span', {
						className: 'phq-queue-actions',
						children: [
							miniButton('Shuffle', 'Shuffle the videos waiting', '', () => this._onShuffle()),
							miniButton('Clear', 'Remove every video waiting', 'phq-mini-btn--danger', () => this._onClear()),
						],
					}),
				],
			});

			this._list = Dom.create('div', { className: 'phq-list' });
			this._element = Dom.create('div', {
				id: 'phq-panel',
				className: 'phq-surface',
				attrs: { role: 'dialog', 'aria-label': 'Queue' },
				children: [
					Dom.create('div', { className: 'phq-panel-header', children: [settingsButton, close] }),
					this._currentButton,
					this._elsewhereNote,
					this._nowPlaying,
					this._upNext,
					this._list,
				],
			});
			this._element.addEventListener('pointerenter', () => clearTimeout(this._autocloseTimer));
			this._element.addEventListener('pointerleave', event => {
				// A finger "leaves" every time it lifts, which would close the panel
				// a few seconds after each tap on a touch screen.
				if (event.pointerType !== 'mouse') return;
				clearTimeout(this._autocloseTimer);
				this._autocloseTimer = setTimeout(() => {
					if (this._open) this.toggle(false);
				}, QUEUE_TIMING.PANEL_AUTOCLOSE_MS);
			});
			// In fullscreen the panel sits inside the player's own element, whose
			// tap and swipe handlers would otherwise also act on touches in the list.
			for (const type of ['touchstart', 'touchmove', 'touchend', 'click', 'dblclick']) {
				this._element.addEventListener(type, event => event.stopPropagation());
			}
			this._edge = Dom.create('div', { className: 'phq-edge', children: [this._element] });
		}

		/** True while the panel is a sheet from the bottom of the screen, as on phones. */
		get isSheet() {
			return this._edge.classList.contains(QUEUE_SHEET_CLASS);
		}

		/** Which edge of the video the panel slides out of: 'left' or 'right'. */
		get side() {
			return this._side;
		}

		contains(target) {
			return Boolean(target && this._element.contains(target));
		}

		/** True while the panel can be seen in fullscreen: the fullscreen element holds it. */
		isShownInFullscreen() {
			const fullscreen = Dom.fullscreenElement(document);
			return Boolean(fullscreen && this._edge.isConnected && fullscreen.contains(this._edge));
		}

		/** Puts the panel on the right edge of `area`, or takes it away when there is no player. */
		/**
		 * Puts the panel on `area`, the player box, or with `asSheet` on the page
		 * itself as a sheet from the bottom of the screen: a phone's player is too
		 * small to hold the list.
		 */
		moveTo(area, { asSheet = false, host = document.documentElement } = {}) {
			this._edge.classList.toggle(QUEUE_SHEET_CLASS, asSheet);
			if (asSheet) {
				if (this._edge.parentElement !== host) host.append(this._edge);
				return;
			}
			if (!area) {
				if (this._open) this.toggle(false);
				this._edge.remove();
				return;
			}
			if (this._edge.parentElement === area) return;
			// The edge layer is positioned against the player box.
			if (area.ownerDocument.defaultView.getComputedStyle(area).position === 'static') area.style.position = 'relative';
			area.append(this._edge);
		}

		/**
		 * Opens, closes, or with no argument toggles the panel. `side` picks the
		 * edge it slides out of when it opens; it stays on the last side otherwise.
		 */
		toggle(force, side = this._side) {
			clearTimeout(this._autocloseTimer);
			const open = Boolean(force ?? !this._open) && this._edge.isConnected;
			if (open && !this._open && side !== this._side) this._moveToSide(side);
			this._open = open;
			this._element.classList.toggle('phq-panel--open', this._open);
			if (this._open) this.render(this._queue.snapshot());
		}

		// Switched without the slide, so the closed panel does not visibly travel
		// across the video to the other edge before sliding in.
		_moveToSide(side) {
			this._side = side;
			this._element.style.transition = 'none';
			this._element.classList.toggle('phq-panel--left', side === 'left');
			// Reading layout applies the closed position on the new side before the
			// transition comes back for the slide in.
			void this._element.offsetWidth;
			this._element.style.transition = '';
		}

		/** True when `rect` sits under the open panel, where the thumbnail button would cover it. */
		overlaps(rect) {
			if (!this._open) return false;
			const box = this._element.getBoundingClientRect();
			const pad = QUEUE.THUMB_BUTTON.AVOID_UI_PAD_PX;
			return rect.left < box.right + pad && rect.right > box.left - pad && rect.top < box.bottom + pad && rect.bottom > box.top - pad;
		}

		/** Adds this page's video, or removes it when it is already queued. */
		toggleCurrent() {
			const current = this._queue.currentVideo();
			if (!current) {
				this._status.show('Not a video page', STATUS_MS.SHORT);
				return;
			}
			if (this._queue.isQueued(current.viewkey)) {
				this._confirm(null);
				this._queue.removeViewkey(current.viewkey);
				this._status.show('Removed from the queue', STATUS_MS.SHORT);
			} else {
				this._confirm('Added to the queue');
				this._queue.add(current);
			}
		}

		render(snapshot) {
			// Only rebuilt while it can be seen.
			if (!this._open) return;
			const { queue, playingAnywhere, playingHere } = snapshot;
			this._renderCurrentButton(snapshot);
			this._elsewhereNote.hidden = !(playingAnywhere && !playingHere);
			const showNowPlaying = playingAnywhere && queue.length > 0;
			this._nowPlaying.hidden = !showNowPlaying;
			if (showNowPlaying) this._nowPlayingText.textContent = queue[0].title;
			const start = showNowPlaying ? 1 : 0;
			this._upNext.hidden = queue.length <= start;
			const waiting = queue.slice(start);
			this._list.replaceChildren(...waiting.map((item, offset) => this._row(item, offset + start, playingAnywhere)));
			if (waiting.length === 0 && !playingAnywhere) {
				this._list.append(
					Dom.create('div', { className: 'phq-empty', text: 'The queue is empty. Use the + on a thumbnail to add videos.' })
				);
			}
		}

		_renderCurrentButton({ queue, playingAnywhere, navigating }) {
			const button = this._currentButton;
			const current = this._queue.currentVideo();
			const queued = current ? this._queue.isQueued(current.viewkey) : false;
			const isPlayingVideo = playingAnywhere && queue[0]?.viewkey === current?.viewkey;
			// Mid-move the head already names the next video while the page still shows the old one.
			button.hidden = !current || (queued && isPlayingVideo) || navigating;
			if (button.hidden) return;
			button.classList.toggle('phq-current--confirm', Boolean(this._confirmation));
			if (this._confirmation) {
				button.textContent = this._confirmation;
			} else if (queued) {
				button.replaceChildren(
					Dom.iconFont(SELECTORS.SITE_ICONS.DELETE, CURRENT_BUTTON_ICON_SIZE_PX),
					' Remove this video from the queue'
				);
			} else {
				button.replaceChildren(
					Dom.svg(queueIconSvg(CURRENT_BUTTON_ICON_SIZE_PX, 'currentColor')),
					' Add this video to the queue'
				);
			}
			button.title = queued ? '' : 'Right-click to play it next';
		}

		_playCurrentNext() {
			const current = this._queue.currentVideo();
			if (!current) return;
			this._confirm('Playing next');
			this._queue.playNext(current);
		}

		/** Shows a confirmation on the add button for a moment, then its real state again. */
		_confirm(text) {
			this._confirmation = text;
			clearTimeout(this._confirmationTimer);
			if (!text) return;
			this._confirmationTimer = setTimeout(() => {
				this._confirmation = null;
				this.render(this._queue.snapshot());
			}, QUEUE_TIMING.CONFIRM_MS);
		}

		_onShuffle() {
			const shuffled = this._queue.shuffleWaiting();
			this._status.show(shuffled ? `Shuffled ${countOf(shuffled, 'video')}` : 'Nothing to shuffle', STATUS_MS.SHORT);
		}

		_onClear() {
			const count = this._queue.waitingCount();
			if (count === 0) {
				this._status.show('Nothing to clear', STATUS_MS.SHORT);
				return;
			}
			askQueueQuestion({
				title: 'Clear the queue',
				text: `Remove ${countOf(count, 'video')} from the queue?`,
				buttons: [
					{ label: 'Cancel' },
					{
						label: 'Clear',
						danger: true,
						onClick: () => {
							this._queue.clearWaiting();
							this._status.show(`Cleared ${countOf(count, 'video')}`, STATUS_MS.SHORT);
						},
					},
				],
			});
		}

		_row(item, index, live) {
			const playNext = event => {
				event.preventDefault();
				event.stopPropagation();
				if (index === (live ? 1 : 0)) {
					this._status.show('Already playing next', STATUS_MS.BRIEF);
					return;
				}
				const before = this._rowRects();
				this._queue.playNext(item);
				this._animateMove(before, item.viewkey);
				this._status.show('Moved to play next', STATUS_MS.BRIEF);
			};
			// draggable is armed on pointerdown and disarmed on release, so the row is
			// only draggable during an actual grab. The remove button never arms it,
			// or a slightly missed click would start a drag.
			const row = Dom.create('div', { className: 'phq-item' });
			// Touch reorders with its own drag (_wireTouchDrag); native dragging would fight the list's scrolling.
			const arm = event => {
				if (event.pointerType === 'mouse') row.draggable = true;
			};
			const handle = Dom.create('span', {
				className: 'phq-item-handle',
				text: '=',
				attrs: { title: 'Drag or Alt+Up/Down to reorder, right-click to play next' },
			});
			const title = Dom.create('span', { className: 'phq-item-title', text: item.title, attrs: { title: `Right-click to play next: ${item.title}` } });
			for (const part of [handle, title]) {
				part.addEventListener('pointerdown', arm);
				part.addEventListener('contextmenu', playNext);
			}
			const remove = Dom.create('button', {
				className: 'phq-item-remove',
				attrs: { type: 'button', 'aria-label': 'Remove from queue', title: 'Remove from queue' },
				children: [Dom.iconFont(SELECTORS.SITE_ICONS.DELETE, QUEUE_ROW_DELETE_ICON_SIZE_PX)],
			});
			remove.addEventListener('click', event => {
				event.stopPropagation();
				this._queue.removeItem(item.id);
			});
			row.append(handle, title, remove);
			row.dataset.queueIndex = String(index);
			row.dataset.viewkey = item.viewkey;
			row.tabIndex = 0;
			row.setAttribute('aria-label', `${item.title}. Alt+Up or Alt+Down to move, Delete to remove`);
			row.addEventListener('keydown', event => this._onRowKey(event, row, item, index));
			this._wireDrag(row, index);
			this._wireTouchDrag(row, handle, index);
			return row;
		}

		/**
		 * Up and Down move focus, Alt+Up and Alt+Down move the row, Delete removes
		 * it. Handled keys stop here so the site's player shortcuts do not see them.
		 */
		_onRowKey(event, row, item, index) {
			const step = { ArrowUp: -1, ArrowDown: 1 }[event.key];
			if (!step && event.key !== 'Delete') return;
			event.preventDefault();
			event.stopPropagation();
			if (!step) {
				const neighbour = row.nextElementSibling ?? row.previousElementSibling;
				this._queue.removeItem(item.id);
				this._focusRow(neighbour?.dataset.viewkey);
				return;
			}
			if (event.altKey) {
				// Never above the first listed row: the playing video sits above it.
				const firstListed = Number(this._list.firstElementChild?.dataset.queueIndex);
				const target = index + step;
				if (target < firstListed || target >= this._queue.snapshot().queue.length) return;
				this._queue.reorder(index, target);
				this._focusRow(item.viewkey);
				return;
			}
			(step < 0 ? row.previousElementSibling : row.nextElementSibling)?.focus();
		}

		_focusRow(viewkey) {
			if (!viewkey) return;
			[...this._list.children].find(row => row.dataset.viewkey === viewkey)?.focus();
		}

		/** Drag to reorder, with an edge line showing exactly where the drop lands. */
		_wireDrag(row, index) {
			const clearIndicators = () => {
				for (const other of this._list.querySelectorAll('.phq-item')) {
					other.classList.remove('phq-item--drop-above', 'phq-item--drop-below');
				}
			};
			const half = event => {
				const box = row.getBoundingClientRect();
				return event.clientY - box.top < box.height / 2 ? 'above' : 'below';
			};
			row.addEventListener('dragstart', event => {
				this._dragFrom = index;
				row.classList.add('phq-item--dragging');
				event.dataTransfer.effectAllowed = 'move';
			});
			row.addEventListener('dragend', () => {
				row.classList.remove('phq-item--dragging');
				row.draggable = false;
				clearIndicators();
			});
			row.addEventListener('pointerup', () => {
				row.draggable = false;
			});
			row.addEventListener('dragover', event => {
				event.preventDefault();
				event.dataTransfer.dropEffect = 'move';
				clearIndicators();
				row.classList.add(half(event) === 'above' ? 'phq-item--drop-above' : 'phq-item--drop-below');
			});
			row.addEventListener('drop', event => {
				event.preventDefault();
				clearIndicators();
				if (this._dragFrom === null) return;
				const from = this._dragFrom;
				this._dragFrom = null;
				this._dropAt(from, index, half(event));
			});
		}

		/** Moves the item at `from` to just above or below the row at `index`. */
		_dropAt(from, index, half) {
			let to = index + (half === 'below' ? 1 : 0);
			if (from < to) to--;
			if (from !== to) this._queue.reorder(from, to);
		}

		/**
		 * Reordering with a finger: hold the handle and drag. The list scrolls on
		 * its own while the finger is near its top or bottom edge.
		 */
		_wireTouchDrag(row, handle, index) {
			const { AUTOSCROLL_EDGE_PX, AUTOSCROLL_STEP_PX } = QUEUE.TOUCH_DRAG;
			let drag = null;
			const rows = () => [...this._list.querySelectorAll('.phq-item')];
			const clearIndicators = () => {
				for (const other of rows()) other.classList.remove('phq-item--drop-above', 'phq-item--drop-below');
			};
			const target = y => {
				for (const other of rows()) {
					const box = other.getBoundingClientRect();
					if (y < box.top || y > box.bottom) continue;
					return { row: other, half: y - box.top < box.height / 2 ? 'above' : 'below' };
				}
				return null;
			};
			const showTarget = () => {
				clearIndicators();
				const hit = target(drag.y);
				drag.hit = hit;
				hit?.row.classList.add(hit.half === 'above' ? 'phq-item--drop-above' : 'phq-item--drop-below');
			};
			const tick = () => {
				if (!drag) return;
				const box = this._list.getBoundingClientRect();
				if (drag.y < box.top + AUTOSCROLL_EDGE_PX) this._list.scrollTop -= AUTOSCROLL_STEP_PX;
				else if (drag.y > box.bottom - AUTOSCROLL_EDGE_PX) this._list.scrollTop += AUTOSCROLL_STEP_PX;
				showTarget();
				drag.frame = requestAnimationFrame(tick);
			};
			const finish = commit => {
				if (!drag) return;
				const { hit, frame, pointerId } = drag;
				drag = null;
				cancelAnimationFrame(frame);
				handle.releasePointerCapture?.(pointerId);
				row.classList.remove('phq-item--dragging');
				clearIndicators();
				if (commit && hit) this._dropAt(index, Number(hit.row.dataset.queueIndex), hit.half);
			};
			handle.addEventListener('pointerdown', event => {
				if (event.pointerType === 'mouse') return;
				event.preventDefault();
				drag = { pointerId: event.pointerId, y: event.clientY, hit: null, frame: 0 };
				handle.setPointerCapture?.(event.pointerId);
				row.classList.add('phq-item--dragging');
				drag.frame = requestAnimationFrame(tick);
			});
			handle.addEventListener('pointermove', event => {
				if (drag && event.pointerId === drag.pointerId) drag.y = event.clientY;
			});
			handle.addEventListener('pointerup', () => finish(true));
			handle.addEventListener('pointercancel', () => finish(false));
		}

		_rowRects() {
			const rects = new Map();
			for (const row of this._list.querySelectorAll('.phq-item')) rects.set(row.dataset.viewkey, row.getBoundingClientRect());
			return rects;
		}

		/** After a "play next": the chosen row flies to the top while the rows it passed slide down. */
		_animateMove(before, movedViewkey) {
			if (window.matchMedia?.('(prefers-reduced-motion: reduce)').matches) return;
			const { MOVED_MS, OTHERS_MS, EASING } = QUEUE.PLAY_NEXT_ANIMATION;
			for (const row of this._list.querySelectorAll('.phq-item')) {
				const old = before.get(row.dataset.viewkey);
				if (!old || typeof row.animate !== 'function') continue;
				const offset = old.top - row.getBoundingClientRect().top;
				if (!offset) continue;
				const moved = row.dataset.viewkey === movedViewkey;
				// The moved row passes over the others, so it is lifted above them.
				if (moved) Object.assign(row.style, { position: 'relative', zIndex: '2' });
				const animation = row.animate([{ transform: `translateY(${offset}px)` }, { transform: 'translateY(0)' }], {
					duration: moved ? MOVED_MS : OTHERS_MS,
					easing: EASING,
				});
				if (moved) {
					animation.onfinish = animation.oncancel = () => Object.assign(row.style, { position: '', zIndex: '' });
				}
			}
		}
	}

	/**
	 * One add-to-queue button for every thumbnail. It lives at the page's top
	 * level, above every stacking context, and moves onto whichever thumbnail
	 * the pointer is on, so the site's cards are never touched.
	 */
	class ThumbButton {
		constructor(settings, queue, { overlapsQueueUi }) {
			this._settings = settings;
			this._queue = queue;
			this._overlapsQueueUi = overlapsQueueUi;
			this._button = null;
			this._hover = null;
			this._hideTimer = null;
			this._confirmation = null;
			this._lastTarget = null;
		}

		mount() {
			this._button = Dom.create('button', { id: 'phq-thumb-btn', attrs: { type: 'button' } });
			this._button.addEventListener('click', event => this._onClick(event));
			this._button.addEventListener('contextmenu', event => this._onContextMenu(event));
			document.documentElement.append(this._button);
			// mousemove rather than mouseenter: when the page shifts under a resting
			// pointer, the browser sends mouseenter to whatever card now sits there,
			// popping the button up with nobody hovering. Only real motion sends mousemove.
			document.addEventListener('mousemove', event => this._onPointerMove(event.target), { capture: true, passive: true });
			// A null relatedTarget means the pointer left the window.
			document.addEventListener(
				'mouseout',
				event => {
					if (!event.relatedTarget) this._scheduleHide();
				},
				true
			);
			window.addEventListener('scroll', () => this.hide(), { capture: true, passive: true });
			window.addEventListener('resize', () => this.hide());
		}

		/** Redraws the button's state, for when the queue changed. */
		render() {
			const viewkey = this._viewkey();
			if (!viewkey) return;
			const state = THUMB_STATES[this._stateFor(viewkey)];
			this._button.dataset.tone = state.tone;
			const glyph = thumbGlyph(state.glyph);
			// A new glyph on the same card is the result of a click (or its
			// confirmation ending), so it pops in; moving to another card does not.
			const changedHere = this._shown?.viewkey === viewkey && this._shown.glyph !== state.glyph;
			if (changedHere) glyph.classList.add('phq-glyph-pop');
			this._shown = { viewkey, glyph: state.glyph };
			this._button.replaceChildren(glyph);
			this._button.title = state.tip;
			this._button.setAttribute('aria-label', state.tip);
		}

		hide() {
			this._cancelHide();
			this._hover = null;
			this._lastTarget = null;
			this._button?.classList.remove('phq-thumb-btn--visible');
		}

		_onPointerMove(target) {
			if (!this._settings.get('queueEnabled')) return;
			if (target === this._lastTarget) return;
			this._lastTarget = target;
			if (this._button.contains(target)) {
				this._cancelHide();
				return;
			}
			const hit = Site.cardAt(target);
			if (!hit) {
				this._scheduleHide();
				return;
			}
			if (hit.card === this._hover?.card) {
				this._cancelHide();
				return;
			}
			this._show(hit);
		}

		_show(hit) {
			this._cancelHide();
			this._hover = hit;
			this._place(hit.anchor);
			this.render();
			const overlaps = this._overlapsQueueUi(hit.card.getBoundingClientRect());
			this._button.classList.toggle('phq-thumb-btn--visible', !overlaps);
		}

		_place(anchor) {
			const box = Site.cardPictureRect(anchor);
			const { SIZE_PX, INSET_PX } = QUEUE.THUMB_BUTTON;
			const left = this._settings.get('queueThumbSide') === 'right' ? box.right - INSET_PX - SIZE_PX : box.left + INSET_PX;
			this._button.style.left = `${left}px`;
			this._button.style.top = `${box.top + INSET_PX}px`;
		}

		_scheduleHide() {
			if (!this._hover || this._hideTimer) return;
			this._hideTimer = setTimeout(() => this.hide(), QUEUE_TIMING.THUMB_HIDE_MS);
		}

		_cancelHide() {
			clearTimeout(this._hideTimer);
			this._hideTimer = null;
		}

		// Read each time: infinite scroll and sorting move cards around.
		_viewkey() {
			return this._hover ? Site.viewkeyOf(this._hover.anchor.getAttribute('href')) : null;
		}

		_stateFor(viewkey) {
			if (this._confirmation?.viewkey === viewkey) return this._confirmation.state;
			return this._queue.isQueued(viewkey) ? 'queued' : 'idle';
		}

		_confirm(viewkey, state) {
			clearTimeout(this._confirmation?.timer);
			this._confirmation = {
				viewkey,
				state,
				timer: setTimeout(() => {
					this._confirmation = null;
					this.render();
				}, QUEUE_TIMING.CONFIRM_MS),
			};
		}

		_onClick(event) {
			event.preventDefault();
			event.stopPropagation();
			const viewkey = this._viewkey();
			if (!viewkey) return;
			if (this._stateFor(viewkey) === 'queued') {
				this._confirm(viewkey, 'removed');
				this._queue.removeViewkey(viewkey);
				return;
			}
			const meta = Site.cardMeta(this._hover);
			this._confirm(viewkey, 'added');
			if (!this._queue.add(meta)) this.render();
		}

		/** Right-click queues the video right after whatever is playing. */
		_onContextMenu(event) {
			event.preventDefault();
			event.stopPropagation();
			const viewkey = this._viewkey();
			if (!viewkey) return;
			this._confirm(viewkey, 'next');
			this._queue.playNext(Site.cardMeta(this._hover));
		}
	}

	// Sized for the pill's 26 px orange circle and its height.
	const PLAY_PILL_GLYPH_SIZE_PX = 11;
	const PLAY_PILL_CLOSE_SIZE_PX = 12;

	/**
	 * "Play queue" in the corner of the page, shown only while videos are queued
	 * and no tab is playing them, so starting the queue never needs a watch page.
	 * Closing it hides it until the queue changes.
	 */
	class QueuePlayPill {
		constructor(settings, queue) {
			this._settings = settings;
			this._queue = queue;
			this._element = null;
			this._count = null;
			this._signature = '';
			this._recheckTimer = null;
		}

		mount() {
			this._count = Dom.create('span', { className: 'phq-play-pill-count' });
			const start = Dom.create('button', {
				className: 'phq-play-pill-start',
				attrs: { type: 'button' },
				children: [
					Dom.create('span', {
						className: 'phq-play-pill-icon',
						children: [Dom.svg(sitePlayerGlyphSvg('play', PLAY_PILL_GLYPH_SIZE_PX, 'currentColor'))],
					}),
					Dom.create('span', { text: 'Play queue' }),
					this._count,
				],
			});
			start.addEventListener('click', () => this._queue.start());
			const dismiss = Dom.create('button', {
				className: 'phq-play-pill-dismiss',
				attrs: { type: 'button', 'aria-label': 'Hide until the queue changes', title: 'Hide until the queue changes' },
				children: [Dom.iconFont(SELECTORS.SITE_ICONS.CLOSE, PLAY_PILL_CLOSE_SIZE_PX)],
			});
			dismiss.addEventListener('click', () => this._dismiss());
			this._element = Dom.create('div', { id: 'phq-play-pill', children: [start, dismiss] });
			this._element.hidden = true;
			document.documentElement.append(this._element);
		}

		render({ queue, playingAnywhere, movingUntil, navigating }) {
			if (!this._element) return;
			this._signature = queue.map(item => item.id).join(',');
			const dismissed = SafeSessionStorage.get(QUEUE.STORAGE.PLAY_PILL_DISMISSED) === this._signature;
			const movingOn = this._recheckWhenMoveEnds(movingUntil);
			this._element.hidden =
				!this._settings.get('queueEnabled') ||
				queue.length === 0 ||
				playingAnywhere ||
				movingOn ||
				navigating ||
				dismissed;
			this._count.textContent = String(queue.length);
			this._element.setAttribute('aria-label', `Play queue, ${queue.length} videos`);
		}

		/**
		 * Whether a tab is still on its way to the next video. If it never picks
		 * the queue back up (it was closed, say), nothing else would show the
		 * pill again, so it checks once more when the grace runs out.
		 */
		_recheckWhenMoveEnds(movingUntil) {
			clearTimeout(this._recheckTimer);
			const remainingMs = movingUntil - Date.now();
			if (remainingMs <= 0) return false;
			this._recheckTimer = setTimeout(() => this.render(this._queue.snapshot()), remainingMs);
			return true;
		}

		_dismiss() {
			SafeSessionStorage.set(QUEUE.STORAGE.PLAY_PILL_DISMISSED, this._signature);
			this._element.hidden = true;
		}
	}

	const MENU_ICON_SIZE_PX = 20;
	const MENU_ITEM_KEYS = Object.freeze({ ADD: 'add', PLAY_NEXT: 'play-next' });

	/**
	 * "Add to queue" and "Play next in queue" in the site's three-dot menu on
	 * video cards, above "Add to Watch Later". The site builds that menu on
	 * demand and may rebuild it, so new menus are watched for and filled in.
	 * On phones one drawer serves every video, so the add item is relabelled
	 * whenever the drawer's content changes, and the video is looked up on click.
	 *
	 * The items copy the site's link class for its styling only. They carry none
	 * of its data attributes, which the site's own click handling reads.
	 */
	class QueueMenuItems {
		constructor(settings, queue, { status }) {
			this._settings = settings;
			this._queue = queue;
			this._status = status;
			this._fillMenusSoon = coalesceToMicrotask(() => this._fillMenus());
			this._renderSoon = coalesceToMicrotask(() => this.render());
			this._watchedDrawers = new WeakSet();
		}

		mount() {
			new MutationObserver(this._fillMenusSoon).observe(document.documentElement, { childList: true, subtree: true });
			this._fillMenus();
		}

		/** Relabels the add item of every open menu, for when the queue changed. */
		render() {
			for (const menu of Site.actionMenus()) {
				const item = Dom.query(`[data-phq-menu-item="${MENU_ITEM_KEYS.ADD}"]`, menu);
				if (item) this._renderAddItem(item, menu);
			}
		}

		_fillMenus() {
			for (const menu of Site.actionMenus()) {
				if (Dom.query('[data-phq-menu-item]', menu)) continue;
				const watchLater = Site.actionMenuWatchLaterLink(menu);
				if (!watchLater) continue;
				const add = this._createItem(MENU_ITEM_KEYS.ADD, () => this._toggleQueued(menu));
				this._renderAddItem(add, menu);
				const playNext = this._createItem(MENU_ITEM_KEYS.PLAY_NEXT, () => this._playNext(menu));
				this._setItem(playNext, thumbGlyph('next'), 'Play next in queue');
				// The site separates its links with spaces, which its layout relies on.
				watchLater.before(add, ' ', playNext, ' ');
				this._watchDrawer(menu);
			}
		}

		/** A reused drawer switches videos by changing its preview, not by adding a menu. */
		_watchDrawer(menu) {
			const drawer = menu.closest(SELECTORS.ACTION_MENU_DRAWER);
			if (!drawer || this._watchedDrawers.has(drawer)) return;
			this._watchedDrawers.add(drawer);
			new MutationObserver(this._renderSoon).observe(drawer, {
				subtree: true,
				childList: true,
				characterData: true,
				attributes: true,
				attributeFilter: ['class', 'href'],
			});
		}

		_createItem(key, onClick) {
			const item = Dom.create('a', {
				className: SELECTORS.ACTION_MENU_LINK_CLASS,
				attrs: { 'data-phq-menu-item': key, role: 'button', tabindex: '0' },
			});
			Dom.onActivate(item, onClick);
			return item;
		}

		/**
		 * `icon` is a site icon-font class or a drawn glyph. A font class goes on
		 * the item's icon span itself, as the site's own items have it; wrapped in
		 * a second span it would take the site's icon spacing twice.
		 */
		_setItem(item, icon, label) {
			const iconSpan =
				typeof icon === 'string'
					? Dom.create('span', { className: `icon ${icon}` })
					: Dom.create('span', { className: 'icon', children: [icon] });
			item.replaceChildren(iconSpan, ' ', Dom.create('span', { className: 'label', text: label }));
		}

		/**
		 * Rebuilds the item only when its label changes: rebuilding is itself a
		 * change to a watched drawer, which would otherwise call this again.
		 */
		_renderAddItem(item, menu) {
			const viewkey = Site.actionMenuVideo(menu)?.viewkey;
			const queued = Boolean(viewkey && this._queue.isQueued(viewkey));
			const shown = queued ? 'remove' : 'add';
			if (item.dataset.phqShown === shown) return;
			item.dataset.phqShown = shown;
			if (queued) this._setItem(item, SELECTORS.SITE_ICONS.DELETE, 'Remove from queue');
			else this._setItem(item, Dom.svg(queueIconSvg(MENU_ICON_SIZE_PX, 'currentColor')), 'Add to queue');
		}

		_toggleQueued(menu) {
			const meta = Site.actionMenuVideo(menu);
			if (!meta) {
				this._status.show('Could not find this video', STATUS_MS.SHORT);
				return;
			}
			if (this._queue.isQueued(meta.viewkey)) {
				this._queue.removeViewkey(meta.viewkey);
				this._status.show('Removed from the queue', STATUS_MS.SHORT);
				return;
			}
			this._queue.add(meta);
			this._status.show('Added to the queue', STATUS_MS.SHORT);
		}

		_playNext(menu) {
			const meta = Site.actionMenuVideo(menu);
			if (!meta) {
				this._status.show('Could not find this video', STATUS_MS.SHORT);
				return;
			}
			this._queue.playNext(meta);
			this._status.show('Playing next', STATUS_MS.SHORT);
		}
	}

	/**
	 * In fullscreen on a touch screen: a swipe in from the left or right edge
	 * opens the queue panel from that edge, a swipe back towards it closes it,
	 * and a tap elsewhere on the video closes it too.
	 *
	 * The player has swipe and tap controls of its own, so only touches that
	 * start in the outermost EDGE_PX strip are taken, and only while the panel
	 * can be seen. Those are caught in the capture phase on the window, before
	 * the player's handlers run, and kept from them; a tap in the strip still
	 * reaches the player. Every other touch is left alone.
	 *
	 * Listens in the window of each document handed to attach(): the one the
	 * player lives in.
	 */
	class QueueFullscreenSwipes {
		constructor({ isActive, panel }) {
			this._isActive = isActive;
			this._panel = panel;
			this._windows = new Map();
			this._gesture = null;
		}

		/** Listens in the windows of `docs` (nulls ignored), and stops listening anywhere else. */
		attach(docs) {
			const wanted = new Set(docs.map(doc => doc?.defaultView).filter(Boolean));
			for (const [win, stopListening] of this._windows) {
				if (wanted.has(win)) continue;
				stopListening();
				this._windows.delete(win);
			}
			for (const win of wanted) {
				if (!this._windows.has(win)) this._windows.set(win, this._listen(win));
			}
		}

		detach() {
			for (const stopListening of this._windows.values()) stopListening();
			this._windows.clear();
			this._gesture = null;
		}

		_listen(win) {
			// passive: false so a swipe can stop the browser's own reaction to it.
			const options = { capture: true, passive: false };
			const handlers = {
				touchstart: event => this._onStart(event, win),
				touchmove: event => this._onMove(event),
				touchend: event => this._onEnd(event),
				touchcancel: () => {
					this._gesture = null;
				},
			};
			for (const [type, handler] of Object.entries(handlers)) win.addEventListener(type, handler, options);
			return () => {
				for (const [type, handler] of Object.entries(handlers)) win.removeEventListener(type, handler, options);
			};
		}

		_onStart(event, win) {
			this._gesture = null;
			const touch = event.touches[0];
			if (event.touches.length !== 1 || !touch || !this._isActive()) return;
			if (this._panel.isOpen && this._panel.contains(event.target)) {
				// The list scrolls and its handles drag rows; only the rest of the panel can be swiped shut.
				if (!event.target.closest?.('.phq-list')) this._gesture = { kind: 'close', x: touch.clientX, y: touch.clientY };
				return;
			}
			const { EDGE_PX } = QUEUE.FULLSCREEN_SWIPE;
			const side = touch.clientX <= EDGE_PX ? 'left' : touch.clientX >= win.innerWidth - EDGE_PX ? 'right' : null;
			if (!side) {
				if (this._panel.isOpen) this._panel.toggle(false);
				return;
			}
			this._gesture = { kind: 'open', side, x: touch.clientX, y: touch.clientY, swiped: false };
			event.stopPropagation();
		}

		_onMove(event) {
			const gesture = this._gesture;
			if (gesture?.kind !== 'open') return;
			event.stopPropagation();
			if (gesture.swiped) {
				if (event.cancelable) event.preventDefault();
				return;
			}
			const touch = event.touches[0];
			if (!touch) return;
			const inward = gesture.side === 'left' ? touch.clientX - gesture.x : gesture.x - touch.clientX;
			if (inward < QUEUE.FULLSCREEN_SWIPE.MIN_PX || Math.abs(touch.clientY - gesture.y) > inward) return;
			gesture.swiped = true;
			if (event.cancelable) event.preventDefault();
			this._panel.toggle(true, gesture.side);
		}

		_onEnd(event) {
			const gesture = this._gesture;
			this._gesture = null;
			if (!gesture) return;
			if (gesture.kind === 'open') {
				// A tap in the strip belongs to the player after all.
				if (!gesture.swiped) return;
				event.stopPropagation();
				// Stops the click the browser would make from the end of the swipe.
				if (event.cancelable) event.preventDefault();
				return;
			}
			const touch = event.changedTouches[0];
			if (!touch) return;
			const dx = touch.clientX - gesture.x;
			const dy = touch.clientY - gesture.y;
			// A sheet is pulled down to close; a side panel is pushed back out of its edge.
			const outward = this._panel.isSheet ? dy : this._panel.side === 'left' ? -dx : dx;
			const across = this._panel.isSheet ? dx : dy;
			if (outward >= QUEUE.FULLSCREEN_SWIPE.MIN_PX && outward > Math.abs(across)) {
				this._panel.toggle(false);
			}
		}
	}

	// Elements the panel cannot be put inside, even when they are what is fullscreen.
	const NON_CONTAINER_TAGS = new Set(['VIDEO', 'IFRAME']);

	const TYPING_TARGETS = 'input, textarea, select, [contenteditable="true"]';

	/** The queue's keyboard shortcuts, when switched on. Ignored while typing and off watch pages. */
	class QueueShortcuts {
		constructor(settings, queue, { toggleCurrent }) {
			this._settings = settings;
			this._queue = queue;
			this._toggleCurrent = toggleCurrent;
		}

		install() {
			const actions = {
				queueShortcutAdd: () => this._toggleCurrent(),
				queueShortcutNext: () => this._queue.next(),
				queueShortcutPrev: () => this._queue.previous(),
			};
			document.addEventListener(
				'keydown',
				event => {
					if (!this._settings.get('queueEnabled') || !this._settings.get('queueShortcuts')) return;
					if (!Site.isWatchPage() || event.target?.closest?.(TYPING_TARGETS)) return;
					const combo = KeyCombos.of(event);
					const match = combo && SHORTCUT_SETTINGS.find(name => this._settings.get(name) === combo);
					if (!match) return;
					event.preventDefault();
					actions[match]();
				},
				true
			);
		}
	}

	/**
	 * Owns the queue's UI: the buttons in the player's controls, the panel on
	 * the video's edge, the thumbnail button and the shortcuts.
	 */
	class QueueUI {
		constructor(settings, bus, queue, { openSettings }) {
			this._settings = settings;
			this._bus = bus;
			this._queue = queue;
			this._status = new QueueStatusPill();
			this._panel = new QueuePanel(settings, queue, { openSettings, status: this._status });
			this._thumbs = new ThumbButton(settings, queue, { overlapsQueueUi: rect => this._panel.overlaps(rect) });
			this._playPill = new QueuePlayPill(settings, queue);
			this._menuItems = new QueueMenuItems(settings, queue, { status: this._status });
			this._shortcuts = new QueueShortcuts(settings, queue, { toggleCurrent: () => this._panel.toggleCurrent() });
			this._swipes = new QueueFullscreenSwipes({
				isActive: () => this._settings.get('queueEnabled') && this._panel.isShownInFullscreen(),
				panel: this._panel,
			});
			this._playerButtons = new PlayerButtonSet(
				[
					{
						key: PLAYER_BUTTON_KEYS.PREVIOUS,
						label: 'Previous in queue',
						icon: sitePlayerGlyphSvg('previous', PLAYER_GLYPH_SIZE_PX, '#ffffff'),
						placement: PLAYER_BUTTON_PLACEMENT.BEFORE_PLAY,
						onClick: () => queue.previous(),
					},
					{
						key: PLAYER_BUTTON_KEYS.STOP,
						label: 'Stop the queue',
						icon: PLAYER_STOP_SVG,
						placement: PLAYER_BUTTON_PLACEMENT.AFTER_PLAY,
						onClick: () => queue.stop(),
					},
					{
						key: PLAYER_BUTTON_KEYS.NEXT,
						label: 'Next in queue',
						icon: sitePlayerGlyphSvg('next', PLAYER_GLYPH_SIZE_PX, '#ffffff'),
						placement: PLAYER_BUTTON_PLACEMENT.AFTER_PLAY,
						follows: PLAYER_BUTTON_KEYS.STOP,
						// The queue's next button takes over from the player's own while it shows.
						replaces: doc => Site.nativeNextButton(doc),
						onClick: () => queue.next(),
					},
					{
						key: PLAYER_BUTTON_KEYS.PANEL,
						label: 'Queue',
						icon: PLAYER_QUEUE_SVG,
						placement: PLAYER_BUTTON_PLACEMENT.AFTER_PLAY,
						follows: PLAYER_BUTTON_KEYS.NEXT,
						// On phones the middle row is for playback; the queue sits with the download button.
						mobilePlacement: PLAYER_BUTTON_PLACEMENT.BEFORE_FULLSCREEN,
						onClick: () => {
							// The phone skin is applied after the buttons go in, so where the panel
							// belongs is settled at the tap.
							this._placePanel();
							this._panel.toggle(undefined, 'right');
						},
					},
				],
				{
					// Buttons are created whenever the player's controls appear, so they
					// get their state then rather than waiting for the next queue change.
					onAdded: () => this._renderPlayerButtons(this._queue.snapshot()),
				}
			);
		}

		mount() {
			Dom.addStyle(QUEUE_UI_STYLES, QUEUE_UI_STYLE_ID);
			this._status.mount();
			this._panel.mount();
			this._thumbs.mount();
			this._playPill.mount();
			this._menuItems.mount();
			this._shortcuts.install();

			this._bus.on('queue:changed', () => this._render());
			this._bus.on('queue:status', ({ text, duration }) => this._status.show(text, duration));
			this._settings.onChange('queueThumbSide', () => this._thumbs.hide());
			this._settings.onChange('queueEnabled', () => this._applyEnabled());

			document.addEventListener('pointerdown', event => {
				if (this._panel.isOpen && !event.target.closest?.(QUEUE_UI_SELECTOR)) this._panel.toggle(false);
			});
			for (const type of Dom.FULLSCREEN_EVENTS) document.addEventListener(type, () => this._placePanel());
			this._applyEnabled();
		}

		/** Opens, closes, or with no argument toggles the queue panel. */
		togglePanel(open) {
			if (this._settings.get('queueEnabled')) this._panel.toggle(open);
		}

		_applyEnabled() {
			const enabled = this._settings.get('queueEnabled');
			document.documentElement.classList.toggle(QUEUE_DISABLED_CLASS, !enabled);
			if (enabled) {
				this._placeInPlayer();
				this._render();
				return;
			}
			this._panel.toggle(false);
			this._thumbs.hide();
			this._playerButtons.detach();
			this._swipes.detach();
		}

		_placeInPlayer() {
			if (!this._settings.get('queueEnabled')) return;
			this._placePanel();
			const doc = this._queue.playerDocument();
			if (doc) this._playerButtons.attach(doc);
			else this._playerButtons.detach();
			this._swipes.attach([document, doc]);
		}

		/**
		 * On the player box, or, while a part of the player is fullscreen, inside
		 * that part: in fullscreen only the fullscreen element is shown.
		 */
		_placePanel() {
			const area = this._queue.playerArea();
			const fullscreen = Dom.fullscreenElement(document);
			const fullscreenHolds =
				fullscreen && area && area.contains(fullscreen) && !NON_CONTAINER_TAGS.has(fullscreen.tagName);
			// In fullscreen only the fullscreen element shows, so the phone's sheet goes inside it.
			if (area && Site.isMobilePlayer()) {
				this._panel.moveTo(null, { asSheet: true, host: fullscreenHolds ? fullscreen : document.documentElement });
				return;
			}
			const insidePlayer = fullscreenHolds && fullscreen !== area;
			this._panel.moveTo(insidePlayer ? fullscreen : area);
		}

		_render() {
			const snapshot = this._queue.snapshot();
			this._panel.render(snapshot);
			this._thumbs.render();
			this._playPill.render(snapshot);
			this._menuItems.render();
			this._renderPlayerButtons(snapshot);
		}

		_renderPlayerButtons({ queue, playingAnywhere, playingHere }) {
			const setDisabled = (key, disabled) => {
				const element = this._playerButtons.element(key);
				if (!element) return;
				element.setAttribute('aria-disabled', String(disabled));
				element.style.opacity = disabled ? DISABLED_PLAYER_BUTTON_OPACITY : '';
			};
			// The queue's player controls only show while it plays in this tab.
			for (const key of Object.values(PLAYER_BUTTON_KEYS)) {
				this._playerButtons.setShown(key, playingHere);
			}
			setDisabled(PLAYER_BUTTON_KEYS.NEXT, queue.length < 2);

			const panelButton = this._playerButtons.element(PLAYER_BUTTON_KEYS.PANEL);
			if (!panelButton) return;
			// The head is the playing video, so it does not count as waiting.
			const waiting = playingAnywhere && queue.length > 0 ? queue.length - 1 : queue.length;
			panelButton.setAttribute('aria-label', waiting ? `Queue (${waiting} waiting)` : 'Queue');
			this._queueBadge(panelButton).textContent = waiting ? String(waiting) : '';
			this._queueBadge(panelButton).hidden = !waiting;
		}

		_queueBadge(button) {
			let badge = button.querySelector('[data-phq-badge]');
			if (badge) return badge;
			badge = Dom.create('span', { attrs: { 'data-phq-badge': '' } });
			button.append(badge);
			return badge;
		}
	}

	// =====================================================================
	// 6. App: connects settings to features and handles the page lifecycle
	// =====================================================================

	const FILTER_SETTINGS = [
		'hideWatched',
		'hidePaid',
		'hideVR',
		'hideAI',
		'hideDurationOutOfRange',
		'hideWords',
		'showWords',
		'minDuration',
		'maxDuration',
	];
	const LISTING_DURATION_SETTINGS = ['enforceSearchDuration', 'minDuration', 'maxDuration'];

	class App {
		constructor(settings, ageGate) {
			this._settings = settings;
			this._ageGate = ageGate;
			this._bus = new EventBus();

			this._durationFilter = new DurationFilter(settings);
			this._videoFilter = new VideoFilter(settings, this._durationFilter);
			this._sorter = new VideoSorter(settings);
			this._playlistEdit = new PlaylistEditMode(this._bus);
			this._playlistOrder = new PlaylistOrder();
			this._language = new LanguageRedirect(settings);
			this._autoScroller = new PlaylistAutoScroller({
				bus: this._bus,
				onItemsAppended: items => this._filterIfActive(items),
			});
			this._volumeSync = new VolumeSync(settings);
			this._autoMute = new AutoMute();
			this._autoplayBlocker = new AutoplayBlocker();
			this._downloadButton = new DownloadButton();
			this._observer = new VideoListObserver({
				onItemsAdded: items => this._filterIfActive(items),
				onListsChanged: () => this._runPagePass(),
			});

			this._queueStore = new QueueStore(this._bus);
			this._playingTab = new PlayingTab(this._queueStore, {
				onLost: () => this._queuePlayer.handOver(),
				onSettled: () => this._bus.emit('queue:changed'),
			});
			this._queuePlayer = new QueuePlayer({
				settings,
				store: this._queueStore,
				positions: new QueuePositions(),
				playingTab: this._playingTab,
				bus: this._bus,
			});
			this._queue = new QueueController({
				store: this._queueStore,
				player: this._queuePlayer,
				bus: this._bus,
			});

			this._ui = new MenuUI(settings, this._bus, {
				sortNow: mode => {
					this._sorter.sort(mode, { includePlaylists: true });
					this._scrollToTop();
				},
				toggleAutoscroll: () => this._autoScroller.toggle(),
				scrollToTop: () => this._scrollToTop(),
				playQueue: () => this._queue.start(),
			});
			this._queueUI = new QueueUI(settings, this._bus, this._queue, { openSettings: () => this._ui.openSettings('Queue') });
			this._playlistTools = new PlaylistEditTools(settings, this._bus, {
				sort: (key, descending) => this._playlistOrder.sort(Site.editablePlaylist(), key, descending),
				restoreOrder: () => this._playlistOrder.restore(Site.editablePlaylist()),
			});

			// Several settings can change in one interaction (both slider bounds);
			// coalescing runs the resulting work once.
			// While a playlist is edited every video stays visible, so the user sees what Save keeps.
			this._refilterAllSoon = coalesceToMicrotask(() => {
				if (!this._playlistEdit.isEditing) this._videoFilter.apply();
			});
			this._enforceListingUrlSoon = coalesceToMicrotask(() => this._durationFilter.enforceListingUrl());
		}

		/** Runs once the DOM is ready. */
		start() {
			try {
				if (this._ageGate.reloadIfServedWithGate()) return;
				this._durationFilter.enforceListingUrl();
				this._language.scheduleCheck();
				CursorHider.setEnabled(this._settings.get('hideCursor'));
				PlaylistDeleteMarker.install();
				this._ui.mount();
				// Before the first page pass, whose auto-sort may reorder the playlist.
				this._playlistOrder.remember(Site.editablePlaylist());
				this._playlistTools.mount();
				this._bindPlaylistEditing();
				if (this._settings.get('downloadButton')) this._downloadButton.enable();
				this._bindSettingReactions();
				this._bindAutoscroll();
				this._bindLifecycle();
				this._startQueue();
				this._observer.connect();
				setTimeout(() => this._runPagePass(), CONFIG.TIMING.FEATURE_INIT_DELAY_MS);
				Log.info('initialized');
			} catch (error) {
				Log.error('App.start', error);
			}
		}

		_startQueue() {
			// Every change may mean another tab started playing, and a waiting tab
			// lines up behind it to notice if it crashes.
			this._bus.on('queue:changed', () => this._playingTab.watchOwner());
			this._bus.on('queue:video', video => {
				this._autoplayBlocker.allowPlayback();
				if (this._settings.get('syncVolume')) this._volumeSync.attach([video]);
			});
			this._queueUI.mount();
			// Any source: switching the queue off in one tab stops it in the tab playing it.
			this._settings.onChange('queueEnabled', ({ value }) => {
				if (!value && this._queuePlayer.playing) this._queuePlayer.stop();
			});

			window.addEventListener('storage', event => {
				// Another tab added, removed or moved videos: the queue is shared live.
				if (event.key === QUEUE.STORAGE.STATE) this._queueStore.reloadFromOtherTab();
			});
			// beforeunload rather than pagehide: pagehide also fires when the page
			// enters the back/forward cache, and a restored page would then think it
			// still plays a queue it had already given up.
			window.addEventListener('beforeunload', () => this._queuePlayer.prepareForUnload());

			this._queuePlayer.resumeAfterReload();
			this._playingTab.watchOwner();
			this._exposeQueueApi();
		}

		/** For the browser console and other scripts on the page. */
		_exposeQueueApi() {
			window.phproQueue = {
				getState: () => this._queue.snapshot(),
				togglePanel: open => this._queueUI.togglePanel(open),
				play: () => this._queue.start(),
				stop: () => this._queue.stop(),
			};
		}

		// The one place that decides what each setting change does. Effects that
		// navigate or reload only follow this tab's own changes; a setting synced
		// from another tab must not reload this one.
		_bindSettingReactions() {
			const settings = this._settings;
			const onAnyChange = (name, handler) => settings.onChange(name, ({ value }) => handler(value));
			const onUserChange = (name, handler) =>
				settings.onChange(name, ({ value, source }) => {
					if (source === ChangeSource.USER) handler(value);
				});

			onUserChange('autoConfirmAge', enabled => (enabled ? this._ageGate.confirm() : this._ageGate.revoke()));
			onUserChange('redirectToEnglish', enabled => {
				if (enabled) this._language.scheduleCheck();
			});
			for (const name of LISTING_DURATION_SETTINGS) onUserChange(name, this._enforceListingUrlSoon);

			onAnyChange('hideShorts', hidden => SiteCleanup.setShortsHidden(hidden));
			onAnyChange('hideCursor', enabled => CursorHider.setEnabled(enabled));
			onAnyChange('downloadButton', enabled => (enabled ? this._downloadButton.enable() : this._downloadButton.disable()));
			onAnyChange('sortMode', mode => this._sorter.sort(mode, { includePlaylists: this._autoSortsPlaylists() }));
			for (const name of FILTER_SETTINGS) onAnyChange(name, this._refilterAllSoon);

			onUserChange('muteByDefault', enabled => {
				if (!enabled) return;
				this._autoMute.reset();
				this._autoMute.apply(Site.playerVideos());
			});
			settings.onChange('blockAutoplay', ({ value, source }) => {
				// Re-arm straight away when switched on mid-page.
				if (value && source === ChangeSource.USER) this._autoplayBlocker.reset();
				this._autoplayBlocker.setEnabled(value);
				if (value) this._autoplayBlocker.watch(Site.playerVideos());
			});
			for (const name of ['savedVolume', 'savedMuted']) {
				settings.onChange(name, ({ source }) => {
					if (source === ChangeSource.SYNC && settings.get('syncVolume')) {
						this._volumeSync.applyTo(Site.playerVideos());
					}
				});
			}
		}

		_bindAutoscroll() {
			this._bus.on('autoscroll:state', ({ isRunning }) => {
				if (isRunning) {
					// Autoscroll filters what it appends itself; the observer would
					// only re-run sorting on every page.
					this._observer.disconnect();
					return;
				}
				this._runPagePass();
				this._observer.connect();
				setTimeout(() => this._scrollToTop(), CONFIG.TIMING.AUTOSCROLL_STOP_SCROLL_DELAY_MS);
			});
		}

		_bindLifecycle() {
			document.addEventListener('visibilitychange', () => {
				if (document.visibilityState !== 'visible') {
					this._autoMute.reset();
					return;
				}
				// Cookie writes from other subdomains fire no event, so returning to
				// the tab is the moment to pick them up.
				this._settings.refresh();
				if (this._settings.get('syncVolume')) this._volumeSync.applyTo(Site.playerVideos());
				setTimeout(() => this._runPagePass(), CONFIG.TIMING.FEATURE_INIT_DELAY_MS);
			});

			// Another tab on this origin wrote a setting (see CrossDomainStorage).
			window.addEventListener('storage', event => {
				if (event.key === CrossDomainStorage.SYNC_PING_KEY) this._settings.refresh();
			});

			// Restored from the back/forward cache: no script re-ran, so state and
			// the observer are brought back in line by hand.
			window.addEventListener('pageshow', event => {
				if (!event.persisted) return;
				this._settings.refresh();
				// Other tabs' queue changes were missed while the page sat in the cache.
				this._queueStore.reloadFromOtherTab();
				this._observer.connect();
				this._runPagePass();
			});
		}

		/** Applies sorting, filtering and player preferences to whatever is on the page now. */
		_runPagePass() {
			try {
				const mode = this._settings.get('sortMode');
				if (mode !== 'none') this._sorter.sort(mode, { includePlaylists: this._autoSortsPlaylists() });
				this._filterIfActive();
				this._applyPlayerPreferences();
			} catch (error) {
				Log.error('App.runPagePass', error);
			}
		}

		// Skipped when nothing is active so the script leaves the site's own
		// item visibility alone. Turning a filter off goes through
		// _refilterAllSoon instead, which always runs.
		_filterIfActive(items) {
			if (this._playlistEdit.isEditing) return;
			if (this._videoFilter.hasActiveFilters()) this._videoFilter.apply(items);
		}

		/** Auto-sort leaves a playlist that is being edited alone, or Save would keep its order. */
		_autoSortsPlaylists() {
			return this._settings.get('sortWithinPlaylists') && !this._playlistEdit.isEditing;
		}

		/**
		 * Editing shows every video in the order Save would keep: filters and
		 * auto-sort step aside, and an auto-sorted playlist goes back to its
		 * saved order. Both come back when editing ends.
		 */
		_bindPlaylistEditing() {
			this._bus.on('playlist:editing', ({ isEditing }) => {
				if (isEditing) {
					this._videoFilter.reveal(Site.allItems());
					this._playlistOrder.restore(Site.editablePlaylist());
					return;
				}
				this._runPagePass();
				this._refilterAllSoon();
			});
			this._playlistEdit.watch();
		}

		_applyPlayerPreferences() {
			const videos = Site.playerVideos();
			if (videos.length === 0) return;
			// Order matters: mute-by-default must win over a saved unmuted state.
			if (this._settings.get('syncVolume')) this._volumeSync.attach(videos);
			if (this._settings.get('muteByDefault')) this._autoMute.apply(videos);
			const blockAutoplay = this._settings.get('blockAutoplay');
			this._autoplayBlocker.setEnabled(blockAutoplay);
			if (blockAutoplay) this._autoplayBlocker.watch(videos);
		}

		_scrollToTop() {
			window.scrollTo({ top: 0, behavior: 'smooth' });
		}
	}

	// =====================================================================
	// 7. Bootstrap
	// =====================================================================

	try {
		const settings = new Settings(SETTINGS_SCHEMA, CrossDomainStorage);

		// Document-start work: must happen before the page parses or reads cookies.
		const ageGate = new AgeGate(settings);
		ageGate.applyAtDocumentStart();
		SiteCleanup.install();
		SiteCleanup.setShortsHidden(settings.get('hideShorts'));
		// Ahead of the page's own listeners, which stop touches on the player's controls.
		PlayerTapRouter.install(window);

		const app = new App(settings, ageGate);
		if (document.readyState === 'loading') {
			document.addEventListener('DOMContentLoaded', () => app.start(), { once: true });
		} else {
			app.start();
		}
	} catch (error) {
		Log.error('startup', error);
	}
})();