Greasy Fork

Greasy Fork is available in English.

YouTube Master Control v1.2.0 The ultimate YouTube audio & video tool

终极YouTube音视频工具!功能:音频增强、A-B循环、屏幕录制(直播/点播)、速度控制(0.1x-5.0x)、视频缩放与旋转、视频质量锁定、广告拦截、截图、主题定制和字幕下载。

当前为 2025-12-15 提交的版本,查看 最新版本

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Greasemonkey 油猴子Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Userscripts ,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展后才能安装此脚本。

(我已经安装了用户脚本管理器,让我安装!)

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

(我已经安装了用户样式管理器,让我安装!)

// ==UserScript==
// @name         YouTube Master Control v1.2.0 The ultimate YouTube audio & video tool
// @name:pt-BR   YouTube Master Control v1.2.0 The ultimate YouTube audio & video tool
// @name:es      YouTube Master Control v1.2.0 The ultimate YouTube audio & video tool
// @name:fr      YouTube Master Control v1.2.0 The ultimate YouTube audio & video tool
// @name:de      YouTube Master Control v1.2.0 The ultimate YouTube audio & video tool
// @name:it      YouTube Master Control v1.2.0 The ultimate YouTube audio & video tool
// @name:ru      YouTube Master Control v1.2.0 The ultimate YouTube audio & video tool
// @name:zh-CN   YouTube Master Control v1.2.0 The ultimate YouTube audio & video tool
// @name:ja      YouTube Master Control v1.2.0 The ultimate YouTube audio & video tool
// @name:ko      YouTube Master Control v1.2.0 The ultimate YouTube audio & video tool
// @name:hi      YouTube Master Control v1.2.0 The ultimate YouTube audio & video tool
// @name:id      YouTube Master Control v1.2.0 The ultimate YouTube audio & video tool
// @namespace    http://tampermonkey.net/
// @version      1.2.0
// @description  The ultimate YouTube audio & video tool! Features: Audio Booster, A-B Loop, Screen Recorder (Live & VOD), Speed Control (0.1x-5.0x), Video Zoom & Rotate, Video Quality Locker, Adblock, Screenshot, Resizable Interface, Theme Customization, and Subtitle Downloader.
// @description:pt-BR A melhor ferramenta de áudio e vídeo para YouTube! Recursos: Reforço de Áudio, Loop A-B, Gravação de Vídeo (Lives/VOD), Controle de Velocidade (0.1x-5.0x), Zoom e Rotação de Vídeo, Travar Qualidade, Adblock, Captura de Tela, Tema Personalizável e Download de Legendas.
// @description:es    ¡La mejor herramienta de audio y video para YouTube! Características: Refuerzo de Audio, Bucle A-B, Grabación de Pantalla (En vivo/VOD), Control de Velocidad (0.1x-5.0x), Zoom y Rotación de Video, Bloqueo de Calidad, Adblock, Captura de Pantalla, Tema Personalizable y Descarga de Subtítulos.
// @description:fr    L'outil audio et vidéo ultime pour YouTube ! Fonctionnalités : Amplificateur audio, Boucle A-B, Enregistrement d'écran (Live/VOD), Contrôle de vitesse (0.1x-5.0x), Zoom et Rotation vidéo, Verrouillage qualité, Adblock, Capture d'écran, Thème personnalisable et Téléchargement de sous-titres.
// @description:de    Das ultimative YouTube-Audio- & Videotool! Funktionen: Audio-Verstärker, A-B-Loop, Bildschirmaufnahme (Live/VOD), Geschwindigkeitssteuerung (0.1x-5.0x), Video-Zoom & Drehung, Qualitäts-Sperre, Werbeblocker, Screenshot, Anpassbares Design und Untertitel-Download.
// @description:it    Lo strumento audio e video definitivo per YouTube! Funzioni: Amplificatore Audio, Loop A-B, Registrazione Schermo (Live/VOD), Controllo Velocità (0.1x-5.0x), Zoom e Rotazione Video, Blocco Qualità, Adblock, Screenshot, Tema Personalizzabile e Download Sottotitoli.
// @description:ru    Ультимативный инструмент для аудио и видео на YouTube! Функции: Усиление звука, Петля A-B, Запись экрана (Live/VOD), Контроль скорости (0.1x-5.0x), Зум и Поворот видео, Блокировка качества, Блокировка рекламы, Скриншот, Настраиваемая тема и Скачивание субтитров.
// @description:zh-CN 终极YouTube音视频工具!功能:音频增强、A-B循环、屏幕录制(直播/点播)、速度控制(0.1x-5.0x)、视频缩放与旋转、视频质量锁定、广告拦截、截图、主题定制和字幕下载。
// @description:ja    究極のYouTubeオーディオ&ビデオツール!機能:オーディオブースター、A-Bループ、画面録画(ライブ/VOD)、速度制御(0.1x-5.0x)、ビデオズーム&回転、品質ロック、広告ブロック、スクリーンショット、テーマのカスタマイズ、字幕ダウンロード。
// @description:ko    최고의 YouTube 오디오 및 비디오 도구! 기능: 오디오 부스터, A-B 루프, 화면 녹화 (라이브/VOD), 속도 제어 (0.1x-5.0x), 비디오 확대/축소 및 회전, 화질 잠금, 광고 차단, 스크린샷, 테마 사용자 정의 및 자막 다운로드.
// @description:hi    अंतिम यूट्यूब ऑडियो और वीडियो उपकरण! विशेषताएं: ऑडियो बूस्टर, ए-बी लूप, स्क्रीन रिकॉर्डिंग (लाइव/वीओडी), गति नियंत्रण (0.1x-5.0x), वीडियो ज़ूम और रोटेशन, गुणवत्ता लॉकर, ऐडब्लॉक, स्क्रीनशॉट, थीम अनुकूलन और उपशीर्षक डाउनलोड।
// @description:id    Alat audio & video YouTube terbaik! Fitur: Penguat Audio, Loop A-B, Perekaman Layar (Live/VOD), Kontrol Kecepatan (0.1x-5.0x), Zoom & Rotasi Video, Pengunci Kualitas, Adblock, Tangkapan Layar, Kustomisasi Tema, dan Pengunduh Subtitle.
// @author       Tauã B. Kloch Leite
// @match        https://www.youtube.com/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=youtube.com
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_registerMenuCommand
// @grant        GM_addStyle
// @run-at       document-end
// @copyright    2025, Tauã B. Kloch Leite - All Rights Reserved.
// ==/UserScript==

(function() {
    'use strict';

    console.log('⚡ YT Master v1.2.0 Started');

    const defaultConfig = {
        adblock: true,
        cinemaMode: false,
        redirectShorts: true,
        hideShorts: false,
        forceQuality: true,
        themeColor: '#00ff00',
        titleColor: '#ffffff',
        textColor: '#aaaaaa',
        titleFontSize: 100,
        btnColor: '#222222',
        btnTextColor: '#ffffff',
        videoZoom: 100,
        videoRotate: 0,
        videoSpeed: 1.0,
        vBrightness: 100,
        vContrast: 100,
        vSaturate: 100,
        vGrayscale: 0,
        vSepia: 0,
        vHDR: false,
        audioBoost: 100,
        eqBass: 0,
        eqTreble: 0,
        bgType: 'default',
        bgColor: '#000000',
        bgImage: '',
        bgOpacity: 80,
        compactHeader: false,
        subColor: '#ffeb3b',
        subBgColor: 'rgba(0,0,0,0.7)',
        subSize: 100,
        uiHidden: false,
        panelPos: { top: '100px', left: '100px', width: '340px', height: 'auto' },
        btnPos: { top: 'auto', left: 'auto', bottom: '20px', right: '20px' }
    };

    let config = { ...defaultConfig, ...GM_getValue('ytMasterConfig', {}) };

    const ICONS = {
        pix: "https://upload.wikimedia.org/wikipedia/commons/a/a2/Logo%E2%80%94pix_powered_by_Banco_Central_%28Brazil%2C_2020%29.svg",
        paypal: "https://www.paypalobjects.com/webstatic/icon/pp258.png",
        btc: "https://cryptologos.cc/logos/bitcoin-btc-logo.svg?v=025",
        eth: "https://cryptologos.cc/logos/ethereum-eth-logo.svg?v=025",
        sol: "https://cryptologos.cc/logos/solana-sol-logo.svg?v=025",
        bnb: "https://cryptologos.cc/logos/bnb-bnb-logo.svg?v=025",
        matic: "https://cryptologos.cc/logos/polygon-matic-logo.svg?v=025",
        usdt: "https://cryptologos.cc/logos/tether-usdt-logo.svg?v=025",
        bubble: "https://img.icons8.com/?size=100&id=9F8aDI7mYs6V&format=png&color=ffffff",
        warn: "https://upload.wikimedia.org/wikipedia/commons/thumb/f/f7/Antu_dialog-warning.svg/200px-Antu_dialog-warning.svg.png"
    };

    let audioCtx, audioSource, gainNode, bassNode, trebleNode;
    let loopStart = null, loopEnd = null, loopActive = false;
    let mediaRecorder, recordedChunks = [];
    let isRecording = false;

    function registerMenus() {
        GM_registerMenuCommand("⚙️ Control Panel", toggleMenu);
        GM_registerMenuCommand("👁️ Show/Hide HUD (Alt+Shift+Y)", toggleStealthMode);
        GM_registerMenuCommand("📸 Take Screenshot (Shift+P)", takeScreenshot);
        GM_registerMenuCommand("🔴 Start/Stop Recording", toggleRecording);
        GM_registerMenuCommand("⏩ Reset Speed (1.0x)", () => { updateConfig('videoSpeed', 1.0); refreshInputs(); });
        GM_registerMenuCommand("🔊 Reset Audio", resetAudioSettings);
        GM_registerMenuCommand("⌨️ View All Hotkeys", () => {
            if (!document.getElementById('ym-panel')) buildUI();
            document.getElementById('ym-panel').style.display = 'flex';
            switchTab('hotkeys');
        });
    }
    registerMenus();

    const cssStructure = `
        :root {
            --ym-theme: ${config.themeColor};
            --ym-title: ${config.titleColor};
            --ym-text: ${config.textColor};
            --ym-btn-bg: ${config.btnColor};
            --ym-btn-txt: ${config.btnTextColor};
            --ym-font-scale: ${config.titleFontSize / 100};
            --ym-sub-color: ${config.subColor};
            --ym-sub-bg: ${config.subBgColor};
            --ym-sub-size: ${config.subSize}%;
        }

        video { transition: transform 0.2s ease-out, filter 0.2s ease-out !important; }

        .yt-lockup-metadata-view-model__title, a.yt-lockup-metadata-view-model__title, h3.yt-lockup-metadata-view-model__title, .yt-lockup-metadata-view-model__title span {
            color: var(--ym-title) !important; font-size: calc(1.6rem * var(--ym-font-scale)) !important; line-height: 1.3 !important; font-weight: 500 !important; max-height: none !important;
        }
        #video-title, #video-title.ytd-rich-grid-media, #video-title.ytd-compact-video-renderer, a#video-title-link, h1.ytd-watch-metadata {
            color: var(--ym-title) !important; font-size: calc(1.5rem * var(--ym-font-scale)) !important;
        }

        .yt-lockup-metadata-view-model__metadata, #metadata-line, ytd-channel-name #text, #description-text, ytd-guide-entry-renderer #endpoint {
             color: var(--ym-text) !important;
        }

        body.ym-hide-shorts ytd-rich-shelf-renderer[is-shorts], body.ym-hide-shorts ytd-reel-shelf-renderer, body.ym-hide-shorts a[href^="/shorts"] { display: none !important; }

        html.ym-bg-image { background-image: var(--ym-bg-url) !important; background-size: cover !important; background-attachment: fixed !important; background-position: center !important; background-color: #000 !important; }
        html.ym-bg-image body, html.ym-bg-image ytd-app, html.ym-bg-image #content, html.ym-bg-image #page-manager { background: transparent !important; }
        html.ym-bg-image ytd-rich-item-renderer, html.ym-bg-image ytd-watch-metadata, html.ym-bg-image #comments, html.ym-bg-image #secondary-inner, html.ym-bg-image #masthead-container {
            background-color: rgba(0,0,0, var(--ym-content-opacity)) !important; border-radius: 12px; padding: 6px !important; margin-bottom: 8px !important;
        }

        .ytp-play-progress, .ytp-swatch-background-color { background: var(--ym-theme) !important; }
        ytd-menu-renderer button, ytd-menu-renderer yt-button-shape { background-color: var(--ym-btn-bg) !important; color: var(--ym-btn-txt) !important; border-radius: 20px; }
        .ytp-caption-segment { color: var(--ym-sub-color) !important; background-color: var(--ym-sub-bg) !important; font-size: var(--ym-sub-size) !important; }

        #ym-panel {
            position: fixed; background: #0f0f0f; border: 1px solid #333; border-radius: 12px; z-index: 2147483647;
            color: white; font-family: Arial, sans-serif; font-size: 12px; box-shadow: 0 10px 50px rgba(0,0,0,1);
            display: none; flex-direction: column; resize: both; overflow: hidden; min-width: 300px; min-height: 250px; max-height: 90vh;
        }
        #ym-header { padding: 12px; background: #1f1f1f; border-bottom: 1px solid #333; display: flex; justify-content: space-between; cursor: move; flex-shrink: 0; user-select: none; }
        #ym-tabs { display: flex; background: #111; border-bottom: 1px solid #333; flex-shrink: 0; user-select: none; flex-wrap: wrap; }
        .ym-tab { flex: 1; padding: 10px 5px; text-align: center; cursor: pointer; color: #888; border-bottom: 2px solid transparent; transition: 0.2s; min-width: 40px; font-size: 11px; }
        .ym-tab.active { color: #fff; border-bottom: 2px solid var(--ym-theme); background: #222; }
        .ym-content { padding: 15px; display: none; overflow-y: auto; flex-grow: 1; }
        .ym-content.active { display: block; }

        .ym-row { display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; }
        .ym-btn { width: 100%; padding: 8px; background: #333; color: white; border: 1px solid #444; margin-top: 5px; cursor: pointer; border-radius: 4px; }
        .ym-btn:hover { background: #444; border-color: white; }
        .ym-btn.active-btn { background: var(--ym-theme); color: #000; font-weight: bold; }
        .ym-rec-active { animation: pulse 1.5s infinite; background: #990000 !important; border-color: red !important; font-weight: bold; }
        @keyframes pulse { 0% { opacity: 1; } 50% { opacity: 0.7; } 100% { opacity: 1; } }

        input[type="text"] { background: #222; border: 1px solid #444; color: #fff; padding: 5px; border-radius: 4px; width: 100%; }
        input[type=range] { accent-color: var(--ym-theme); }

        #ym-float-btn {
            position: fixed; width: 50px; height: 50px; background: #111; border: 2px solid var(--ym-theme); border-radius: 50%;
            text-align: center; line-height: 50px; font-size: 24px; cursor: pointer; z-index: 2147483647;
            box-shadow: 0 0 15px rgba(0,0,0,0.5); transition: transform 0.2s; user-select: none;
        }
        #ym-float-btn:hover { transform: scale(1.1); }

        .ym-stealth #ym-panel, .ym-stealth #ym-float-btn { display: none !important; }

        .sup-row { display: flex; align-items: center; margin-bottom: 8px; }
        .sup-icon { height: 20px; width: 20px; margin-right: 10px; }
        .sup-val { flex: 1; margin: 0 10px; background: #222; border: 1px solid #444; color: #fff; padding: 5px; border-radius: 4px; font-size: 11px; }
        .sup-copy { background: #333; color: #fff; border: 1px solid #444; padding: 5px 10px; border-radius: 4px; cursor: pointer; font-size: 11px; }
        .sup-copy:hover { background: #444; }
    `;

    GM_addStyle(cssStructure);

    function isTabElement(element) {
        return element && (element.classList.contains('ym-tab') || element.closest('.ym-tab'));
    }

    function initAudioContext() {
        if (audioCtx) return;
        try {
            const AudioContext = window.AudioContext || window.webkitAudioContext;
            audioCtx = new AudioContext();
            const video = document.querySelector('video');
            if (!video) return;
            if (!audioSource) {
                audioSource = audioCtx.createMediaElementSource(video);
                gainNode = audioCtx.createGain();
                bassNode = audioCtx.createBiquadFilter();
                trebleNode = audioCtx.createBiquadFilter();
                bassNode.type = 'lowshelf'; bassNode.frequency.value = 200;
                trebleNode.type = 'highshelf'; trebleNode.frequency.value = 2000;
                audioSource.connect(bassNode); bassNode.connect(trebleNode); trebleNode.connect(gainNode); gainNode.connect(audioCtx.destination);
            }
            applyAudioSettings();
        } catch (e) { console.error('YT Master: AudioContext Error', e); }
    }

    function applyAudioSettings() {
        if (!gainNode) initAudioContext();
        if (gainNode) { gainNode.gain.value = config.audioBoost / 100; bassNode.gain.value = config.eqBass; trebleNode.gain.value = config.eqTreble; }
    }

    function resetAudioSettings() { updateConfig('audioBoost', 100); updateConfig('eqBass', 0); updateConfig('eqTreble', 0); refreshInputs(); }

    function toggleRecording() { if (isRecording) stopRecording(); else startRecording(); }

    function startRecording() {
        const video = document.querySelector('video'); if (!video) return;
        try {
            const stream = video.captureStream();
            mediaRecorder = new MediaRecorder(stream, { mimeType: 'video/webm' });
            recordedChunks = [];
            mediaRecorder.ondataavailable = (event) => { if (event.data.size > 0) recordedChunks.push(event.data); };
            mediaRecorder.onstop = () => {
                const blob = new Blob(recordedChunks, { type: 'video/webm' });
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a'); a.href = url; a.download = `yt_rec_${new Date().getTime()}.webm`; a.click();
                window.URL.revokeObjectURL(url); updateRecButton(false);
            };
            mediaRecorder.start(); isRecording = true; updateRecButton(true);
        } catch (e) { alert('Error: Browser does not support direct recording here.'); }
    }

    function stopRecording() { if (mediaRecorder && isRecording) { mediaRecorder.stop(); isRecording = false; } }

    function updateRecButton(active) {
        const btn = document.getElementById('btn-rec');
        if (btn) {
            if (active) { btn.innerText = '⏹️ Stop Recording'; btn.classList.add('ym-rec-active'); }
            else { btn.innerText = '🔴 Record Video (REC)'; btn.classList.remove('ym-rec-active'); }
        }
    }

    function setLoopA() { const v = document.querySelector('video'); if (v) { loopStart = v.currentTime; loopActive = true; updateLoopUI(); } }

    function setLoopB() { const v = document.querySelector('video'); if (v) { loopEnd = v.currentTime; loopActive = true; updateLoopUI(); } }

    function clearLoop() { loopStart = null; loopEnd = null; loopActive = false; updateLoopUI(); }

    function updateLoopUI() {
        const status = document.getElementById('loop-status');
        if (status) {
            const a = loopStart !== null ? loopStart.toFixed(1) + 's' : '...';
            const b = loopEnd !== null ? loopEnd.toFixed(1) + 's' : '...';
            status.innerText = `Loop: [A: ${a}] - [B: ${b}] ${loopActive ? '(ON)' : ''}`;
            status.style.color = loopActive ? '#00ff00' : '#888';
        }
    }

    async function downloadSubtitles() {
        try {
            const player = document.getElementById('movie_player'); if (!player) return alert('Player not found.');
            const captions = player.getOption('captions', 'tracklist'); if (!captions || captions.length === 0) return alert('No subtitles.');
            const track = captions.find(c => c.languageCode === player.getOption('captions', 'track').languageCode) || captions[0];
            const response = await fetch(track.baseUrl + '&fmt=srv3');
            const text = await response.text();
            let srtOutput = '', srtIndex = 1, match;
            const regex = /<p t="(\d+)" d="(\d+)".*?>(.*?)<\/p>/g;
            function fmt(ms) { const d = new Date(ms); return d.toISOString().slice(11, 23).replace('.', ','); }
            while ((match = regex.exec(text)) !== null) {
                srtOutput += `${srtIndex}\n${fmt(parseInt(match[1]))} --> ${fmt(parseInt(match[1]) + parseInt(match[2]))}\n${match[3].replace(/&quot;/g,'"').replace(/&#39;/g,"'")}\n\n`;
                srtIndex++;
            }
            const a = document.createElement('a'); a.href = URL.createObjectURL(new Blob([srtOutput], { type: 'text/srt' })); a.download = `subs.srt`; a.click();
        } catch (e) { alert('Download error.'); }
    }

    function enforceQuality() {
        if (!config.forceQuality) return;
        const player = document.getElementById('movie_player');
        if (player && player.getAvailableQualityLevels) {
            const levels = player.getAvailableQualityLevels();
            if (levels.length > 0 && player.getPlaybackQuality() !== levels[0]) player.setPlaybackQualityRange(levels[0], levels[0]);
        }
    }

    function el(tag, props = {}, children = []) {
        const element = document.createElement(tag);
        for (let key in props) {
            if (key === 'style') {
                Object.assign(element.style, props[key]);
            } else if (key.startsWith('on')) {
                element.addEventListener(key.substring(2).toLowerCase(), props[key]);
            } else if (key.startsWith('data-')) {
                element.setAttribute(key, props[key]);
            } else {
                element[key] = props[key];
            }
        }
        children.forEach(child => { if (typeof child === 'string') element.appendChild(document.createTextNode(child)); else element.appendChild(child); });
        return element;
    }

    function switchTab(tabId) {
        const tabElement = document.querySelector(`[data-tab="${tabId}"]`);
        const contentElement = document.getElementById(`tab-${tabId}`);
        if (!tabElement || !contentElement) return;
        document.querySelectorAll('.ym-tab').forEach(t => t.classList.remove('active'));
        document.querySelectorAll('.ym-content').forEach(c => c.classList.remove('active'));
        tabElement.classList.add('active');
        contentElement.classList.add('active');
    }

    function setupCopyButtons() {
        document.querySelectorAll('.sup-copy').forEach(btn => {
            btn.addEventListener('click', function() {
                const val = this.getAttribute('data-val');
                navigator.clipboard.writeText(val).then(() => {
                    const originalText = this.innerText;
                    this.innerText = 'Copied!';
                    setTimeout(() => this.innerText = originalText, 2000);
                }).catch(err => {
                    console.error('Failed to copy: ', err);
                });
            });
        });
    }

    function buildUI() {
        if (document.getElementById('ym-panel')) return;

        const createFooter = () => el('div', {
            className: 'ym-footer-drag',
            style: { color: '#888', fontSize: '11px', textAlign: 'center', marginTop: '20px', paddingBottom: '10px', cursor: 'move', userSelect: 'none' }
        }, ['Tauã B. Kloch Leite - All Rights Reserved 2025']);

        const tGeneral = el('div', { className: 'ym-content active', id: 'tab-general' }, [
            createCheck('Anti-AdBlock', 'adblock'),
            createCheck('Force Max Quality (4K)', 'forceQuality'),
            createCheck('Auto Cinema', 'cinemaMode'),
            el('hr', { style: { border: '0', borderTop: '1px solid #333', margin: '10px 0' } }),
            createCheck('Shorts -> Normal', 'redirectShorts'),
            createCheck('🚫 HIDE SHORTS', 'hideShorts'),
            el('div', { style: { color: '#888', fontSize: '11px', textAlign: 'center', marginTop: '10px' } }, ['Tip: Alt+Shift+Y to hide HUD']),
            createFooter()
        ]);

        const tAudio = el('div', { className: 'ym-content', id: 'tab-audio' }, [
            el('h3', { style: { margin: '0 0 10px 0', fontSize: '14px', color: '#fff' } }, ['Audio Booster & EQ']),
            createRange('🔊 Volume Boost', 'audioBoost', 100, 600, '%', 10),
            el('hr', { style: { border: '0', borderTop: '1px solid #333', margin: '10px 0' } }),
            createRange('🎸 Bass', 'eqBass', -20, 20, 'dB'),
            createRange('🎻 Treble', 'eqTreble', -20, 20, 'dB'),
            el('button', { className: 'ym-btn', innerText: 'Reset Audio', onclick: () => { initAudioContext(); resetAudioSettings(); } }),
            createFooter()
        ]);

        const tImage = el('div', { className: 'ym-content', id: 'tab-image' }, [
            el('h3', { style: { margin: '0 0 10px 0', fontSize: '14px', color: '#fff' } }, ['Image Adjustments']),
            createRange('☀️ Brightness', 'vBrightness', 0, 200, '%'),
            createRange('🌗 Contrast', 'vContrast', 0, 200, '%'),
            createRange('🎨 Saturation', 'vSaturate', 0, 200, '%'),
            el('hr', { style: { border: '0', borderTop: '1px solid #333', margin: '10px 0' } }),
            createCheck('✨ HDR / SHARPNESS MODE', 'vHDR'),
            createRange('🌑 Grayscale', 'vGrayscale', 0, 100, '%'),
            el('button', { className: 'ym-btn', style: { marginTop: '15px', background: '#4a1111' }, innerText: 'Reset Image', onclick: resetImage },),
            createFooter()
        ]);

        const tVisual = el('div', { className: 'ym-content', id: 'tab-visual' }, [
            el('h3', { style: { margin: '0 0 10px 0', fontSize: '14px', color: '#fff' } }, ['Colors & Sizes']),
            createColor('Title Color', 'titleColor'),
            createColor('General Text Color', 'textColor'),
            createRange('Font Size', 'titleFontSize', 50, 200, '%'),
            el('hr', { style: { border: '0', borderTop: '1px solid #333', margin: '10px 0' } }),
            el('h3', { style: { margin: '0 0 10px 0', fontSize: '14px', color: '#fff' } }, ['Background']),
            el('div', { className: 'ym-row' }, [
                el('span', {}, ['Type:']),
                el('select', { style: { padding: '5px', borderRadius: '4px', background: '#333', color: '#fff' }, onchange: (e) => updateConfig('bgType', e.target.value) }, [
                    el('option', { value: 'default', innerText: 'Default (YT)', selected: config.bgType === 'default' }),
                    el('option', { value: 'color', innerText: 'Solid Color', selected: config.bgType === 'color' }),
                    el('option', { value: 'image', innerText: 'Image / Photo', selected: config.bgType === 'image' })
                ])
            ]),
            config.bgType === 'color' ? createColor('Choose Color', 'bgColor') : null,
            config.bgType === 'image' ? el('div', { style: { marginBottom: '10px' } }, [
                el('div', { style: { marginBottom: '5px' } }, ['Image Link:']),
                el('input', { type: 'text', placeholder: 'Paste link...', value: config.bgImage, onchange: (e) => updateConfig('bgImage', e.target.value) })
            ]) : null,
            (config.bgType === 'image') ? createRange('Content Opacity', 'bgOpacity', 0, 100, '%') : null,
            el('hr', { style: { border: '0', borderTop: '1px solid #333', margin: '10px 0' } }),
            createColor('Theme Color', 'themeColor'),
            createColor('Button BG', 'btnColor'),
            createColor('Button Text', 'btnTextColor'),
            el('button', { className: 'ym-btn', style: { marginTop: '15px', background: '#4a1111' }, innerText: 'Reset Visual', onclick: resetVisual }),
            createFooter()
        ].filter(Boolean));

        const tSubtitles = el('div', { className: 'ym-content', id: 'tab-subtitles' }, [
            createColor('Text Color', 'subColor'),
            createRange('Size', 'subSize', 50, 250, '%'),
            el('button', { className: 'ym-btn', innerText: '📥 Download Subtitles (.srt)', onclick: downloadSubtitles }),
            createFooter()
        ]);

        const tTools = el('div', { className: 'ym-content', id: 'tab-tools' }, [
            el('h3', { style: { margin: '0 0 10px 0', fontSize: '14px', color: '#fff' } }, ['Tools']),
            createRange('⏩ Speed', 'videoSpeed', 0.1, 5.0, 'x', 0.1),
            el('div', { style: { display: 'flex', justifyContent: 'space-between', marginBottom: '15px' } }, [
                 el('button', { className: 'ym-btn', style: { width: '48%' }, innerText: '1.0x (Normal)', onclick: () => { updateConfig('videoSpeed', 1.0); refreshInputs(); } }),
                 el('button', { className: 'ym-btn', style: { width: '48%' }, innerText: '2.5x (Fast)', onclick: () => { updateConfig('videoSpeed', 2.5); refreshInputs(); } })
            ]),
            el('hr', { style: { border: '0', borderTop: '1px solid #333', margin: '10px 0' } }),
            el('button', { id: 'btn-rec', className: 'ym-btn', innerText: '🔴 Record Video (REC)', onclick: toggleRecording }),
            el('hr', { style: { border: '0', borderTop: '1px solid #333', margin: '10px 0' } }),
            el('div', { style: { display: 'flex', gap: '5px' } }, [
                el('button', { className: 'ym-btn', innerText: 'Set A', onclick: setLoopA }),
                el('button', { className: 'ym-btn', innerText: 'Set B', onclick: setLoopB }),
                el('button', { className: 'ym-btn', innerText: 'Clear', onclick: clearLoop }),
            ]),
            el('div', { id: 'loop-status', style: { textAlign: 'center', margin: '5px 0', fontSize: '11px', color: '#888' } }, ['Loop Inactive']),
            el('hr', { style: { border: '0', borderTop: '1px solid #333', margin: '10px 0' } }),
            createRange('🔍 Zoom', 'videoZoom', 100, 300, '%'),
            createRange('🔄 Rotation', 'videoRotate', -720, 720, '°'),
            el('button', { className: 'ym-btn', style: { marginBottom: '15px', background: '#4a1111' }, innerText: 'Reset Zoom/Rotation', onclick: () => { updateConfig('videoZoom', 100); updateConfig('videoRotate', 0); refreshInputs(); } }),
            el('div', { style: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '5px' } }, [
                el('button', { className: 'ym-btn', innerText: '📸 Screenshot', onclick: takeScreenshot }),
                el('button', { className: 'ym-btn', innerText: '📺 PiP', onclick: togglePiP }),
                el('button', { className: 'ym-btn', innerText: '👁️ Stealth', onclick: toggleStealthMode }),
                el('button', { className: 'ym-btn', innerText: '🖼️ Thumbnail', onclick: downloadThumb })
            ]),
            createFooter()
        ]);

        const tHotkeys = el('div', { className: 'ym-content', id: 'tab-hotkeys' }, [
            el('h3', { style: { margin: '0 0 10px 0', fontSize: '14px', color: '#fff' } }, ['Keyboard Shortcuts']),
            el('div', { style: { fontSize: '12px', lineHeight: '1.6' } }, [
                el('div', { style: { marginBottom: '8px' } }, [el('b', {}, ['F9 / Insert']), ' - Open/Close Control Panel']),
                el('div', { style: { marginBottom: '8px' } }, [el('b', {}, ['Alt + Shift + Y']), ' - Show/Hide HUD (Stealth Mode)']),
                el('div', { style: { marginBottom: '8px' } }, [el('b', {}, ['Shift + P']), ' - Take Screenshot']),
                el('div', { style: { marginBottom: '8px' } }, [el('b', {}, ['Ctrl + Shift + Arrow Up/+']), ' - Zoom In']),
                el('div', { style: { marginBottom: '8px' } }, [el('b', {}, ['Ctrl + Shift + Arrow Down/-']), ' - Zoom Out']),
                el('div', { style: { marginBottom: '8px' } }, [el('b', {}, ['Ctrl + Shift + Arrow Right']), ' - Rotate +90°']),
                el('div', { style: { marginBottom: '8px' } }, [el('b', {}, ['Ctrl + Shift + Arrow Left']), ' - Rotate -90°']),
                el('div', { style: { marginBottom: '8px' } }, [el('b', {}, ['Ctrl + Shift + 0']), ' - Reset Zoom/Rotation']),
                el('div', { style: { marginBottom: '8px' } }, [el('b', {}, ['Tampermonkey Menu']), ' - Access all functions']),
                el('hr', { style: { border: '0', borderTop: '1px solid #333', margin: '15px 0' } }),
                createFooter()
            ])
        ]);

        const tAbout = el('div', { className: 'ym-content', id: 'tab-about' }, [
            el('h3', { style: { margin: '0 0 10px 0', fontSize: '14px', color: '#fff' } }, ['About']),
            el('div', { style: { fontSize: '12px', lineHeight: '1.6' } }, [
                el('p', {}, ['⚡ YT Master v1.2.0']),
                el('ul', { style: { paddingLeft: '20px', margin: '10px 0' } }, [
                    el('li', {}, ['Audio Booster & Equalizer']),
                    el('li', {}, ['Video Recording (WEBM)']),
                    el('li', {}, ['AB Loop Function']),
                    el('li', {}, ['Speed Control (0.1x - 5.0x)']),
                    el('li', {}, ['Image Adjustments']),
                    el('li', {}, ['Theme Customization']),
                    el('li', {}, ['Subtitles Download'])
                ]),
                el('hr', { style: { border: '0', borderTop: '1px solid #333', margin: '15px 0' } }),
                el('h4', { style: { color: '#d63384', margin: '10px 0 5px' } }, ['Support the Project']),
                el('p', { style: { fontSize: '11px', color: '#aaa', marginBottom: '10px' } }, ['If you like this tool, consider donating to help with development and maintenance.']),
                el('div', { style: { textAlign: 'left', color: '#d63384', fontWeight: 'bold', fontSize: '10px', marginBottom: '5px' } }, ['Pix (Brazil)']),
                el('div', { className: 'sup-row' }, [
                    el('img', { src: ICONS.pix, className: 'sup-icon', style: { height: '20px', width: '20px' } }),
                    el('input', { type: 'text', className: 'sup-val', readonly: true, value: '69993230419', style: { flex: 1, margin: '0 10px', background: '#222', border: '1px solid #444', color: '#fff', padding: '5px', borderRadius: '4px', fontSize: '11px' } }),
                    el('button', { className: 'sup-copy', 'data-val': '69993230419', style: { background: '#333', color: '#fff', border: '1px solid #444', padding: '5px 10px', borderRadius: '4px', cursor: 'pointer', fontSize: '11px' } }, ['Copy'])
                ]),
                el('div', { style: { textAlign: 'left', color: '#d63384', fontWeight: 'bold', fontSize: '10px', margin: '15px 0 5px' } }, ['Cryptocurrency']),
                ...['btc', 'eth', 'sol', 'usdt'].map(crypto => {
                    let address, name;
                    switch(crypto) {
                        case 'btc': address = 'bc1q6gz3dtj9qvlxyyh3grz35x8xc7hkuj07knlemn'; name = 'BTC'; break;
                        case 'eth': address = '0xd8724d0b19d355e9817d2a468f49e8ce067e70a6'; name = 'ETH'; break;
                        case 'sol': address = '7ztAogE7SsyBw7mwVHhUr5ZcjUXQr99JoJ6oAgP99aCn'; name = 'SOL'; break;
                        case 'usdt': address = '0xd8724d0b19d355e9817d2a468f49e8ce067e70a6'; name = 'USDT'; break;
                    }
                    return el('div', { className: 'sup-row', style: { marginBottom: '5px' } }, [
                        el('img', { src: ICONS[crypto], className: 'sup-icon', style: { height: '20px', width: '20px' } }),
                        el('span', { style: { fontSize: '9px', color: '#888', width: '30px' } }, [name]),
                        el('input', { type: 'text', className: 'sup-val', readonly: true, value: address, style: { flex: 1, margin: '0 10px', background: '#222', border: '1px solid #444', color: '#fff', padding: '5px', borderRadius: '4px', fontSize: '11px' } }),
                        el('button', { className: 'sup-copy', 'data-val': address, style: { background: '#333', color: '#fff', border: '1px solid #444', padding: '5px 10px', borderRadius: '4px', cursor: 'pointer', fontSize: '11px' } }, ['Copy'])
                    ]);
                }),
                el('div', { style: { textAlign: 'center', marginTop: '20px' } }, [
                    el('a', { href: 'https://www.paypal.com/donate/?business=4J4UK7ACU3DS6', target: '_blank', style: { display: 'inline-flex', alignItems: 'center', gap: '8px', background: '#003087', color: 'white', padding: '8px 20px', borderRadius: '20px', textDecoration: 'none', fontWeight: 'bold', fontSize: '12px' } }, [
                        el('img', { src: ICONS.paypal, style: { height: '20px' } }),
                        ' PayPal'
                    ])
                ]),
                el('hr', { style: { border: '0', borderTop: '1px solid #333', margin: '15px 0' } }),
                createFooter()
            ])
        ]);

        const header = el('div', { id: 'ym-header' }, [
            el('span', { innerText: '⚡ YT Master v1.2.0', style: { fontWeight: 'bold', pointerEvents: 'none' } }),
            el('span', { innerText: '✖', style: { cursor: 'pointer', fontSize: '16px' }, onclick: toggleMenu })
        ]);

        const tabsContainer = el('div', { id: 'ym-tabs' });
        const tabs = [
            { n: 'General', id: 'general', c: tGeneral },
            { n: 'Audio', id: 'audio', c: tAudio },
            { n: 'Image', id: 'image', c: tImage },
            { n: 'Visual', id: 'visual', c: tVisual },
            { n: 'Tools', id: 'tools', c: tTools },
            { n: 'Subtitles', id: 'subtitles', c: tSubtitles },
            { n: 'Hotkeys', id: 'hotkeys', c: tHotkeys },
            { n: 'About', id: 'about', c: tAbout }
        ];

        tabs.forEach((t, index) => {
            tabsContainer.appendChild(el('div', {
                className: `ym-tab ${index === 0 ? 'active' : ''}`,
                innerText: t.n,
                'data-tab': t.id,
                onclick: () => switchTab(t.id)
            }));
        });

        const panel = el('div', { id: 'ym-panel' }, [header, tabsContainer, tGeneral, tAudio, tImage, tVisual, tTools, tSubtitles, tHotkeys, tAbout]);

        if (config.panelPos.left !== 'auto') { panel.style.left = config.panelPos.left; panel.style.top = config.panelPos.top; }
        else { panel.style.right = config.panelPos.right; panel.style.top = config.panelPos.top; }
        if (config.panelSize) { panel.style.width = config.panelSize.width; panel.style.height = config.panelSize.height; }

        document.documentElement.appendChild(panel);

        makeDraggable(panel, header, 'panelPos', null);
        panel.querySelectorAll('.ym-footer-drag').forEach(footer => {
            makeDraggable(panel, footer, 'panelPos', null);
        });

        tabsContainer.addEventListener('mousedown', (e) => {
            if (!isTabElement(e.target)) {
                const rect = panel.getBoundingClientRect();
                const startX = e.clientX;
                const startY = e.clientY;
                const relativeX = e.clientX - rect.left;
                const relativeY = e.clientY - rect.top;
                let isDragging = false;

                const onMouseMove = (e) => {
                    const dx = e.clientX - startX;
                    const dy = e.clientY - startY;
                    if (!isDragging && Math.sqrt(dx*dx + dy*dy) > 3) {
                        isDragging = true;
                        panel.style.bottom = 'auto';
                        panel.style.right = 'auto';
                        if (!panel.style.width) panel.style.width = panel.offsetWidth + 'px';
                    }
                    if (isDragging) {
                        e.preventDefault();
                        panel.style.left = (e.clientX - relativeX) + 'px';
                        panel.style.top = (e.clientY - relativeY) + 'px';
                    }
                };

                const onMouseUp = (e) => {
                    document.removeEventListener('mousemove', onMouseMove);
                    document.removeEventListener('mouseup', onMouseUp);
                    if (isDragging) {
                        config.panelPos = {
                            top: panel.style.top,
                            left: panel.style.left,
                            width: panel.style.width,
                            height: panel.style.height
                        };
                        GM_setValue('ytMasterConfig', config);
                    }
                };

                document.addEventListener('mousemove', onMouseMove);
                document.addEventListener('mouseup', onMouseUp);
            }
        });

        panel.addEventListener('mouseup', () => {
            setTimeout(() => {
                config.panelSize = { width: panel.style.width, height: panel.style.height };
                GM_setValue('ytMasterConfig', config);
            }, 200);
        });

        setupCopyButtons();
    }

    function makeDraggable(element, handle, configKey, clickCallback) {
        let isDragging = false, startX, startY, relativeX, relativeY;
        const onMouseDown = (e) => {
            if (isTabElement(e.target)) return;
            if (['INPUT','TEXTAREA','SELECT'].includes(e.target.tagName) || e.target.innerText === '✖') return;
            const rect = element.getBoundingClientRect();
            startX = e.clientX; startY = e.clientY;
            relativeX = e.clientX - rect.left; relativeY = e.clientY - rect.top;
            isDragging = false;
            document.addEventListener('mousemove', onMouseMove);
            document.addEventListener('mouseup', onMouseUp);
        };
        const onMouseMove = (e) => {
            const dx = e.clientX - startX, dy = e.clientY - startY;
            if (!isDragging && Math.sqrt(dx*dx + dy*dy) > 3) {
                isDragging = true;
                element.style.bottom = 'auto'; element.style.right = 'auto';
                if (!element.style.width) element.style.width = element.offsetWidth + 'px';
            }
            if (isDragging) { e.preventDefault(); element.style.left = (e.clientX - relativeX) + 'px'; element.style.top = (e.clientY - relativeY) + 'px'; }
        };
        const onMouseUp = (e) => {
            document.removeEventListener('mousemove', onMouseMove); document.removeEventListener('mouseup', onMouseUp);
            if (isDragging && configKey) { config[configKey] = { top: element.style.top, left: element.style.left, width: element.style.width, height: element.style.height }; GM_setValue('ytMasterConfig', config); }
            else if (!isDragging && clickCallback) clickCallback();
        };
        handle.addEventListener('mousedown', onMouseDown);
    }

    function refreshInputs() {
        const ids = ['videoZoom', 'videoRotate', 'vBrightness', 'vContrast', 'vSaturate', 'vGrayscale', 'videoSpeed', 'audioBoost', 'eqBass', 'eqTreble', 'titleFontSize', 'bgOpacity'];
        ids.forEach(id => {
            if(document.getElementById('inp-'+id)) {
                document.getElementById('inp-'+id).value = config[id];
                let suffix = '%';
                if(id === 'videoRotate') suffix = '°';
                if(id === 'videoSpeed') suffix = 'x';
                if(id === 'eqBass' || id === 'eqTreble') suffix = 'dB';
                if(document.getElementById('disp-'+id)) document.getElementById('disp-'+id).innerText = config[id] + suffix;
            }
        });
        if (document.getElementById('ym-panel')) {
            const activeTab = document.querySelector('.ym-tab.active');
            const activeTabId = activeTab ? activeTab.getAttribute('data-tab') : 'general';
            document.getElementById('ym-panel').remove();
            buildUI();
            document.getElementById('ym-panel').style.display = 'flex';
            switchTab(activeTabId);
        }
    }

    function resetVisual() {
        updateConfig('themeColor', '#00ff00');
        updateConfig('titleColor', '#ffffff');
        updateConfig('textColor', '#aaaaaa');
        updateConfig('titleFontSize', 100);
        updateConfig('btnColor', '#222222');
        updateConfig('btnTextColor', '#ffffff');
        updateConfig('bgType', 'default');
        updateConfig('bgColor', '#000000');
        updateConfig('bgImage', '');
        updateConfig('bgOpacity', 80);
        refreshInputs();
    }

    function resetImage() {
        updateConfig('vBrightness', 100); updateConfig('vContrast', 100); updateConfig('vSaturate', 100);
        updateConfig('vGrayscale', 0); updateConfig('vSepia', 0); updateConfig('vHDR', false);
        refreshInputs();
    }

    function updateConfig(key, value) {
        config[key] = value;
        GM_setValue('ytMasterConfig', config);
        applyLiveStyles();
        applyVideoTransforms();
        applyAudioSettings();
        if (key === 'bgType') refreshInputs();
    }

    function createCheck(label, key) { return el('div', { className: 'ym-row' }, [ el('span', {}, [label]), el('input', { type: 'checkbox', checked: config[key], onchange: (e) => updateConfig(key, e.target.checked) }) ]); }
    function createColor(label, key) { return el('div', { className: 'ym-row' }, [ el('span', {}, [label]), el('input', { type: 'color', value: config[key], oninput: (e) => updateConfig(key, e.target.value) }) ]); }
    function createRange(label, key, min, max, suffix, step=1) {
        const display = el('b', { id: 'disp-'+key }, [config[key] + suffix]);
        return el('div', {}, [ el('div', { className: 'ym-row' }, [ el('span', {}, [label + ': ']), display ]), el('input', { id: 'inp-'+key, type: 'range', min: min, max: max, step: step, value: config[key], style: { width: '100%' }, oninput: (e) => { display.innerText = e.target.value + suffix; updateConfig(key, e.target.value); } }) ]);
    }

    function takeScreenshot() {
        const v = document.querySelector('video'); if(!v)return;
        const c=document.createElement('canvas');c.width=v.videoWidth;c.height=v.videoHeight;
        const ctx = c.getContext('2d'); ctx.filter = v.style.filter; ctx.drawImage(v,0,0);
        const a=document.createElement('a');a.href=c.toDataURL('image/png');a.download='screenshot_ym.png';a.click();
    }
    function togglePiP() { const v=document.querySelector('video');if(v)document.pictureInPictureElement?document.exitPictureInPicture():v.requestPictureInPicture(); }
    function downloadThumb() { const v=new URLSearchParams(location.search).get('v');if(v)window.open(`https://img.youtube.com/vi/${v}/maxresdefault.jpg`); }

    function toggleStealthMode() {
        config.uiHidden = !config.uiHidden;
        GM_setValue('ytMasterConfig', config);
        applyLiveStyles();
        console.log('YT Master: Stealth mode', config.uiHidden ? 'ON' : 'OFF');
    }

    function toggleMenu() {
        const p = document.getElementById('ym-panel');
        if (!p) { buildUI(); document.getElementById('ym-panel').style.display = 'flex'; }
        else { p.style.display = p.style.display === 'none' ? 'flex' : 'none'; }
    }

    function checkButton() {
        if (!document.getElementById('ym-float-btn')) {
            const btn = el('div', { id: 'ym-float-btn', innerText: '⚙️' });
            if(config.btnPos.left !== 'auto') { btn.style.left = config.btnPos.left; btn.style.top = config.btnPos.top; btn.style.bottom = 'auto'; btn.style.right = 'auto'; }
            else { btn.style.bottom = config.btnPos.bottom; btn.style.right = config.btnPos.right; }
            document.documentElement.appendChild(btn);
            makeDraggable(btn, btn, 'btnPos', toggleMenu);
        }
    }

    document.addEventListener('keydown', function(e) {
        if (['INPUT', 'TEXTAREA'].includes(e.target.tagName) || e.target.isContentEditable) return;

        if (e.code === 'F9' || e.code === 'Insert') {
            e.preventDefault();
            toggleMenu();
            return;
        }

        if (e.shiftKey && (e.key === 'P' || e.key === 'p')) {
            e.preventDefault();
            takeScreenshot();
        }

        if (e.altKey && e.shiftKey && (e.key === 'Y' || e.key === 'y')) {
            console.log('YT Master: Alt+Shift+Y pressed');
            e.preventDefault();
            toggleStealthMode();
        }

        if (e.ctrlKey && e.shiftKey) {
            switch(e.key) {
                case 'ArrowRight':
                    e.preventDefault();
                    updateConfig('videoRotate', parseInt(config.videoRotate) + 90);
                    refreshInputs();
                    break;
                case 'ArrowLeft':
                    e.preventDefault();
                    updateConfig('videoRotate', parseInt(config.videoRotate) - 90);
                    refreshInputs();
                    break;
                case 'ArrowUp':
                case '+':
                case '=':
                    e.preventDefault();
                    updateConfig('videoZoom', Math.min(parseInt(config.videoZoom) + 10, 300));
                    refreshInputs();
                    break;
                case 'ArrowDown':
                case '-':
                case '_':
                    e.preventDefault();
                    updateConfig('videoZoom', Math.max(parseInt(config.videoZoom) - 10, 50));
                    refreshInputs();
                    break;
                case '0':
                case ')':
                    e.preventDefault();
                    updateConfig('videoZoom', 100);
                    updateConfig('videoRotate', 0);
                    refreshInputs();
                    break;
            }
        }
    });

    function applyLiveStyles() {
        const root = document.documentElement.style;
        const body = document.body;
        root.setProperty('--ym-theme', config.themeColor);
        root.setProperty('--ym-title', config.titleColor);
        root.setProperty('--ym-text', config.textColor);
        root.setProperty('--ym-btn-bg', config.btnColor);
        root.setProperty('--ym-btn-txt', config.btnTextColor);
        root.setProperty('--ym-sub-color', config.subColor);
        root.setProperty('--ym-sub-bg', config.subBgColor);
        root.setProperty('--ym-sub-size', config.subSize + '%');
        root.setProperty('--ym-font-scale', config.titleFontSize / 100);

        root.setProperty('--yt-spec-text-primary', config.titleColor, 'important');
        root.setProperty('--yt-spec-text-secondary', config.textColor, 'important');

        if (config.hideShorts) body.classList.add('ym-hide-shorts'); else body.classList.remove('ym-hide-shorts');
        if (config.uiHidden) document.documentElement.classList.add('ym-stealth'); else document.documentElement.classList.remove('ym-stealth');

        if (config.compactHeader) body.classList.add('ym-compact'); else body.classList.remove('ym-compact');

        if (config.bgType === 'color') {
            document.documentElement.classList.remove('ym-bg-image');
            root.setProperty('--yt-spec-base-background', config.bgColor, 'important');
            root.setProperty('--yt-spec-general-background-a', config.bgColor, 'important');
            root.setProperty('--yt-spec-general-background-b', config.bgColor, 'important');
        } else if (config.bgType === 'image') {
            document.documentElement.classList.add('ym-bg-image');
            root.setProperty('--yt-spec-base-background', 'transparent', 'important');
            root.setProperty('--yt-spec-general-background-a', 'transparent', 'important');
            root.setProperty('--yt-spec-general-background-b', 'transparent', 'important');
            root.setProperty('--ym-bg-url', `url(${config.bgImage})`);
            root.setProperty('--ym-content-opacity', config.bgOpacity / 100);
        } else {
            document.documentElement.classList.remove('ym-bg-image');
            root.removeProperty('--yt-spec-base-background');
            root.removeProperty('--yt-spec-general-background-a');
            root.removeProperty('--yt-spec-general-background-b');
        }
    }

    function applyVideoTransforms() {
        const video = document.querySelector('video'); if (!video) return;
        video.style.transform = `scale(${config.videoZoom / 100}) rotate(${config.videoRotate}deg)`;
        let filterString = `brightness(${config.vBrightness}%) contrast(${config.vContrast}%) saturate(${config.vSaturate}%) grayscale(${config.vGrayscale}%) sepia(${config.vSepia}%)`;
        if (config.vHDR) filterString += ` drop-shadow(0 0 1px rgba(255,255,255,0.3)) contrast(110%) saturate(110%)`;
        video.style.filter = filterString;
        if (video.playbackRate !== config.videoSpeed && !video.paused) video.playbackRate = config.videoSpeed;
        if (loopActive && loopStart !== null && loopEnd !== null) { if (video.currentTime >= loopEnd) video.currentTime = loopStart; }
    }

    setInterval(() => {
        if (config.adblock) {
            const skip = document.querySelector('.ytp-ad-skip-button, .ytp-ad-skip-button-modern'); if (skip) skip.click();
            const ad = document.querySelector('.ad-showing'); const video = document.querySelector('video');
            if (ad && video) { video.playbackRate = 16; video.muted = true; if (!isNaN(video.duration)) video.currentTime = video.duration; document.querySelector('ytd-enforcement-message-view-model')?.remove(); }
        }
    }, 50);

    setInterval(() => {
        applyLiveStyles(); applyVideoTransforms(); enforceQuality();
    }, 500);

    setInterval(() => { checkButton(); if (config.redirectShorts && location.href.includes('/shorts/')) location.replace(location.href.replace('/shorts/', '/watch?v=')); }, 1000);
    setTimeout(() => { applyLiveStyles(); checkButton(); }, 500);
})();