☰

Pornhub Cleaner

Hide watched, ignored, too short or too long videos and blocked channels on Pornhub, keep your own watch history and make thumbnails bigger

Чтобы установить этот скрипт, вы сначала должны установить расширение браузера, например Tampermonkey, Greasemonkey или Violentmonkey.

Вам потребуется установить расширение, например Tampermonkey или Violentmonkey, чтобы установить этот скрипт.

Чтобы установить этот скрипт, вы сначала должны установить расширение браузера, например Tampermonkey или Violentmonkey.

Чтобы установить этот скрипт, вы сначала должны установить расширение браузера, например Tampermonkey или Userscripts.

Чтобы установить этот скрипт, сначала вы должны установить расширение браузера, например Tampermonkey.

Чтобы установить этот скрипт, вы должны установить расширение — менеджер скриптов.

(у меня уже есть менеджер скриптов, дайте мне установить скрипт!)

Чтобы установить этот стиль, сначала вы должны установить расширение браузера, например Stylus.

Чтобы установить этот стиль, сначала вы должны установить расширение браузера, например Stylus.

Чтобы установить этот стиль, сначала вы должны установить расширение браузера, например Stylus.

Чтобы установить этот стиль, сначала вы должны установить расширение — менеджер стилей.

Чтобы установить этот стиль, сначала вы должны установить расширение — менеджер стилей.

Чтобы установить этот стиль, сначала вы должны установить расширение — менеджер стилей.

(у меня уже есть менеджер стилей, дайте мне установить скрипт!)

// ==UserScript==
// @name         Pornhub Cleaner
// @namespace    http://tampermonkey.net/
// @version      1.7
// @description  Hide watched, ignored, too short or too long videos and blocked channels on Pornhub, keep your own watch history and make thumbnails bigger
// @author       Common-Fool
// @license      MIT
// @homepageURL  https://github.com/Common-Fool/Pornhub-cleaner
// @supportURL   https://github.com/Common-Fool/Pornhub-cleaner/issues
// @match        https://*.pornhub.com/*
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_addStyle
// @grant        GM_addValueChangeListener
// @run-at       document-idle
// ==/UserScript==

(function() {
    'use strict';

    // ==================== Site markup ====================

    // Video cards: listings, related videos, playlists and the header dropdowns
    const CARD_SELECTOR = 'li.pcVideoListItem, li.videoblock';
    // The site's own "Watched" label on a thumbnail (two variants are in use)
    const SITE_WATCHED_SELECTOR = '.watchedVideo, .watchedVideoText';
    const THUMB_LINK_SELECTOR = 'a.linkVideoThumb, .phimage a[href*="viewkey="]';
    // Channel, model, pornstar or user who uploaded the video
    const UPLOADER_SELECTOR = '.usernameWrap a[href]';
    // Video length on the thumbnail, "12:34" or "1:02:03"
    const DURATION_SELECTOR = '.marker-overlays .duration, .duration';
    // Column next to the player: .sideColumn, or #hd-rightColVideoPage in the older
    // layout. Its layout depends on the thumbnail size
    const RIGHT_COLUMN_SELECTOR = '.sideColumn, #hd-rightColVideoPage';
    // Filtered, but never scaled: the header dropdowns and the column next to the
    // player. The site adds cards there after loading, so the check is also made in CSS
    const NO_SCALE_SELECTOR = `#header, header, ${RIGHT_COLUMN_SELECTOR}`;
    // Lists under the player: with bigger thumbnails they stretch across the window.
    // The column next to the player sits in the same block and is never stretched
    const STRETCH_SELECTOR = '#hd-leftColVideoPage';

    // ==================== Data ====================

    // Thumbnail size: from the site's own size up to three times as big
    const SCALE_MIN = 1, SCALE_MAX = 3, SCALE_STEP = 0.1;

    // Title words offered under the word box until they are added
    const WORD_SUGGESTIONS = ['compilation', 'fart*', 'bts', 'behind the scenes', 'backstage', 'trans', 'gay'];
    const WORD_MAX_LENGTH = 60;

    let hideIgnored = GM_getValue('hideIgnored', true);
    let hideBlockedChannels = GM_getValue('hideBlockedChannels', true);
    let hideWatched = GM_getValue('hideWatched', true);
    let hideShort = GM_getValue('hideShort', false);
    let hideLong = GM_getValue('hideLong', false);
    let hideWords = GM_getValue('hideWords', false);
    // Words and phrases that hide a video when its title has them (see wordPattern)
    let titleWords = cleanWords(GM_getValue('titleWords', []));
    // Minutes typed into the length boxes; null while a box is empty
    const durationMinutes = {
        shortMinutes: validMinutes(GM_getValue('shortMinutes', null)),
        longMinutes:  validMinutes(GM_getValue('longMinutes', null)),
    };
    let scaleThumbs = GM_getValue('scaleThumbs', false);
    let thumbScale = validScale(GM_getValue('thumbScale', 1.5));
    let ignoredVideos = GM_getValue('ignoredVideos', []);
    let blockedChannels = GM_getValue('blockedChannels', []);
    let watchedVideos = GM_getValue('watchedVideos', []);
    let panelState = GM_getValue('panelState', 1);
    if (panelState !== 0) panelState = 1;

    // First automatic showing comes one interval after install
    let donateLastShown = GM_getValue('donateLastShown', 0);
    if (!donateLastShown) {
        donateLastShown = Date.now();
        GM_setValue('donateLastShown', donateLastShown);
    }

    // ==================== Lookup indexes (Set) ====================

    let ignoredKeys = new Set();
    let watchedKeys = new Set();
    let blockedKeys = new Set();

    function rebuildLookups() {
        ignoredKeys = new Set(ignoredVideos.map(v => v.key).filter(Boolean));
        watchedKeys = new Set(watchedVideos.map(v => v.key).filter(Boolean));
        blockedKeys = new Set(blockedChannels.map(c => c.key).filter(Boolean));
    }

    rebuildLookups();

    // One regular expression per title word
    let wordMatchers = [];

    function rebuildWordMatchers() {
        wordMatchers = titleWords.map(wordPattern).filter(Boolean);
    }

    rebuildWordMatchers();

    // ==================== Cross-tab sync ====================

    const toggleKeys = {
        hideIgnored:         v => { hideIgnored = v; },
        hideBlockedChannels: v => { hideBlockedChannels = v; },
        hideWatched:         v => { hideWatched = v; },
        hideShort:           v => { hideShort = v; },
        hideLong:            v => { hideLong = v; },
        hideWords:           v => { hideWords = v; },
    };

    // `reason` links a toggle to the filter that hides a card (see filterVideos).
    // Toggles with `duration` are the length filters and the one with `words` is the
    // title word filter: they have settings of their own, and "All" leaves them alone
    const toggleDefs = [
        { id: 'phc-ignored-toggle',          countId: 'phc-cnt-ignored',  key: 'hideIgnored',         reason: 'ignored', label: 'Ignored',  get: () => hideIgnored },
        { id: 'phc-blocked-channels-toggle', countId: 'phc-cnt-channels', key: 'hideBlockedChannels', reason: 'channel', label: 'Channels', get: () => hideBlockedChannels },
        { id: 'phc-watched-toggle',          countId: 'phc-cnt-watched',  key: 'hideWatched',         reason: 'watched', label: 'Watched',  get: () => hideWatched },
        { id: 'phc-short-toggle',            countId: 'phc-cnt-short',    key: 'hideShort',           reason: 'short',   label: 'Shorter than', get: () => hideShort,
          duration: { valueKey: 'shortMinutes', inputId: 'phc-short-minutes', presetsId: 'phc-short-presets', presets: [2, 5, 10, 30] } },
        { id: 'phc-long-toggle',             countId: 'phc-cnt-long',     key: 'hideLong',            reason: 'long',    label: 'Longer than',  get: () => hideLong,
          duration: { valueKey: 'longMinutes', inputId: 'phc-long-minutes', presetsId: 'phc-long-presets', presets: [10, 30, 60] } },
        { id: 'phc-words-toggle',            countId: 'phc-cnt-words',    key: 'hideWords',           reason: 'words',   label: 'Keywords filter', get: () => hideWords,
          words: true },
    ];

    for (const [key, setter] of Object.entries(toggleKeys)) {
        GM_addValueChangeListener(key, (name, oldVal, newVal, remote) => {
            if (remote) { setter(newVal); syncTogglesUI(); filterVideos(); }
        });
    }

    const dataKeys = {
        ignoredVideos:   v => { ignoredVideos = v; },
        blockedChannels: v => { blockedChannels = v; },
        watchedVideos:   v => { watchedVideos = v; },
    };

    for (const [key, setter] of Object.entries(dataKeys)) {
        GM_addValueChangeListener(key, (name, oldVal, newVal, remote) => {
            if (remote) { setter(newVal); rebuildLookups(); filterVideos(); }
        });
    }

    for (const key of Object.keys(durationMinutes)) {
        GM_addValueChangeListener(key, (name, oldVal, newVal, remote) => {
            if (remote) { durationMinutes[key] = validMinutes(newVal); syncTogglesUI(); filterVideos(); }
        });
    }

    GM_addValueChangeListener('titleWords', (name, oldVal, newVal, remote) => {
        if (remote) { titleWords = cleanWords(newVal); rebuildWordMatchers(); renderWords(); filterVideos(); }
    });

    GM_addValueChangeListener('scaleThumbs', (name, oldVal, newVal, remote) => {
        if (remote) { scaleThumbs = newVal; syncScaleUI(); applyThumbScale(); }
    });

    GM_addValueChangeListener('thumbScale', (name, oldVal, newVal, remote) => {
        if (remote) { thumbScale = validScale(newVal); syncScaleUI(); applyThumbScale(); }
    });

    // Dismissing the donate banner in one tab hides it in the others
    GM_addValueChangeListener('donateLastShown', (name, oldVal, newVal, remote) => {
        if (remote) { donateLastShown = newVal; hideDonateBanner(); }
    });

    // ==================== Donations ====================

    const DONATE_INTERVAL = 7 * 24 * 60 * 60 * 1000;

    const donateLinks = [
        { label: 'Monobank',   note: 'jar, any bank card', url: 'https://send.monobank.ua/jar/6m4nBQCW9B' },
        { label: 'Ko-fi',      note: 'card, PayPal',       url: 'https://ko-fi.com/commonfool' },
        { label: 'Crypto',     note: 'NOWPayments',        url: 'https://nowpayments.io/donation/commonfool' },
    ];

    // QR code for the Monobank jar link
    const DONATE_QR_PATH = 'M0 0h7v1H0zM8 0h4v1H8zM15 0h2v1H15zM19 0h2v1H19zM22 0h7v1H22zM0 1h1v1H0zM6 1h1v1H6zM8 1h6v1H8zM16 1h3v1H16zM20 1h1v1H20zM22 1h1v1H22zM28 1h1v1H28zM0 2h1v1H0zM2 2h3v1H2zM6 2h1v1H6zM10 2h1v1H10zM12 2h1v1H12zM14 2h1v1H14zM16 2h1v1H16zM18 2h1v1H18zM20 2h1v1H20zM22 2h1v1H22zM24 2h3v1H24zM28 2h1v1H28zM0 3h1v1H0zM2 3h3v1H2zM6 3h1v1H6zM8 3h4v1H8zM17 3h1v1H17zM19 3h1v1H19zM22 3h1v1H22zM24 3h3v1H24zM28 3h1v1H28zM0 4h1v1H0zM2 4h3v1H2zM6 4h1v1H6zM9 4h1v1H9zM14 4h1v1H14zM17 4h1v1H17zM19 4h2v1H19zM22 4h1v1H22zM24 4h3v1H24zM28 4h1v1H28zM0 5h1v1H0zM6 5h1v1H6zM9 5h4v1H9zM14 5h1v1H14zM16 5h1v1H16zM19 5h2v1H19zM22 5h1v1H22zM28 5h1v1H28zM0 6h7v1H0zM8 6h1v1H8zM10 6h1v1H10zM12 6h1v1H12zM14 6h1v1H14zM16 6h1v1H16zM18 6h1v1H18zM20 6h1v1H20zM22 6h7v1H22zM8 7h2v1H8zM11 7h5v1H11zM17 7h4v1H17zM0 8h1v1H0zM2 8h2v1H2zM5 8h3v1H5zM9 8h2v1H9zM13 8h1v1H13zM17 8h1v1H17zM22 8h1v1H22zM25 8h1v1H25zM27 8h2v1H27zM2 9h1v1H2zM4 9h2v1H4zM10 9h1v1H10zM12 9h1v1H12zM17 9h6v1H17zM24 9h1v1H24zM28 9h1v1H28zM0 10h1v1H0zM3 10h2v1H3zM6 10h1v1H6zM9 10h2v1H9zM12 10h1v1H12zM14 10h1v1H14zM18 10h1v1H18zM20 10h4v1H20zM26 10h2v1H26zM0 11h1v1H0zM3 11h1v1H3zM8 11h2v1H8zM11 11h1v1H11zM13 11h1v1H13zM16 11h1v1H16zM18 11h1v1H18zM20 11h1v1H20zM23 11h1v1H23zM28 11h1v1H28zM1 12h6v1H1zM10 12h2v1H10zM15 12h1v1H15zM17 12h1v1H17zM19 12h1v1H19zM25 12h2v1H25zM0 13h1v1H0zM5 13h1v1H5zM8 13h8v1H8zM19 13h1v1H19zM22 13h1v1H22zM26 13h3v1H26zM0 14h1v1H0zM2 14h1v1H2zM5 14h3v1H5zM9 14h1v1H9zM11 14h1v1H11zM14 14h1v1H14zM16 14h2v1H16zM19 14h3v1H19zM24 14h1v1H24zM26 14h3v1H26zM1 15h3v1H1zM5 15h1v1H5zM8 15h1v1H8zM11 15h1v1H11zM13 15h1v1H13zM16 15h1v1H16zM18 15h1v1H18zM23 15h1v1H23zM27 15h1v1H27zM2 16h3v1H2zM6 16h2v1H6zM10 16h1v1H10zM15 16h1v1H15zM18 16h1v1H18zM20 16h2v1H20zM23 16h3v1H23zM27 16h1v1H27zM1 17h1v1H1zM4 17h2v1H4zM7 17h2v1H7zM11 17h3v1H11zM15 17h1v1H15zM20 17h1v1H20zM23 17h1v1H23zM25 17h3v1H25zM0 18h1v1H0zM2 18h2v1H2zM5 18h2v1H5zM9 18h1v1H9zM11 18h1v1H11zM15 18h1v1H15zM18 18h1v1H18zM22 18h3v1H22zM26 18h1v1H26zM4 19h2v1H4zM9 19h1v1H9zM11 19h1v1H11zM16 19h7v1H16zM26 19h1v1H26zM1 20h3v1H1zM5 20h2v1H5zM9 20h5v1H9zM17 20h10v1H17zM8 21h3v1H8zM12 21h3v1H12zM20 21h1v1H20zM24 21h5v1H24zM0 22h7v1H0zM8 22h2v1H8zM11 22h3v1H11zM16 22h1v1H16zM19 22h2v1H19zM22 22h1v1H22zM24 22h2v1H24zM27 22h1v1H27zM0 23h1v1H0zM6 23h1v1H6zM8 23h4v1H8zM20 23h1v1H20zM24 23h2v1H24zM27 23h2v1H27zM0 24h1v1H0zM2 24h3v1H2zM6 24h1v1H6zM9 24h1v1H9zM14 24h1v1H14zM17 24h2v1H17zM20 24h5v1H20zM26 24h2v1H26zM0 25h1v1H0zM2 25h3v1H2zM6 25h1v1H6zM8 25h1v1H8zM11 25h1v1H11zM13 25h4v1H13zM19 25h1v1H19zM21 25h1v1H21zM23 25h3v1H23zM28 25h1v1H28zM0 26h1v1H0zM2 26h3v1H2zM6 26h1v1H6zM8 26h1v1H8zM11 26h1v1H11zM16 26h3v1H16zM20 26h1v1H20zM23 26h1v1H23zM26 26h1v1H26zM28 26h1v1H28zM0 27h1v1H0zM6 27h1v1H6zM9 27h1v1H9zM11 27h1v1H11zM13 27h2v1H13zM16 27h1v1H16zM20 27h1v1H20zM22 27h2v1H22zM25 27h1v1H25zM27 27h1v1H27zM0 28h7v1H0zM8 28h1v1H8zM10 28h2v1H10zM14 28h1v1H14zM16 28h1v1H16zM19 28h2v1H19zM22 28h2v1H22zM25 28h1v1H25zM27 28h1v1H27z';

    // ==================== Utilities ====================

    function validMinutes(value) {
        return Number.isInteger(value) && value > 0 ? value : null;
    }

    function validScale(value) {
        const n = Number(value);
        if (!Number.isFinite(n)) return 1.5;
        return Math.round(Math.min(SCALE_MAX, Math.max(SCALE_MIN, n)) * 10) / 10;
    }

    // "12:34" → 754, "1:02:03" → 3723; null when there is no length
    function parseDuration(text) {
        const value = String(text || '').trim();
        if (!/^\d+(:\d{1,2}){0,2}$/.test(value)) return null;
        return value.split(':').reduce((total, part) => total * 60 + Number(part), 0);
    }

    // A title word as stored: lower case, single spaces, no spaces around asterisks.
    // null when there is nothing to look for
    function normalizeWord(text) {
        const word = String(text || '').toLowerCase()
            .replace(/\s+/g, ' ')
            .replace(/\*+/g, '*')
            .replace(/ ?\* ?/g, '*')
            .trim()
            .slice(0, WORD_MAX_LENGTH);
        return /[\p{L}\p{N}]/u.test(word) ? word : null;
    }

    function cleanWords(list) {
        if (!Array.isArray(list)) return [];
        return [...new Set(list.map(normalizeWord).filter(Boolean))];
    }

    function escapeRegExp(str) {
        return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    }

    // "gay" matches the whole word only, "fart*" also matches "farting" and "*cam*"
    // matches "cam" anywhere in a word. Case doesn't matter. The spaces of a phrase
    // match any spaces, hyphens or underscores between its words
    function wordPattern(word) {
        const letter = '[\\p{L}\\p{N}]';
        const body = word.split('*')
            .map(part => part.split(' ').map(escapeRegExp).join('[\\s\\-_]+'))
            .join(`${letter}*`);
        const start = word.startsWith('*') ? '' : `(?<!${letter})`;
        const end = word.endsWith('*') ? '' : `(?!${letter})`;
        try {
            return new RegExp(start + body + end, 'iu');
        } catch (e) {
            return null;
        }
    }

    function escapeHtml(str) {
        if (!str) return '';
        const div = document.createElement('div');
        div.textContent = str;
        return div.innerHTML;
    }

    function extractViewkey(url) {
        const m = String(url || '').match(/[?&]viewkey=([A-Za-z0-9]+)/);
        return m ? m[1] : null;
    }

    function videoUrl(key) {
        return `/view_video.php?viewkey=${key}`;
    }

    // '/channels/teamskeet/videos?page=2' → '/channels/teamskeet'
    function uploaderKey(href) {
        if (!href) return null;
        let path;
        try { path = new URL(href, location.origin).pathname; } catch (e) { return null; }
        const m = path.toLowerCase().match(/^\/[^/]+\/[^/]+/);
        return m ? m[0] : null;
    }

    // Viewkey of the video open on this page, if it is a video page
    function currentViewkey() {
        return location.pathname.startsWith('/view_video.php') ? extractViewkey(location.search) : null;
    }

    function readCard(card) {
        const link = card.querySelector(THUMB_LINK_SELECTOR) || card.querySelector('a[href*="viewkey="]');
        const titleLink = card.querySelector('.title a');
        const uploaderLink = card.querySelector(UPLOADER_SELECTOR);

        return {
            key: card.getAttribute('data-video-vkey') || extractViewkey(link?.getAttribute('href')),
            title: (titleLink?.textContent || link?.getAttribute('title') || '').trim() || 'Untitled',
            // The title attribute holds the whole title, the text may be cut short
            fullTitle: (titleLink?.getAttribute('title') || titleLink?.textContent || link?.getAttribute('title') || '').trim(),
            uploaderLink,
            uploaderKey: uploaderKey(uploaderLink?.getAttribute('href')),
            uploaderName: uploaderLink?.textContent.trim() || '',
            siteWatched: !!card.querySelector(SITE_WATCHED_SELECTOR),
            duration: parseDuration(card.querySelector(DURATION_SELECTOR)?.textContent),
        };
    }

    // ==================== Styles ====================

    GM_addStyle(`
        .phc-hidden {
            display: none !important;
        }

        #phc-control-panel {
            position: fixed;
            bottom: 8px;
            right: 8px;
            width: 180px;
            max-height: calc(100vh - 16px);
            overflow-y: auto;
            box-sizing: border-box;
            background: #1a1a1a;
            border: 1px solid #333;
            border-radius: 6px;
            padding: 7px 8px;
            z-index: 9999;
            color: #fff;
            font-family: Arial, Helvetica, sans-serif;
            font-size: 11px;
            line-height: 1.3;
            text-align: left;
            box-shadow: 0 3px 10px rgba(0,0,0,0.5);
        }

        #phc-control-panel * {
            box-sizing: border-box;
            text-align: left;
        }

        #phc-control-panel h3 {
            margin: 0;
            padding: 0;
            font-size: 11px;
            font-weight: bold;
            color: #ff9000;
            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 6px;
            white-space: nowrap;
        }

        #phc-control-panel h3 .phc-collapse-btn {
            background: none;
            border: none;
            color: #ff9000;
            font-size: 10px;
            font-family: inherit;
            cursor: pointer;
            padding: 0;
            margin: 0;
            line-height: 1;
        }

        #phc-control-panel h3 .phc-collapse-btn:hover {
            color: #fff;
        }

        #phc-panel-body {
            margin-top: 6px;
        }

        .phc-head-row {
            display: flex;
            justify-content: space-between;
            align-items: baseline;
            gap: 8px;
            font-size: 10px;
            color: #7a7a7a;
            padding: 0 0 3px 18px;
            margin: 0 0 3px 0;
            border-bottom: 1px solid #2a2a2a;
        }

        .phc-toggle {
            display: flex;
            align-items: center;
            gap: 6px;
            margin: 0;
            padding: 2px 0;
            cursor: pointer;
            user-select: none;
        }

        .phc-toggle_master {
            padding-bottom: 4px;
            margin-bottom: 3px;
            border-bottom: 1px solid #2a2a2a;
        }

        .phc-toggle label {
            cursor: pointer;
            font-size: 11px;
            font-family: inherit;
            line-height: 1.2;
            flex: 1;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            color: #fff;
            margin: 0;
        }

        .phc-toggle_master label {
            color: #ddd;
        }

        #phc-control-panel .phc-count {
            flex: 0 0 auto;
            min-width: 16px;
            font-size: 11px;
            color: #9a9a9a;
            text-align: right;
        }

        #phc-control-panel .phc-toggle_master .phc-count {
            color: #ff9000;
            font-weight: bold;
        }

        #phc-control-panel input[type="checkbox"] {
            appearance: none;
            -webkit-appearance: none;
            -moz-appearance: none;
            flex: 0 0 auto;
            width: 12px;
            height: 12px;
            margin: 0;
            padding: 0;
            border: 1px solid #555;
            border-radius: 2px;
            background: #101010;
            cursor: pointer;
            position: relative;
        }

        #phc-control-panel input[type="checkbox"]:hover {
            border-color: #ff9000;
        }

        #phc-control-panel input[type="checkbox"]:checked {
            background: #ff9000;
            border-color: #ff9000;
        }

        #phc-control-panel input[type="checkbox"]:checked::after {
            content: '';
            position: absolute;
            left: 3px;
            top: 0px;
            width: 3px;
            height: 7px;
            border: solid #101010;
            border-width: 0 2px 2px 0;
            transform: rotate(45deg);
        }

        #phc-control-panel input[type="checkbox"]:indeterminate {
            background: #101010;
            border-color: #ff9000;
        }

        #phc-control-panel input[type="checkbox"]:indeterminate::after {
            content: '';
            position: absolute;
            left: 2px;
            top: 2px;
            width: 6px;
            height: 6px;
            border-radius: 1px;
            background: #ff9000;
        }

        #phc-duration-block,
        #phc-words-block,
        #phc-view-block {
            margin-top: 3px;
            padding-top: 3px;
            border-top: 1px solid #2a2a2a;
        }

        #phc-control-panel .phc-minutes {
            flex: 0 0 auto;
            display: inline-flex;
            align-items: center;
            gap: 3px;
            font-size: 10px;
            color: #7a7a7a;
        }

        #phc-control-panel .phc-minutes input {
            width: 30px;
            height: 16px;
            margin: 0;
            padding: 0 2px;
            border: 1px solid #555;
            border-radius: 2px;
            background: #101010;
            color: #fff;
            font-family: inherit;
            font-size: 11px;
            line-height: 14px;
            text-align: center;
            outline: none;
            box-shadow: none;
        }

        #phc-control-panel .phc-minutes input:focus {
            border-color: #ff9000;
        }

        .phc-presets {
            display: flex;
            gap: 4px;
            padding: 1px 0 3px 18px;
        }

        #phc-control-panel .phc-preset {
            flex: 0 0 auto;
            min-width: 26px;
            margin: 0;
            padding: 1px 4px;
            border: 1px solid #333;
            border-radius: 3px;
            background: #252525;
            color: #bbb;
            font-family: inherit;
            font-size: 10px;
            line-height: 1.3;
            text-align: center;
            cursor: pointer;
        }

        #phc-control-panel .phc-preset:hover {
            border-color: #ff9000;
            color: #ff9000;
        }

        /* Everything hidden on the page, whichever filter hid it */
        .phc-total-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 6px;
            margin-top: 3px;
            padding: 4px 0 1px 18px;
            border-top: 1px solid #2a2a2a;
            font-size: 11px;
            color: #ddd;
        }

        #phc-control-panel .phc-total-row .phc-count {
            color: #ff9000;
            font-weight: bold;
        }

        /* Title words: tags in a box with the text field after them */
        .phc-words-box {
            display: flex;
            flex-wrap: wrap;
            align-items: center;
            gap: 3px;
            max-height: 118px;
            overflow-y: auto;
            margin: 2px 0 3px 0;
            padding: 3px;
            border: 1px solid #555;
            border-radius: 3px;
            background: #101010;
            cursor: text;
        }

        .phc-words-box:focus-within {
            border-color: #ff9000;
        }

        #phc-control-panel .phc-word {
            display: inline-flex;
            align-items: center;
            gap: 1px;
            max-width: 100%;
            padding: 1px 1px 1px 5px;
            border: 1px solid #3a3a3a;
            border-radius: 3px;
            background: #252525;
            color: #ddd;
            font-size: 10px;
            line-height: 13px;
            cursor: default;
        }

        #phc-control-panel .phc-word:hover {
            border-color: #ff9000;
        }

        #phc-control-panel .phc-word-text {
            min-width: 0;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        #phc-control-panel .phc-word-x {
            flex: 0 0 auto;
            width: 12px;
            height: 12px;
            margin: 0;
            padding: 0;
            border: none;
            border-radius: 2px;
            background: none;
            color: #ff9000;
            font-family: inherit;
            font-size: 12px;
            line-height: 12px;
            text-align: center;
            cursor: pointer;
            visibility: hidden;
        }

        #phc-control-panel .phc-word:hover .phc-word-x {
            visibility: visible;
        }

        #phc-control-panel .phc-word-x:hover {
            background: #ff9000;
            color: #101010;
        }

        /* Touch screens have no hover: the remove buttons are always there */
        @media (hover: none) {
            #phc-control-panel .phc-word-x {
                visibility: visible;
            }
        }

        #phc-control-panel #phc-words-input {
            flex: 1 0 70px;
            min-width: 70px;
            height: 16px;
            margin: 0;
            padding: 0 2px;
            border: none;
            background: transparent;
            color: #fff;
            font-family: inherit;
            font-size: 11px;
            line-height: 16px;
            outline: none;
            box-shadow: none;
        }

        #phc-control-panel #phc-words-input::placeholder {
            color: #666;
        }

        .phc-word-suggestions {
            display: flex;
            flex-wrap: wrap;
            gap: 3px;
            padding: 0 0 3px 0;
        }

        #phc-control-panel .phc-word-sugg {
            flex: 0 0 auto;
            margin: 0;
            padding: 0 4px;
            border: 1px dashed #444;
            border-radius: 3px;
            background: none;
            color: #9a9a9a;
            font-family: inherit;
            font-size: 10px;
            line-height: 13px;
            cursor: pointer;
        }

        #phc-control-panel .phc-word-sugg:hover {
            border-color: #ff9000;
            color: #ff9000;
        }

        #phc-control-panel .phc-scale-value {
            flex: 0 0 auto;
            font-size: 11px;
            color: #ff9000;
            text-align: right;
        }

        .phc-scale-row {
            display: flex;
            align-items: center;
            gap: 4px;
            padding: 2px 0 3px 0;
            font-size: 9px;
            color: #7a7a7a;
        }

        #phc-control-panel .phc-scale-row input[type="range"] {
            flex: 1;
            min-width: 0;
            height: 14px;
            margin: 0;
            padding: 0;
            background: transparent;
            accent-color: #ff9000;
            cursor: pointer;
        }

        /* Bigger thumbnails: the card is zoomed, its text and our button keep their size */
        html.phc-scaling .phc-card {
            zoom: var(--phc-scale);
        }

        html.phc-scaling .phc-card .thumbnail-info-wrapper,
        html.phc-scaling .phc-card .phc-ignore-btn {
            zoom: var(--phc-unscale);
        }

        html.phc-scaling :is(${NO_SCALE_SELECTOR}) .phc-card,
        html.phc-scaling :is(${NO_SCALE_SELECTOR}) .phc-card .thumbnail-info-wrapper,
        html.phc-scaling :is(${NO_SCALE_SELECTOR}) .phc-card .phc-ignore-btn {
            zoom: 1 !important;
        }

        #phc-lists-block {
            margin-top: 6px;
            padding-top: 5px;
            border-top: 1px solid #2a2a2a;
        }

        .phc-btn {
            background: #ff9000;
            color: #000;
            border: none;
            padding: 8px 12px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            margin-top: 10px;
            width: 100%;
            font-weight: bold;
        }

        .phc-btn:hover {
            background: #e68200;
        }

        .phc-list-link {
            display: flex;
            justify-content: space-between;
            align-items: baseline;
            gap: 8px;
            background: none;
            border: none;
            width: 100%;
            text-align: left;
            color: #7a7a7a;
            font-size: 10px;
            font-family: inherit;
            padding: 2px 0;
            margin: 0;
            cursor: pointer;
            transition: color 0.2s;
        }

        .phc-list-link:hover {
            color: #ff9000;
        }

        .phc-list-link span {
            color: #ff9000;
        }

        .phc-ignore-btn {
            position: absolute;
            top: 6px;
            right: 6px;
            width: 36px;
            height: 36px;
            background: rgba(0, 0, 0, 0.5);
            border: 2px solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            cursor: pointer;
            opacity: 0;
            transition: opacity 0.2s, background 0.2s;
            z-index: 100;
            display: flex;
            align-items: center;
            justify-content: center;
            box-sizing: border-box;
        }

        .phc-card:hover .phc-ignore-btn {
            opacity: 1;
        }

        .phc-ignore-btn:hover {
            background: rgba(0, 0, 0, 0.8);
            border-color: rgba(255, 255, 255, 0.6);
        }

        .phc-ignore-btn::before,
        .phc-ignore-btn::after {
            content: '';
            position: absolute;
            width: 18px;
            height: 3px;
            background: #fff;
        }

        .phc-ignore-btn::before { transform: rotate(45deg); }
        .phc-ignore-btn::after { transform: rotate(-45deg); }

        .phc-block-channel-btn {
            display: inline-block;
            width: 16px;
            height: 16px;
            background: rgba(0, 0, 0, 0.5);
            border: 1px solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            cursor: pointer;
            margin: 0 0 0 5px;
            padding: 0;
            opacity: 0;
            transition: opacity 0.2s, background 0.2s;
            vertical-align: middle;
            position: relative;
            box-sizing: border-box;
        }

        .phc-card:hover .phc-block-channel-btn {
            opacity: 1;
        }

        .phc-block-channel-btn:hover {
            background: #c00;
            border-color: rgba(255, 255, 255, 0.6);
        }

        .phc-block-channel-btn::before,
        .phc-block-channel-btn::after {
            content: '';
            position: absolute;
            left: 50%;
            top: 50%;
            width: 8px;
            height: 1.5px;
            margin: -0.75px 0 0 -4px;
            background: #fff;
        }

        .phc-block-channel-btn::before { transform: rotate(45deg); }
        .phc-block-channel-btn::after { transform: rotate(-45deg); }

        .phc-modal {
            position: fixed !important;
            top: 0 !important;
            left: 0 !important;
            width: 100% !important;
            height: 100% !important;
            background: rgba(0, 0, 0, 0.8) !important;
            z-index: 999998 !important;
            display: none !important;
            align-items: center !important;
            justify-content: center !important;
            visibility: hidden !important;
            pointer-events: none !important;
            font-family: Arial, Helvetica, sans-serif;
        }

        .phc-modal.active {
            display: flex !important;
            visibility: visible !important;
            pointer-events: auto !important;
        }

        .phc-modal-content {
            background: #1a1a1a !important;
            border: 2px solid #333 !important;
            border-radius: 8px !important;
            padding: 20px !important;
            width: 600px !important;
            max-width: calc(100vw - 40px) !important;
            max-height: 80vh !important;
            overflow-y: auto !important;
            box-sizing: border-box !important;
            color: #fff !important;
            z-index: 999999 !important;
            pointer-events: auto !important;
            position: relative !important;
        }

        .phc-modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }

        .phc-modal-header h2 {
            margin: 0;
            font-size: 18px;
            color: #ff9000;
        }

        .phc-modal-close {
            background: #ff4444;
            color: #fff;
            border: none;
            width: 30px;
            height: 30px;
            border-radius: 50%;
            cursor: pointer;
            font-size: 18px;
            line-height: 1;
        }

        .phc-modal-close:hover {
            background: #ff6666;
        }

        .phc-modal-actions {
            margin-bottom: 15px;
            display: flex;
            gap: 10px;
        }

        .phc-modal-actions .phc-btn {
            margin-top: 0;
            width: auto;
        }

        .phc-list {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .phc-list-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px;
            background: #252525;
            margin-bottom: 8px;
            border-radius: 4px;
        }

        .phc-list-item-title {
            flex: 1;
            font-size: 13px;
            margin-right: 10px;
            word-break: break-word;
        }

        .phc-list-item-title a {
            color: #ff9000;
            text-decoration: none;
        }

        .phc-list-item-title a:hover {
            text-decoration: underline;
        }

        .phc-remove-btn {
            background: #ff4444;
            color: #fff;
            border: none;
            padding: 5px 10px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 11px;
        }

        .phc-remove-btn:hover {
            background: #ff6666;
        }

        .phc-empty-list {
            text-align: center;
            color: #888;
            padding: 20px;
        }

        .phc-list-link.phc-support-link,
        .phc-list-link.phc-support-link span {
            color: #ff8fab;
        }

        .phc-list-link.phc-support-link:hover {
            color: #ffb3c6;
        }

        #phc-donate {
            position: fixed;
            bottom: 8px;
            left: 8px;
            width: 250px;
            box-sizing: border-box;
            background: #1a1a1a;
            border: 1px solid #333;
            border-radius: 6px;
            padding: 10px 12px;
            z-index: 9999;
            color: #ddd;
            font-family: Arial, Helvetica, sans-serif;
            font-size: 11px;
            line-height: 1.4;
            text-align: left;
            box-shadow: 0 3px 10px rgba(0,0,0,0.5);
        }

        #phc-donate * {
            box-sizing: border-box;
        }

        #phc-donate h4 {
            margin: 0 18px 4px 0;
            padding: 0;
            font-size: 12px;
            font-weight: bold;
            color: #ff9000;
        }

        #phc-donate p {
            margin: 0 0 8px 0;
            padding: 0;
            color: #aaa;
        }

        .phc-donate-close {
            position: absolute;
            top: 6px;
            right: 8px;
            background: none;
            border: none;
            color: #777;
            font-size: 16px;
            font-family: inherit;
            line-height: 1;
            cursor: pointer;
            padding: 0;
        }

        .phc-donate-close:hover {
            color: #fff;
        }

        .phc-donate-row {
            display: flex;
            gap: 10px;
            align-items: flex-start;
        }

        .phc-donate-links {
            flex: 1;
            display: flex;
            flex-direction: column;
            gap: 5px;
        }

        #phc-donate a.phc-donate-link {
            display: block;
            padding: 4px 7px;
            background: #252525;
            border-radius: 4px;
            color: #ff9000;
            font-weight: bold;
            text-decoration: none;
        }

        #phc-donate a.phc-donate-link:hover {
            background: #303030;
        }

        #phc-donate a.phc-donate-link small {
            display: block;
            font-size: 9px;
            font-weight: normal;
            color: #888;
        }

        .phc-donate-qr {
            flex: 0 0 auto;
            text-align: center;
            font-size: 9px;
            color: #888;
        }

        .phc-donate-qr svg {
            display: block;
            width: 86px;
            height: 86px;
            margin-bottom: 2px;
            border-radius: 3px;
        }
    `);

    // ==================== CRUD operations ====================

    function ignoreVideo(key, title) {
        if (!key || ignoredKeys.has(key)) return;
        ignoredVideos.push({ key, title, url: videoUrl(key), date: new Date().toISOString() });
        GM_setValue('ignoredVideos', ignoredVideos);
        rebuildLookups();
        filterVideos();
    }

    function unignoreVideo(key) {
        ignoredVideos = ignoredVideos.filter(v => v.key !== key);
        GM_setValue('ignoredVideos', ignoredVideos);
        rebuildLookups();
        filterVideos();
        updateIgnoredListModal();
    }

    function blockChannel(key, name) {
        if (!key || blockedKeys.has(key)) return;
        blockedChannels.push({ key, name: name || key, url: key, date: new Date().toISOString() });
        GM_setValue('blockedChannels', blockedChannels);
        rebuildLookups();
        filterVideos();
    }

    function unblockChannel(key) {
        blockedChannels = blockedChannels.filter(c => c.key !== key);
        GM_setValue('blockedChannels', blockedChannels);
        rebuildLookups();
        filterVideos();
        updateBlockedChannelsModal();
    }

    // Adds to the in-memory list only; call saveWatched() afterwards
    function addWatched(key, title, date) {
        if (!key || watchedKeys.has(key)) return false;
        watchedVideos.push({ key, title: title || 'Untitled', url: videoUrl(key), date: date || new Date().toISOString() });
        watchedKeys.add(key);
        return true;
    }

    function saveWatched() {
        GM_setValue('watchedVideos', watchedVideos);
    }

    function unmarkAsWatched(key) {
        watchedVideos = watchedVideos.filter(v => v.key !== key);
        saveWatched();
        rebuildLookups();
        filterVideos();
        updateWatchedListModal();
    }

    // The video open on this page counts as watched
    function markCurrentVideo() {
        const key = currentViewkey();
        if (!key) return;

        const title = document.querySelector('h1.title .inlineFree, h1.title')?.textContent.trim()
            || document.title.replace(/\s*-\s*Pornhub\.com\s*$/i, '').trim();

        if (addWatched(key, title)) saveWatched();
    }

    // ==================== Video DOM buttons ====================

    function addIgnoreButton(card) {
        if (card.querySelector('.phc-ignore-btn')) return;

        const thumb = card.querySelector('.phimage');
        if (!thumb) return;

        const btn = document.createElement('div');
        btn.className = 'phc-ignore-btn';
        btn.title = 'Ignore this video';

        if (getComputedStyle(thumb).position === 'static') thumb.style.position = 'relative';
        thumb.appendChild(btn);
    }

    function addBlockChannelButton(info) {
        const link = info.uploaderLink;
        if (!link || !info.uploaderKey || link.parentElement.querySelector('.phc-block-channel-btn')) return;

        const btn = document.createElement('span');
        btn.className = 'phc-block-channel-btn';
        btn.title = `Block ${info.uploaderName || 'this channel'}`;

        link.insertAdjacentElement('afterend', btn);
    }

    // ==================== Filtering ====================

    // Length limit in seconds, or null while the filter is off or its box is empty
    function durationLimit(enabled, key) {
        return enabled && durationMinutes[key] ? durationMinutes[key] * 60 : null;
    }

    function filterVideos() {
        const current = currentViewkey();
        const shortLimit = durationLimit(hideShort, 'shortMinutes');
        const longLimit = durationLimit(hideLong, 'longMinutes');
        const wordsOn = hideWords && wordMatchers.length > 0;
        const hidden = { ignored: 0, channel: 0, watched: 0, words: 0, short: 0, long: 0 };

        document.querySelectorAll(CARD_SELECTOR).forEach(card => {
            const info = readCard(card);
            // Leave alone cards without a video and the video that is playing right now
            if (!info.key || info.key === current) return;

            card.classList.add('phc-card');

            const isIgnored = ignoredKeys.has(info.key);
            const isChannelBlocked = !!info.uploaderKey && blockedKeys.has(info.uploaderKey);
            // Hidden if the site labels it "Watched" or it is in the script's own history
            const isWatched = info.siteWatched || watchedKeys.has(info.key);
            const isShort = shortLimit !== null && info.duration !== null && info.duration < shortLimit;
            const isLong = longLimit !== null && info.duration !== null && info.duration > longLimit;
            const hasWord = wordsOn && wordMatchers.some(re => re.test(info.fullTitle));

            let reason = null;
            if (isIgnored && hideIgnored)                     reason = 'ignored';
            else if (isChannelBlocked && hideBlockedChannels) reason = 'channel';
            else if (isWatched && hideWatched)                reason = 'watched';
            else if (hasWord)                                 reason = 'words';
            else if (isShort)                                 reason = 'short';
            else if (isLong)                                  reason = 'long';

            card.classList.toggle('phc-hidden', reason !== null);
            if (reason) hidden[reason]++;

            addIgnoreButton(card);
            addBlockChannelButton(info);
        });

        updateStats(hidden);
    }

    // ==================== Thumbnail scale ====================

    // Space left at each window edge by a stretched list: half of the site's own card
    // width, or this when the list has no grid to measure
    const EDGE_FALLBACK = 160;
    // Space between a stretched list and the column next to the player
    const COLUMN_GAP = 16;

    // Lists changed by applyThumbScale, with the width they got
    const scaledLists = new Map();
    const LIST_PROPS = ['grid-template-columns', 'justify-content', 'margin-left', 'width', 'max-width', 'box-sizing', '--phc-scale', '--phc-unscale'];
    // Items moved by fitPinnedItems
    const movedItems = new Set();
    const ITEM_PROPS = ['grid-column-start', 'grid-column-end'];

    // Lists of cards that may be scaled right now
    function scalableLists() {
        const lists = new Set();
        document.querySelectorAll('.phc-card').forEach(card => {
            const list = card.parentElement;
            if (list && !lists.has(list) && !list.closest(NO_SCALE_SELECTOR)) lists.add(list);
        });
        return lists;
    }

    // Stretches a list under the player across the window, leaving `edge` pixels at
    // each side, or up to the column next to the player when that column reaches down
    // this far. A list never gets narrower than the site made it
    function stretchList(list, edge) {
        const rect = list.getBoundingClientRect();
        if (!rect.width) return;

        const left = Math.min(edge, rect.left);
        let right = document.documentElement.clientWidth - edge;
        document.querySelectorAll(RIGHT_COLUMN_SELECTOR).forEach(el => {
            const column = el.getBoundingClientRect();
            if (column.height && column.bottom > rect.top && column.left > rect.left) {
                right = Math.min(right, column.left - COLUMN_GAP);
            }
        });
        right = Math.max(right, rect.right);

        const width = right - left;
        if (width <= rect.width + 1) return;

        const margin = parseFloat(getComputedStyle(list).marginLeft) || 0;
        list.style.setProperty('margin-left', `${margin + left - rect.left}px`, 'important');
        list.style.setProperty('width', `${width}px`, 'important');
        list.style.setProperty('max-width', 'none', 'important');
        list.style.setProperty('box-sizing', 'border-box', 'important');
    }

    // Picks the number of columns that gives cards closest to the chosen size, then
    // sizes the cards so that a row fills the list exactly
    function fitColumns(room, column, gap) {
        const scaleFor = n => (room - (n - 1) * gap) / n / column;

        let n = Math.max(1, Math.round((room + gap) / (column * thumbScale + gap)));
        while (n > 1 && scaleFor(n) < 1) n--;
        while (scaleFor(n) > SCALE_MAX && scaleFor(n + 1) >= 1) n++;

        const scale = scaleFor(n);
        return scale >= 1 ? { n, scale } : null;
    }

    // The site pins some items to a grid column: on the home page the ad block of the
    // first row sits in column 4. With fewer columns such an item would add a narrow
    // extra column that the cards flow into too, so it moves into the last column
    function fitPinnedItems(list, columns) {
        [...list.children].forEach(item => {
            const style = getComputedStyle(item);
            const start = parseInt(style.gridColumnStart, 10);
            if (!(start > 0)) return;

            const end = style.gridColumnEnd;
            const endLine = parseInt(end, 10);
            const span = end.startsWith('span') ? (parseInt(end.slice(4), 10) || 1) : (endLine > start ? endLine - start : 1);
            if (start + span - 1 <= columns) return;

            const width = Math.min(span, columns);
            item.style.setProperty('grid-column-start', String(columns - width + 1), 'important');
            item.style.setProperty('grid-column-end', `span ${width}`, 'important');
            movedItems.add(item);
        });
    }

    function applyThumbScale() {
        const on = scaleThumbs;
        const root = document.documentElement;

        root.classList.toggle('phc-scaling', on);
        root.style.setProperty('--phc-scale', String(thumbScale));
        root.style.setProperty('--phc-unscale', String(1 / thumbScale));

        scaledLists.forEach((width, list) => {
            listResizeObserver.unobserve(list);
            LIST_PROPS.forEach(prop => list.style.removeProperty(prop));
        });
        scaledLists.clear();
        movedItems.forEach(item => ITEM_PROPS.forEach(prop => item.style.removeProperty(prop)));
        movedItems.clear();
        if (!on) return;

        scalableLists().forEach(list => {
            // The site centres its lists: bigger cards start at the left edge instead
            list.style.setProperty('justify-content', 'flex-start', 'important');

            // The column size is read before the list is stretched
            const style = getComputedStyle(list);
            const isGrid = /grid/.test(style.display);
            const column = isGrid ? parseFloat(style.gridTemplateColumns) : 0;
            const gap = parseFloat(style.columnGap) || 0;

            if (list.closest(STRETCH_SELECTOR)) stretchList(list, column ? Math.round(column / 2) : EDGE_FALLBACK);
            scaledLists.set(list, list.getBoundingClientRect().width);

            // Grid columns are resized to fit the zoomed cards. Other layouts make
            // room on their own and use the chosen size as it is
            if (!column) return;
            // 1px spare keeps rounding from pushing the last card out of the row
            const room = list.clientWidth - parseFloat(style.paddingLeft) - parseFloat(style.paddingRight) - 1;
            const fit = fitColumns(room, column, gap);
            if (!fit) return;

            list.style.setProperty('--phc-scale', String(fit.scale));
            list.style.setProperty('--phc-unscale', String(1 / fit.scale));
            list.style.setProperty('grid-template-columns', `repeat(${fit.n}, ${Math.floor(column * fit.scale * 100) / 100}px)`, 'important');
            fitPinnedItems(list, fit.n);
        });

        scaledLists.forEach((width, list) => listResizeObserver.observe(list));
    }

    let scaleTimer = null;

    function scheduleThumbScale(delay = 150) {
        clearTimeout(scaleTimer);
        scaleTimer = setTimeout(applyThumbScale, delay);
    }

    // A list that appears later (another tab under the player) or changes its width
    // is measured again. Changes made by applyThumbScale itself are ignored
    const listResizeObserver = new ResizeObserver(entries => {
        if (!scaleThumbs) return;
        const changed = entries.some(entry => {
            const width = scaledLists.get(entry.target);
            return width === undefined || Math.abs(entry.target.getBoundingClientRect().width - width) > 1;
        });
        if (changed) scheduleThumbScale();
    });

    let filterTimer = null;

    function scheduleFilter(delay = 50) {
        clearTimeout(filterTimer);
        filterTimer = setTimeout(filterVideos, delay);
    }

    function updateStats(hidden) {
        const counts = {
            'phc-cnt-total': masterDefs().reduce((sum, t) => sum + hidden[t.reason], 0),
            'phc-cnt-hidden': Object.values(hidden).reduce((sum, n) => sum + n, 0),
            'phc-link-ignored-count':  ignoredVideos.length,
            'phc-link-channels-count': blockedChannels.length,
            'phc-link-watched-count':  watchedVideos.length,
        };
        toggleDefs.forEach(t => { counts[t.countId] = hidden[t.reason]; });

        for (const [id, value] of Object.entries(counts)) {
            const el = document.getElementById(id);
            if (el) el.textContent = value;
        }
    }

    // ==================== Modals ====================

    function closeModal(modalId) {
        const modal = document.getElementById(modalId);
        if (modal) {
            modal.style.setProperty('display', 'none', 'important');
            modal.style.setProperty('visibility', 'hidden', 'important');
            modal.style.setProperty('pointer-events', 'none', 'important');
            modal.classList.remove('active');
        }
    }

    function openModal(modalId) {
        const modal = document.getElementById(modalId);
        if (!modal) return;

        modal.style.setProperty('display', 'flex', 'important');
        modal.style.setProperty('visibility', 'visible', 'important');
        modal.style.setProperty('opacity', '1', 'important');
        modal.style.setProperty('pointer-events', 'auto', 'important');
        modal.querySelector('.phc-modal-content')?.style.setProperty('pointer-events', 'auto', 'important');
        modal.classList.add('active');

        if (modalId === 'phc-ignored-modal') updateIgnoredListModal();
        else if (modalId === 'phc-blocked-channels-modal') updateBlockedChannelsModal();
        else if (modalId === 'phc-watched-modal') updateWatchedListModal();
    }

    // Builds an empty list window with a close button and a "Clear list" button
    function createListModal(modalId, listId, title, clearList) {
        const modal = document.createElement('div');
        modal.className = 'phc-modal';
        modal.id = modalId;
        modal.innerHTML = `
            <div class="phc-modal-content">
                <div class="phc-modal-header">
                    <h2>${title}</h2>
                    <button class="phc-modal-close">×</button>
                </div>
                <div class="phc-modal-actions">
                    <button class="phc-btn phc-clear-btn" style="background: #ff4444;">🗑️ Clear list</button>
                </div>
                <ul class="phc-list" id="${listId}"></ul>
            </div>
        `;

        document.body.appendChild(modal);

        modal.querySelector('.phc-modal-close').addEventListener('click', (e) => {
            e.preventDefault();
            e.stopPropagation();
            closeModal(modalId);
        });

        modal.addEventListener('click', (e) => {
            if (e.target === modal) closeModal(modalId);
        });

        modal.querySelector('.phc-clear-btn').addEventListener('click', clearList);

        closeModal(modalId);
        return modal;
    }

    function createIgnoredListModal() {
        createListModal('phc-ignored-modal', 'phc-ignored-list', '📝 Ignored videos', () => {
            if (confirm(`Clear the ignored videos list?\n\nEntries in the list: ${ignoredVideos.length}`)) {
                ignoredVideos = [];
                GM_setValue('ignoredVideos', ignoredVideos);
                rebuildLookups();
                filterVideos();
                updateIgnoredListModal();
            }
        });
    }

    function createBlockedChannelsModal() {
        createListModal('phc-blocked-channels-modal', 'phc-blocked-channels-list', '🚫 Blocked channels', () => {
            if (confirm(`Clear the blocked channels list?\n\nEntries in the list: ${blockedChannels.length}`)) {
                blockedChannels = [];
                GM_setValue('blockedChannels', blockedChannels);
                rebuildLookups();
                filterVideos();
                updateBlockedChannelsModal();
            }
        });
    }

    function createWatchedListModal() {
        const modal = createListModal('phc-watched-modal', 'phc-watched-list', '👁️ Watched videos', () => {
            if (confirm(`Clear the watched videos list?\n\nEntries in the list: ${watchedVideos.length}`)) {
                watchedVideos = [];
                saveWatched();
                rebuildLookups();
                filterVideos();
                updateWatchedListModal();
            }
        });

        const actions = modal.querySelector('.phc-modal-actions');

        const fileInput = document.createElement('input');
        fileInput.type = 'file';
        fileInput.accept = '.csv,.txt,.json';
        fileInput.style.display = 'none';
        modal.querySelector('.phc-modal-content').appendChild(fileInput);

        const importBtn = document.createElement('button');
        importBtn.className = 'phc-btn';
        importBtn.style.background = '#ff9800';
        importBtn.textContent = '📥 Import from history';
        importBtn.addEventListener('click', () => fileInput.click());
        actions.appendChild(importBtn);

        const exportBtn = document.createElement('button');
        exportBtn.className = 'phc-btn';
        exportBtn.style.background = '#4CAF50';
        exportBtn.textContent = '📤 Export';
        exportBtn.addEventListener('click', () => {
            const blob = new Blob([JSON.stringify(watchedVideos, null, 2)], { type: 'application/json' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'pornhub_watched.json';
            a.click();
            setTimeout(() => URL.revokeObjectURL(url), 1000);
        });
        actions.appendChild(exportBtn);

        fileInput.addEventListener('change', (e) => {
            const file = e.target.files[0];
            if (!file) return;

            const reader = new FileReader();
            reader.onload = (event) => {
                const { imported, skipped } = importWatched(String(event.target.result || ''));

                saveWatched();
                rebuildLookups();
                filterVideos();
                updateWatchedListModal();
                alert(`Import complete!\n\nAdded: ${imported}\nSkipped (duplicates): ${skipped}\nTotal watched: ${watchedVideos.length}`);

                fileInput.value = '';
            };

            reader.readAsText(file);
        });
    }

    // Accepts this script's own export (JSON) or any text with video links,
    // such as a browser history export (CSV or TXT)
    function importWatched(text) {
        let entries = [];

        try {
            const data = JSON.parse(text);
            if (Array.isArray(data)) {
                entries = data.map(v => ({
                    key: (typeof v?.key === 'string' && /^[A-Za-z0-9]+$/.test(v.key)) ? v.key : extractViewkey(v?.url),
                    title: typeof v?.title === 'string' ? v.title : null,
                    date: (typeof v?.date === 'string' && !isNaN(Date.parse(v.date))) ? v.date : null,
                }));
            }
        } catch (e) {
            // Not JSON: look for links below
        }

        if (!entries.length) {
            for (const m of text.matchAll(/[?&]viewkey=([A-Za-z0-9]+)/g)) {
                entries.push({ key: m[1], title: null, date: null });
            }
        }

        let imported = 0, skipped = 0;
        entries.forEach(entry => {
            if (!entry.key) return;
            if (addWatched(entry.key, entry.title || 'Imported from history', entry.date)) imported++;
            else skipped++;
        });

        return { imported, skipped };
    }

    // ==================== Modal content updates ====================

    function renderList(listId, items, render, onRemove) {
        const list = document.getElementById(listId);
        if (!list) return null;

        if (items.length === 0) {
            list.innerHTML = '<div class="phc-empty-list">The list is empty</div>';
            return list;
        }

        list.innerHTML = items.map(item => `
            <li class="phc-list-item">
                <div class="phc-list-item-title">
                    <a href="${escapeHtml(item.url)}" target="_blank">${escapeHtml(render(item))}</a>
                </div>
                <button class="phc-remove-btn" data-key="${escapeHtml(item.key)}">Remove</button>
            </li>
        `).join('');

        list.querySelectorAll('.phc-remove-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                e.preventDefault();
                e.stopPropagation();
                onRemove(btn.getAttribute('data-key'));
            });
        });

        return list;
    }

    function updateIgnoredListModal() {
        const modal = document.getElementById('phc-ignored-modal');
        if (!modal) return;

        modal.querySelector('h2').textContent = `📝 Ignored videos (${ignoredVideos.length})`;
        renderList('phc-ignored-list', ignoredVideos, v => v.title, unignoreVideo);
    }

    function updateBlockedChannelsModal() {
        const modal = document.getElementById('phc-blocked-channels-modal');
        if (!modal) return;

        modal.querySelector('h2').textContent = `🚫 Blocked channels (${blockedChannels.length})`;
        renderList('phc-blocked-channels-list', blockedChannels, c => c.name, unblockChannel);
    }

    function updateWatchedListModal() {
        const modal = document.getElementById('phc-watched-modal');
        if (!modal) return;

        modal.querySelector('h2').textContent = `👁️ Watched videos (${watchedVideos.length})`;

        const recent = [...watchedVideos].sort((a, b) => new Date(b.date) - new Date(a.date)).slice(0, 100);
        const list = renderList('phc-watched-list', recent, v => v.title, unmarkAsWatched);

        if (list && watchedVideos.length > 100) {
            list.insertAdjacentHTML('beforeend', `<div class="phc-empty-list">...and ${watchedVideos.length - 100} more</div>`);
        }
    }

    // ==================== Control panel ====================

    function updatePanelView() {
        const body = document.getElementById('phc-panel-body');
        const btn = document.querySelector('.phc-collapse-btn');
        const expanded = panelState === 1;

        if (body) body.style.display = expanded ? 'block' : 'none';
        if (btn) {
            btn.textContent = expanded ? '▼' : '▲';
            btn.title = expanded ? 'Collapse' : 'Expand';
        }
    }

    function syncTogglesUI() {
        toggleDefs.forEach(t => {
            const cb = document.getElementById(t.id);
            if (cb) cb.checked = t.get();

            const input = t.duration && document.getElementById(t.duration.inputId);
            if (input && document.activeElement !== input) {
                input.value = durationMinutes[t.duration.valueKey] || '';
            }
        });
        updateMasterToggle();
        updateFilterOptionsUI();
    }

    // A length box shows only while its filter is on; presets only while the box is
    // empty. The word box shows while its filter is on, with the unused suggestions
    function updateFilterOptionsUI() {
        toggleDefs.forEach(t => {
            if (!t.duration) return;
            const input = document.getElementById(t.duration.inputId);
            const presets = document.getElementById(t.duration.presetsId);
            if (!input || !presets) return;

            const on = t.get();
            input.parentElement.style.display = on ? '' : 'none';
            presets.style.display = on && input.value === '' ? '' : 'none';
        });

        const editor = document.getElementById('phc-words-editor');
        const suggestions = document.getElementById('phc-word-suggestions');
        if (editor) editor.style.display = hideWords ? '' : 'none';
        if (suggestions) suggestions.style.display = suggestions.children.length ? '' : 'none';
    }

    // Title words as tags in the box, each with a remove button, then the suggestions
    // that are not in the list yet
    function renderWords() {
        const box = document.getElementById('phc-words-box');
        const input = document.getElementById('phc-words-input');
        const suggestions = document.getElementById('phc-word-suggestions');
        if (!box || !input || !suggestions) return;

        box.querySelectorAll('.phc-word').forEach(el => el.remove());
        titleWords.forEach(word => {
            const tag = document.createElement('span');
            tag.className = 'phc-word';
            tag.dataset.word = word;

            const text = document.createElement('span');
            text.className = 'phc-word-text';
            text.textContent = word;

            const remove = document.createElement('button');
            remove.type = 'button';
            remove.className = 'phc-word-x';
            remove.title = 'Remove';
            remove.textContent = '×';

            tag.append(text, remove);
            box.insertBefore(tag, input);
        });

        suggestions.textContent = '';
        // Not offered again when the list has the same word, with or without asterisks
        const bare = word => word.replace(/\*/g, '');
        const added = new Set(titleWords.map(bare));
        WORD_SUGGESTIONS.filter(word => !added.has(bare(word))).forEach(word => {
            const btn = document.createElement('button');
            btn.type = 'button';
            btn.className = 'phc-word-sugg';
            btn.dataset.word = word;
            btn.textContent = `+ ${word}`;
            btn.title = 'Add to the list';
            suggestions.appendChild(btn);
        });

        updateFilterOptionsUI();
    }

    function setTitleWords(list) {
        titleWords = cleanWords(list);
        GM_setValue('titleWords', titleWords);
        rebuildWordMatchers();
        renderWords();
        filterVideos();
    }

    function setDurationMinutes(def, text) {
        const value = validMinutes(parseInt(text, 10));
        durationMinutes[def.duration.valueKey] = value;
        GM_setValue(def.duration.valueKey, value);
        updateFilterOptionsUI();
        scheduleFilter(150);
    }

    function syncScaleUI() {
        const cb = document.getElementById('phc-scale-toggle');
        const row = document.getElementById('phc-scale-row');
        const slider = document.getElementById('phc-scale-slider');
        const value = document.getElementById('phc-scale-value');

        if (cb) cb.checked = scaleThumbs;
        if (row) row.style.display = scaleThumbs ? '' : 'none';
        if (slider) slider.value = thumbScale;
        if (value) value.textContent = scaleThumbs ? `×${thumbScale.toFixed(1)}` : '';
    }

    // The toggles that "All" switches: everything except the length and word filters
    function masterDefs() {
        return toggleDefs.filter(t => !t.duration && !t.words);
    }

    function updateMasterToggle() {
        const master = document.getElementById('phc-master-toggle');
        if (!master) return;

        const defs = masterDefs();
        const on = defs.filter(t => t.get()).length;
        master.checked = on === defs.length;
        master.indeterminate = on > 0 && on < defs.length;
    }

    function createControlPanel() {
        const toggleHtml = t => `
            <div class="phc-toggle">
                <input type="checkbox" id="${t.id}" ${t.get() ? 'checked' : ''}>
                <label for="${t.id}">${t.label}</label>
                ${t.duration ? `
                    <span class="phc-minutes">
                        <input type="text" id="${t.duration.inputId}" inputmode="numeric" maxlength="4" autocomplete="off"
                               value="${durationMinutes[t.duration.valueKey] || ''}">min
                    </span>` : ''}
                <span class="phc-count" id="${t.countId}">0</span>
            </div>
            ${t.duration ? `
                <div class="phc-presets" id="${t.duration.presetsId}">
                    ${t.duration.presets.map(m => `<button type="button" class="phc-preset" data-minutes="${m}" title="${m} minutes">${m}m</button>`).join('')}
                </div>` : ''}
        `;

        const togglesHtml = masterDefs().map(toggleHtml).join('');
        const durationHtml = toggleDefs.filter(t => t.duration).map(toggleHtml).join('');
        const wordsHtml = toggleHtml(toggleDefs.find(t => t.words));

        const panel = document.createElement('div');
        panel.id = 'phc-control-panel';
        panel.innerHTML = `
            <h3>
                <span>🎬 Pornhub Filter</span>
                <button class="phc-collapse-btn">▼</button>
            </h3>
            <div id="phc-panel-body">
                <div id="phc-toggles-block">
                    <div class="phc-head-row">
                        <span>Hide</span>
                        <span>Hidden</span>
                    </div>
                    <div class="phc-toggle phc-toggle_master">
                        <input type="checkbox" id="phc-master-toggle">
                        <label for="phc-master-toggle">All</label>
                        <span class="phc-count" id="phc-cnt-total">0</span>
                    </div>
                    ${togglesHtml}
                    <div id="phc-duration-block">${durationHtml}</div>
                    <div id="phc-words-block">
                        ${wordsHtml}
                        <div id="phc-words-editor">
                            <div class="phc-words-box" id="phc-words-box">
                                <input type="text" id="phc-words-input" maxlength="${WORD_MAX_LENGTH}" autocomplete="off" spellcheck="false"
                                       placeholder="Add a word, Enter"
                                       title="A word hides videos with that whole word in the title. word* also matches longer words (farting), *word* matches it anywhere. Commas add several at once">
                            </div>
                            <div class="phc-word-suggestions" id="phc-word-suggestions"></div>
                        </div>
                    </div>
                    <div class="phc-total-row">
                        <span>Total hidden</span>
                        <span class="phc-count" id="phc-cnt-hidden">0</span>
                    </div>
                </div>
                <div id="phc-view-block">
                    <div class="phc-toggle">
                        <input type="checkbox" id="phc-scale-toggle">
                        <label for="phc-scale-toggle">Thumbnail size</label>
                        <span class="phc-scale-value" id="phc-scale-value"></span>
                    </div>
                    <div class="phc-scale-row" id="phc-scale-row">
                        <span>×${SCALE_MIN}</span>
                        <input type="range" id="phc-scale-slider" min="${SCALE_MIN}" max="${SCALE_MAX}" step="${SCALE_STEP}">
                        <span>×${SCALE_MAX}</span>
                    </div>
                </div>
                <div id="phc-lists-block">
                    <button class="phc-list-link" id="phc-show-ignored">Ignored videos<span id="phc-link-ignored-count">${ignoredVideos.length}</span></button>
                    <button class="phc-list-link" id="phc-show-blocked-channels">Blocked channels<span id="phc-link-channels-count">${blockedChannels.length}</span></button>
                    <button class="phc-list-link" id="phc-show-watched">Watched<span id="phc-link-watched-count">${watchedVideos.length}</span></button>
                    <button class="phc-list-link phc-support-link" id="phc-show-donate">Support the project<span>♥</span></button>
                </div>
            </div>
        `;

        document.body.appendChild(panel);

        panel.querySelector('.phc-collapse-btn').addEventListener('click', (e) => {
            e.stopPropagation();
            panelState = panelState === 1 ? 0 : 1;
            GM_setValue('panelState', panelState);
            updatePanelView();
        });

        toggleDefs.forEach(t => {
            document.getElementById(t.id).addEventListener('change', (e) => {
                toggleKeys[t.key](e.target.checked);
                GM_setValue(t.key, e.target.checked);
                updateMasterToggle();
                updateFilterOptionsUI();
                filterVideos();
            });

            if (!t.duration) return;
            const input = document.getElementById(t.duration.inputId);

            // Whole minutes only, without leading zeros
            input.addEventListener('input', () => {
                const digits = input.value.replace(/\D/g, '').replace(/^0+/, '').slice(0, 4);
                if (digits !== input.value) input.value = digits;
                setDurationMinutes(t, digits);
            });

            // Typing must not reach the site's keyboard shortcuts (the player seeks on digits)
            ['keydown', 'keyup', 'keypress'].forEach(type => input.addEventListener(type, e => e.stopPropagation()));

            document.getElementById(t.duration.presetsId).addEventListener('click', (e) => {
                const btn = e.target.closest('.phc-preset');
                if (!btn) return;
                input.value = btn.dataset.minutes;
                setDurationMinutes(t, input.value);
            });
        });

        const wordsBox = document.getElementById('phc-words-box');
        const wordsInput = document.getElementById('phc-words-input');

        // Enter turns the typed text into tags; commas separate several words
        wordsInput.addEventListener('keydown', (e) => {
            e.stopPropagation();
            if (e.key !== 'Enter' || e.isComposing) return;
            e.preventDefault();
            const added = wordsInput.value.split(',').map(normalizeWord).filter(Boolean);
            wordsInput.value = '';
            if (added.length) setTitleWords([...titleWords, ...added]);
        });
        // Typing must not reach the site's keyboard shortcuts
        ['keyup', 'keypress'].forEach(type => wordsInput.addEventListener(type, e => e.stopPropagation()));

        wordsBox.addEventListener('click', (e) => {
            const remove = e.target.closest('.phc-word-x');
            if (remove) {
                const word = remove.parentElement.dataset.word;
                setTitleWords(titleWords.filter(w => w !== word));
                return;
            }
            if (!e.target.closest('.phc-word')) wordsInput.focus();
        });

        document.getElementById('phc-word-suggestions').addEventListener('click', (e) => {
            const btn = e.target.closest('.phc-word-sugg');
            if (btn) setTitleWords([...titleWords, btn.dataset.word]);
        });

        document.getElementById('phc-scale-toggle').addEventListener('change', (e) => {
            scaleThumbs = e.target.checked;
            GM_setValue('scaleThumbs', scaleThumbs);
            syncScaleUI();
            applyThumbScale();
        });

        const slider = document.getElementById('phc-scale-slider');
        slider.addEventListener('input', () => {
            thumbScale = validScale(slider.value);
            syncScaleUI();
            applyThumbScale();
        });
        // Saved once the slider is let go, not on every step of a drag
        slider.addEventListener('change', () => GM_setValue('thumbScale', thumbScale));

        document.getElementById('phc-master-toggle').addEventListener('change', (e) => {
            const on = e.target.checked;
            masterDefs().forEach(t => {
                toggleKeys[t.key](on);
                GM_setValue(t.key, on);
                const cb = document.getElementById(t.id);
                if (cb) cb.checked = on;
            });
            updateMasterToggle();
            updateFilterOptionsUI();
            filterVideos();
        });

        document.getElementById('phc-show-ignored').addEventListener('click', () => openModal('phc-ignored-modal'));
        document.getElementById('phc-show-blocked-channels').addEventListener('click', () => openModal('phc-blocked-channels-modal'));
        document.getElementById('phc-show-watched').addEventListener('click', () => openModal('phc-watched-modal'));
        document.getElementById('phc-show-donate').addEventListener('click', showDonateBanner);

        updateMasterToggle();
        renderWords();
        syncScaleUI();
        updatePanelView();
    }

    // ==================== Donate banner ====================

    function showDonateBanner() {
        if (document.getElementById('phc-donate')) return;

        const linksHtml = donateLinks.map(l => `
            <a class="phc-donate-link" href="${l.url}" target="_blank" rel="noopener">${l.label}<small>${l.note}</small></a>
        `).join('');

        const banner = document.createElement('div');
        banner.id = 'phc-donate';
        banner.innerHTML = `
            <button class="phc-donate-close" title="Close">×</button>
            <h4>♥ Enjoying Pornhub Cleaner?</h4>
            <p>It's free and kept up to date in my spare time. If it saves you some scrolling, consider buying me a coffee.</p>
            <div class="phc-donate-row">
                <div class="phc-donate-links">${linksHtml}</div>
                <div class="phc-donate-qr">
                    <svg viewBox="-2 -2 33 33" shape-rendering="crispEdges"><rect x="-2" y="-2" width="33" height="33" fill="#fff"/><path d="${DONATE_QR_PATH}" fill="#000"/></svg>
                    Monobank
                </div>
            </div>
        `;

        document.body.appendChild(banner);

        // Closing or following any link postpones the next showing by a full interval
        const dismiss = () => {
            donateLastShown = Date.now();
            GM_setValue('donateLastShown', donateLastShown);
        };

        banner.querySelector('.phc-donate-close').addEventListener('click', () => {
            dismiss();
            hideDonateBanner();
        });
        banner.querySelectorAll('.phc-donate-link').forEach(a => a.addEventListener('click', dismiss));
    }

    function hideDonateBanner() {
        document.getElementById('phc-donate')?.remove();
    }

    function maybeShowDonateBanner() {
        if (Date.now() - donateLastShown >= DONATE_INTERVAL) showDonateBanner();
    }

    // ==================== Event delegates ====================

    // The cards carry the site's own click handlers (previews, pop-ups), so the
    // buttons are handled on window in the capture phase, before the site sees them
    function installButtonDelegate() {
        const BUTTONS = '.phc-ignore-btn, .phc-block-channel-btn';

        ['pointerdown', 'mousedown', 'pointerup', 'mouseup', 'auxclick'].forEach(type => {
            window.addEventListener(type, (e) => {
                if (e.target.closest?.(BUTTONS)) e.stopImmediatePropagation();
            }, true);
        });

        window.addEventListener('click', (e) => {
            const btn = e.target.closest?.(BUTTONS);
            if (!btn) return;

            e.preventDefault();
            e.stopImmediatePropagation();

            const card = btn.closest(CARD_SELECTOR);
            if (!card) return;

            const info = readCard(card);
            if (btn.classList.contains('phc-ignore-btn')) ignoreVideo(info.key, info.title);
            else blockChannel(info.uploaderKey, info.uploaderName);
        }, true);
    }

    // Opening a video from a card (left or middle click) marks it as watched
    function installWatchDelegate() {
        const onOpen = (e) => {
            if (e.type === 'click' ? e.button !== 0 : e.button !== 1) return;

            const link = e.target.closest?.('a[href*="viewkey="]');
            const card = link?.closest('.phc-card');
            if (!card) return;

            const info = readCard(card);
            if (addWatched(info.key, info.title)) saveWatched();
            scheduleFilter(100);
        };

        window.addEventListener('click', onOpen, true);
        window.addEventListener('auxclick', onOpen, true);
    }

    // ==================== DOM observer ====================

    function observeVideoList() {
        const WATCH = `${CARD_SELECTOR}, ${SITE_WATCHED_SELECTOR}`;

        const observer = new MutationObserver((mutations) => {
            for (const mutation of mutations) {
                for (const node of mutation.addedNodes) {
                    if (node.nodeType === 1 && (node.matches(WATCH) || node.querySelector(WATCH))) {
                        scheduleFilter();
                        // New or moved cards may belong to a list that isn't sized yet
                        if (scaleThumbs) scheduleThumbScale();
                        return;
                    }
                    // Anything else added to a resized list (an ad block) may be pinned to a column
                    if (node.nodeType === 1 && scaleThumbs && scaledLists.has(mutation.target)) {
                        scheduleThumbScale();
                        return;
                    }
                }
            }
        });

        observer.observe(document.body, { childList: true, subtree: true });

        window.addEventListener('scroll', () => scheduleFilter(100), { passive: true });
        // Column widths depend on the window size
        window.addEventListener('resize', () => { if (scaleThumbs) scheduleThumbScale(); });
    }

    // ==================== Data cleanup ====================

    // Drops entries without a key and repeated keys
    function cleanupList(name, list) {
        const seen = new Set();
        const cleaned = list.filter(item => {
            if (!item || !item.key || seen.has(item.key)) return false;
            seen.add(item.key);
            return true;
        });

        if (cleaned.length !== list.length) {
            GM_setValue(name, cleaned);
            console.log(`[PH Cleaner] Cleanup ${name}: ${list.length} → ${cleaned.length}`);
        }
        return cleaned;
    }

    // ==================== Initialization ====================

    function init() {
        ignoredVideos = cleanupList('ignoredVideos', ignoredVideos);
        blockedChannels = cleanupList('blockedChannels', blockedChannels);
        watchedVideos = cleanupList('watchedVideos', watchedVideos);
        rebuildLookups();
        markCurrentVideo();
        createControlPanel();
        createIgnoredListModal();
        createBlockedChannelsModal();
        createWatchedListModal();
        filterVideos();
        applyThumbScale();
        installButtonDelegate();
        installWatchDelegate();
        observeVideoList();
        maybeShowDonateBanner();
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }

})();