Youtube 工具 多合一本地下載 MP4、MP3

Youtube 工具 多合一本地下載 mp4、MP3

安裝腳本?
作者推薦腳本

您可能也會喜歡 自訂貼紙

安裝腳本
// ==UserScript==
// @name Youtube Tools All in one local download mp3 mp4 HIGT QUALITY return dislikes and more
// @name:zh-TW  Youtube 工具 多合一本地下載 MP4、MP3
// @name:zh-HK  Youtube 工具 多合一本地下載 MP4、MP3
// @name:zh-CN  Youtube 工具 多合一本地下載 MP4、MP3
// @name:ja Youtube ツール オールインワンのローカル ダウンロード MP4、MP3
// @name:kr Youtube 도구 올인원 로컬 다운로드 외부 서비스 없이 MP4, MP3
// @name:ar Youtube Tools All in one local download mp3 mp4 HIGT QUALITY return dislikes and more
// @name:bg Youtube-Tools Alles in einem lokalen Download von MP4, MP3.
// @name:cs Nástroje YouTube Vše v jednom místní Stahujte MP4, MP3
// @name:da Youtube-værktøjer Alt i én lokal Download MP4, MP3
// @name:de Youtube-Tools Alles in einem lokalen Download von MP4, MP3
// @name:tel Youtube టూల్స్ అన్నీ ఒకే లోకల్ డౌన్‌లోడ్ MP4, Mp3
// @name:es Youtube Custom Todo en uno Descarga local MP4, MP3.
// @name:en Youtube Tools All in one local download mp3 mp4.
// @name:fr Outils Youtube Tout-en-un local Téléchargez MP4, MP3.
// @name:fr-CA Outils Youtube Tout-en-un local Téléchargez MP4, MP3.
// @name:he כלים של YouTube הכל במקום אחד מקומי הורדה MP4, MP3 באיכות גבוהה ללא שירות חיצוני ועוד.
// @name:hu Youtube Eszközök Minden egy helyen Letöltés MP4, MP3.
// @name:id Alat Youtube Semua dalam satu lokal Unduh MP4, MP3.
// @name:it Strumenti Youtube Tutto in uno Scarica locale MP4, MP3.
// @name:ko Youtube 도구 올인원 로컬 외부 서비스 없이 MP4, MP3
// @name:nb Youtube-verktøy Alt i ett lokalt Last ned MP4, MP3
// @name:nl Youtube Tools Alles in één lokaal Download MP4, MP3
// @name:pl Narzędzia YouTube Wszystko w jednym lokalnym. Pobierz MP4, MP3
// @name:pt-BR Ferramentas do Youtube Tudo em um local Baixe MP4, MP3 DE ALTA QUALIDAD.
// @name:ro YInstrumente Youtube Toate într-un singur local Descărcați MP4, MP3.
// @name:ru Инструменты Youtube Все в одном локальном формате. Загрузите MP4, MP3.
// @name:sk Nástroje YouTube Všetko v jednom miestne Stiahnite si MP4, MP3
// @name:sr Иоутубе алати Све у једном локалном Преузми МП4, МП3
// @name:sv Youtube-verktyg Allt i ett lokalt Ladda ner MP4, MP3
// @name:th เครื่องมือ Youtube ทั้งหมดในที่เดียว ดาวน์โหลด MP4, MP3
// @name:tr Youtube Araçları Hepsi bir arada yerel Harici hizmet olmadan MP4, MP3
// @name:uk Інструменти Youtube Все в одному локальному завантаженні MP4, MP3
// @name:ug Youtube قوراللىرى ھەممىسى بىر يەرلىك چۈشۈرۈش MP4,mp3
// @name:vi Công cụ Youtube Tất cả trong một cục bộ Tải xuống MP4, MP3
// @description:zh-TW Youtube 工具 多合一本地下載 mp4、MP3
// @description:zh-HK Youtube 工具 多合一本地下載 mp4、MP3
// @description:zh-CN Youtube 工具 多合一本地下載 mp4、MP3
// @description:ja    Youtube ツール オールインワン ローカル ダウンロード mp4、MP3 、
// @description:kr    Youtube 도구 올인원 로컬 다운로드 mp4, MP3
// @description:ar    Herramientas de YouTube Todo en uno Descarga local mp4, MP3
// @description:bg    Инструменти за Youtube Всичко в едно локално изтегляне mp4,
// @description:cs    Nástroje YouTube Vše v jednom místní Stahování mp4, MP3
// @description:da    Youtube-værktøjer Alt i ét lokalt Download mp4, MP3
// @description:de    YouTube-Tools Alles in einem lokalen Laden Sie MP4, MP3
// @description:tel   Youtube Tools All in one local Download mp4, MP3 HIGT QUALITY,
// @description:es Youtube tools todo en uno personlizada youtube a tu estilo y descarga MP4 y MP3
// @description:fr Outils Youtube Tout-en-un local Téléchargez des mp4, des MP3
// @description:fr-CA Outils Youtube Tout-en-un local Téléchargez des mp4, des MP3
// @description:he  כלים של YouTube הכל במקום אחד מקומי הורד mp4, MP3
// @description:hu  Youtube Eszközök Minden egyben helyi Letöltés mp4, MP3
// @description:id  Alat Youtube Semua dalam satu lokal Unduh mp4, MP3
// @description:it Strumenti Youtube Tutto in uno locale Scarica mp4, MP3
// @description:ko  Youtube 도구 올인원 로컬 다운로드 mp4, MP3
// @description:nb  YoYoutube-verktøy Alt i ett lokalt Last ned mp4, MP3
// @description:nl    YouTube-tools Alles in één lokaal Download mp4, MP3
// @description:pl    Narzędzia Youtube Wszystko w jednym miejscu Pobierz mp4, MP3
// @description:pt-BR Ferramentas do YouTube Tudo em um só local Baixe mp4, MP3
// @description:ro    Instrumente Youtube Toate într-un singur local Descărcați mp4, MP3
// @description:ru    Инструменты Youtube Все в одном, локально. Загрузите mp4, MP3
// @description:sk    Nástroje YouTube Všetko v jednom miestnom Sťahujte mp4, MP3
// @description:sr    Иоутубе алати Све у једном локалном Преузми мп4, МП3
// @description:sv    Youtube-verktyg Allt i ett lokalt Ladda ner mp4, MP3
// @description:th เครื่องมือ Youtube ทั้งหมดในที่เดียว ดาวน์โหลด mp4, MP3
// @description:tr Youtube Araçları Hepsi bir arada yerel Harici hizmet olmadan mp4, MP3
// @description:uk Інструменти Youtube Все в одному локальному завантаженні mp4, MP3
// @description:ug Youtube قورالىنىڭ ھەممىسى بىر يەرلىك چۈشۈرۈشتە mp4, MP3 HIGH QUAقنى قا
// @description:vi Công cụ Youtube Tất cả trong một cục bộ Tải xuống mp4, MP3
// @description:en Youtube Tools All in one local Download mp4, MP3 HIGT QUALITY
// @description Youtube Tools All in one local Download mp4, MP3 HIGT QUALITY
// @homepage     https://github.com/DeveloperMDCM/
// @version      2.3.4.3
// @author       DeveloperMDCM
// @match        *://www.youtube.com/*
// @exclude      *://music.youtube.com/*
// @exclude      *://*.music.youtube.com/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=youtube.com
// @grant        GM_info
// @grant        GM_addStyle
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        unsafeWindow
// @run-at       document-end
// @require      https://cdn.jsdelivr.net/npm/[email protected]/dist/js/iziToast.min.js
// @compatible chrome
// @compatible firefox
// @compatible opera
// @compatible safari
// @compatible edge
// @license MIT
// @namespace https://github.com/DeveloperMDCM/
// ==/UserScript==

(function () {
  'use strict';
  let validoUrl = document.location.href;
  const $e = (el) => document.querySelector(el); // any element
  const $id = (el) => document.getElementById(el); // element by id
  const $m = (el) => document.querySelectorAll(el); // multiple all elements
  const $cl = (el) => document.createElement(el); // create element
  const $sp = (el, pty) => document.documentElement.style.setProperty(el, pty); // set property variable css
  const $ap = (el) => document.body.appendChild(el); // append element
  const apiDislikes = "https://returnyoutubedislikeapi.com/Votes?videoId="; // Api dislikes
  const apiGoogleTranslate = "https://translate.googleapis.com/translate_a/t"; // Api google translate
  let selectedBgColor = "#252525"; // Background color menu default
  let selectedTextColor = "#ffffff"; // Text color menu default
  let selectedBgAccentColor = "#ff0000"; // Accent color menu default
  const urlSharedCode = "https://greasyfork.org/es/scripts/460680-youtube-tools-all-in-one-local-download-mp3-mp4-higt-quality-return-dislikes-and-more";

  function isFullscreen() {
    return document.fullscreenElement !== null;
  }
  // for translate comments video
  const languagesTranslate = {
    "af": "Afrikaans",
    "sq": "Albanian",
    "am": "Amharic",
    "ar": "Arabic",
    "hy": "Armenian",
    "az": "Azerbaijani",
    "eu": "Basque",
    "be": "Belarusian",
    "bn": "Bengali",
    "bs": "Bosnian",
    "bg": "Bulgarian",
    "ca": "Catalan",
    "ceb": "Cebuano",
    "zh-CN": "Chinese (Simplified)",
    "zh-TW": "Chinese (Traditional)",
    "co": "Corsican",
    "hr": "Croatian",
    "cs": "Czech",
    "da": "Danish",
    "nl": "Dutch",
    "en": "English",
    "eo": "Esperanto",
    "et": "Estonian",
    "fi": "Finnish",
    "fr": "French",
    "fy": "Frisian",
    "gl": "Galician",
    "ka": "Georgian",
    "de": "German",
    "el": "Greek",
    "gu": "Gujarati",
    "ht": "Haitian Creole",
    "ha": "Hausa",
    "haw": "Hawaiian",
    "iw": "Hebrew",
    "hi": "Hindi",
    "hmn": "Hmong",
    "hu": "Hungarian",
    "is": "Icelandic",
    "ig": "Igbo",
    "id": "Indonesian",
    "ga": "Irish",
    "it": "Italian",
    "ja": "Japanese",
    "jw": "Javanese",
    "kn": "Kannada",
    "kk": "Kazakh",
    "km": "Khmer",
    "ko": "Korean",
    "ku": "Kurdish",
    "ky": "Kyrgyz",
    "lo": "Lao",
    "la": "Latin",
    "lv": "Latvian",
    "lt": "Lithuanian",
    "lb": "Luxembourgish",
    "mk": "Macedonian",
    "mg": "Malagasy",
    "ms": "Malay",
    "ml": "Malayalam",
    "mt": "Maltese",
    "mi": "Maori",
    "mr": "Marathi",
    "mn": "Mongolian",
    "my": "Myanmar (Burmese)",
    "ne": "Nepali",
    "no": "Norwegian",
    "ny": "Nyanja (Chichewa)",
    "ps": "Pashto",
    "fa": "Persian",
    "pl": "Polish",
    "pt": "Portuguese",
    "pa": "Punjabi",
    "ro": "Romanian",
    "ru": "Russian",
    "sm": "Samoan",
    "gd": "Scots Gaelic",
    "sr": "Serbian",
    "st": "Sesotho",
    "sn": "Shona",
    "sd": "Sindhi",
    "si": "Sinhala",
    "sk": "Slovak",
    "sl": "Slovenian",
    "so": "Somali",
    "es": "Spanish",
    "su": "Sundanese",
    "sw": "Swahili",
    "sv": "Swedish",
    "tl": "Tagalog (Filipino)",
    "tg": "Tajik",
    "ta": "Tamil",
    "te": "Telugu",
    "th": "Thai",
    "tr": "Turkish",
    "uk": "Ukrainian",
    "ur": "Urdu",
    "uz": "Uzbek",
    "vi": "Vietnamese",
    "cy": "Welsh",
    "xh": "Xhosa",
    "yi": "Yiddish",
    "yo": "Yoruba",
    "zu": "Zulu"
  }
  
  function hideCanvas() {
   
    const canvas = $id('wave-visualizer-canvas');
    if (canvas) {
        canvas.style.opacity = '0';
        if (controlPanel) {
            controlPanel.style.opacity = '0';
        }
    }
  }



  function Notify(type = 'info', message = '', title = '') {
    const defaultTitles = {
        success: 'Success',
        error: 'Error',
        info: 'Information',
        warning: 'Warning',
    };
   
    iziToast[type]({
        title: title || defaultTitles[type] || 'Notification',
        message: message,
        position: 'bottomLeft',
      });
  }


  const UPDATE_INTERVAL = 1000;
    const STORAGE = {
        USAGE: 'YT_TOTAL_USAGE',
        VIDEO: 'YT_VIDEO_TIME',
        SHORTS: 'YT_SHORTS_TIME'
    };

    let usageTime = GM_getValue(STORAGE.USAGE, 0);
    let videoTime = GM_getValue(STORAGE.VIDEO, 0);
    let shortsTime = GM_getValue(STORAGE.SHORTS, 0);
    let lastUpdate = Date.now();
    let activeVideo = null;
    let activeType = null;

    // Inicializar almacenamiento
    GM_setValue(STORAGE.USAGE, usageTime);
    GM_setValue(STORAGE.VIDEO, videoTime);
    GM_setValue(STORAGE.SHORTS, shortsTime);

  function FormatterNumber(num, digits) {
    const lookup = [
      {
        value: 1,
        symbol: '',
      },
      {
        value: 1e3,
        symbol: ' K',
      },
      {
        value: 1e6,
        symbol: ' M',
      },
    ];
    const rx = /\.0+$|(\.[0-9]*[1-9])0+$/;
    const item = lookup
      .slice()
      .reverse()
      .find((item) => {
        return num >= item.value;
      });
    return item
      ? (num / item.value).toFixed(digits).replace(rx, '$1') + item.symbol
      : '0';
  }

  function paramsVideoURL() {
    const parametrosURL = new URLSearchParams(window.location.search); // Url parametros
    return parametrosURL.get('v');
  }

//   Dislikes video
  async function videoDislike() {

    validoUrl = document.location.href;

    const validoVentana = $e('#below > ytd-watch-metadata > div');
    if (validoVentana != undefined && document.location.href.split('?v=')[0].includes('youtube.com/watch')) {
        validoUrl = paramsVideoURL();
        const urlShorts = `${apiDislikes}${validoUrl}`;
      try {
        const respuesta = await fetch(urlShorts);
        const datosShort = await respuesta.json();
        const { dislikes } = datosShort;
        const dislikes_content = $e('#top-level-buttons-computed > segmented-like-dislike-button-view-model > yt-smartimation > div > div > dislike-button-view-model > toggle-button-view-model > button-view-model > button');
        if (dislikes_content !== undefined) {
          dislikes_content.style = 'width: 90px';
          dislikes_content.innerHTML = `
            <svg class="svg-dislike-icon" width="24" height="24" viewBox="0 0 24 24" stroke-width="1" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M7 13v-8a1 1 0 0 0 -1 -1h-2a1 1 0 0 0 -1 1v7a1 1 0 0 0 1 1h3a4 4 0 0 1 4 4v1a2 2 0 0 0 4 0v-5h3a2 2 0 0 0 2 -2l-1 -5a2 3 0 0 0 -2 -2h-7a3 3 0 0 0 -3 3" /></svg>
            ${FormatterNumber(dislikes, 0)}`;
        }

      } catch (error) {
        console.log(error);
      }
    }
  }

  // dislikes shorts
  async function shortDislike() {
    validoUrl = document.location.href;
    const validoVentanaShort = $m(
      '#dislike-button > yt-button-shape > label > div > span'
    );
    if (validoVentanaShort != undefined && document.location.href.split('/')[3] === 'shorts') {
      validoUrl = document.location.href.split('/')[4];
      const urlShorts = `${apiDislikes}${validoUrl}`;
      try {
        const respuesta = await fetch(urlShorts);
        const datosShort = await respuesta.json();  
        const { dislikes } = datosShort;
        for (let i = 0; i < validoVentanaShort.length; i++) {
          validoVentanaShort[i].textContent = `${FormatterNumber(
            dislikes,
            0
          )}`;
        }
      } catch (error) {
        console.log(error);
      }
    }
  }

  // Url change in second load
  let prevUrl;
  let showDislikes = false;

  setInterval(() => {
    const svgDislike = $e('.svg-dislike-ico'); // Check svg in dom
    const currUrl = window.location.href;
    if (prevUrl !== undefined && currUrl !== prevUrl && !svgDislike && showDislikes) {
      setTimeout(async() => {
            await videoDislike();
            await shortDislike();
      },2000)
    }
    prevUrl = currUrl;
  }, 1000);



  // Create a Trusted Types policy
  const policy = window.trustedTypes?.createPolicy('default', {
    createHTML: (input) => input,
  });


  // Styles for our enhancement panel
  GM_addStyle(`
       @import url("https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css");
      @import url("https://cdn.jsdelivr.net/npm/[email protected]/dist/css/iziToast.min.css");
      :root {
              --primary-custom: #ff0000 !important;
              --bg-dark-custom: #1a1a1a !important;
              --bg-card-custom: #252525 !important;
              --text-custom: #ffffff !important;
              --text-custom-secondary: #9e9e9e !important;
              --accent-custom: #ff4444 !important;
          }
        body .container-mdcm {
              font-family: "Inter", -apple-system, sans-serif;
              color: var(--yt-enhance-menu-text, --text-custom);
        }
        #toggle-button:hover {
          background-color: rgba(255,255,255,0.1);
          border-radius: 50%;
          opacity: 1 !important;
          }
        .container-mdcm {
            width: 420px;
            max-width: 420px;
            background-color: var(--yt-enhance-menu-bg, #252525);
            border-radius: 16px 16px 0 0;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
            backdrop-filter: blur(15px);
            border: 1px solid rgba(255, 255, 255, 0.1);
            display: flex;
            flex-direction: column;
            max-height: 80vh;
            overflow-y: auto;
            overflow-x: hidden;
            height: auto;
        }

        #shareDropdown {
        display: none;
        position: absolute;
        top: 50px;
        right: 100px;
        background-color: var(--yt-enhance-menu-bg, #252525);
        border-radius: 6px;
        padding: 10px;
        box-shadow: rgba(0, 0, 0, 0.2) 0px 4px 12px;
        z-index: 11;
        }
        #shareDropdown a {
        color: var(--text-custom);
        text-decoration: none;
        line-height: 2;
        font-size: 14px;
        }
        #shareDropdown a:hover {
        color: var(--primary-custom);
        }
        .header-mdcm {
            padding: 12px 16px;
            border-bottom: 1px solid rgba(255,255,255,0.1);
            position: sticky;
            top: 0;
            background-color: var(--yt-enhance-menu-bg, #252525);
            border-radius: 16px 16px 0 0;
            z-index: 10;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .header-mdcm h1 {
            font-size: 16px; 
            margin: 0;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 8px;
        }


        .header-mdcm i {
         color: var(--primary-custom)
        }
        

        .icons-mdcm {
            display: flex;
            gap: 4px;
        }
        .icons-mdcm i {
          color: var(--yh-enhance-menu-accent, var(--text-custom));
        }
            

        .icon-btn-mdcm {
            background: rgba(255,255,255,0.1);
            border: none;
            color: var(--text-custom);
            width: 28px; 
            height: 28px; 
            border-radius: 6px; 
            cursor: pointer;
            transition: all 0.3s;
        }

        .icon-btn-mdcm:hover {
            background: rgba(255,255,255,0.2);
            transform: translateY(-2px);
        }

        .icon-btn-mdcm i {
         color: var(--text-custom);
         outline: none;
         text-decoration: none;
        }

        .tabs-mdcm {
            padding: 10px 12px;
            margin: 10px 0;
            position: sticky;
            top: 50px;
            background-color: var(--yt-enhance-menu-bg, #252525);
            z-index: 10;
            display: flex;
            gap: 8px;
            -ms-overflow-style: none; 
            padding-bottom: 8px; 
        }

        

        .tabs-mdcm::-webkit-scrollbar {
            height: 0px;
            background-color: transparent;
        }

        .tabs-mdcm:hover::-webkit-scrollbar {
            height: 6px;
        }

        .tabs-mdcm::-webkit-scrollbar-thumb {
            background-color: rgba(255, 0, 0, 0.5);
            border-radius: 3px;
        }

        .tabs-mdcm::-webkit-scrollbar-track {
            background-color: transparent;
        }

        .tab-mdcm {
            padding: 6px 10px;
            border: none;
            background: rgba(255,255,255,0.05);
            cursor: pointer;
            font-size: 12px;
            color: var(--text-custom-secondary);
            border-radius: 6px;
            transition: all 0.3s;
            flex: 1;
            display: flex;
            align-items: center;
            gap: 6px;
            flex-shrink: 0;
            justify-content: center;
            white-space: nowrap;
        }

        .tab-mdcm svg {
            width: 14px;
            height: 14px;
            fill: currentColor;
        }

        .tab-mdcm.active {
            background: var(--yt-enhance-menu-accent, --primary-custom) !important;
            color: var(--text-custom);
            font-weight: 500;
            box-shadow: 0 4px 12px rgba(255,0,0,0.2);
        }

        .tab-mdcm:hover:not(.active) {
            background: rgba(255,255,255,0.1);
            transform: translateY(-1px);
        }

        .options-mdcm {
            flex: 1;
            overflow-y: auto;
            padding: 0 16px 0;
            scrollbar-width: thin;
            scrollbar-color: var(--primary-custom) var(--bg-dark-custom);
            max-height: 300px;
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); 
            gap: 8px;
        }

        .options-settings-mdcm {
            flex: 1;
            overflow-y: auto;
            padding: 0 16px 0;
            scrollbar-width: thin;
            scrollbar-color: var(--primary-custom) var(--bg-dark-custom);
            max-height: 300px;
            display: grid;
            gap: 8px;
        }

         .card-items-end {
          display: flex;
          justify-content: space-between;
          align-items: center;
          width: 175px;
        }

         .radio-mdcm {
            width: 14px;
            height: 14px;
            accent-color: var(--primary-custom);
        }
       
        .color-picker-mdcm {
            width: 50px;
            height: 24px;
            border: 1px solid rgba(255, 255, 255, 0.2);
            background: rgba(255, 255, 255, 0.1);
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.3s;
        }

        .color-picker-mdcm:hover {
            background: rgba(255, 255, 255, 0.2);
        }

        .options-mdcm::-webkit-scrollbar, .options-settings-mdcm::-webkit-scrollbar {
            width: 6px;
        }

        .options-mdcm::-webkit-scrollbar-track, .options-settings-mdcm::-webkit-scrollbar-track {
            background: var(--bg-dark-custom);
            border-radius: 3px;
        }

        .options-mdcm::-webkit-scrollbar-thumb, .options-settings-mdcm::-webkit-scrollbar-thumb {
            background: var(--primary-custom);
            border-radius: 3px;
        }

        .options-mdcm::-webkit-scrollbar-thumb:hover, .options-settings-mdcm::-webkit-scrollbar-thumb:hover {
            background: var(--accent-custom);
        }

        .options-mdcm::after, .options-settings-mdcm::after {
            content: '';
            display: block;
        }

        .option-mdcm {
            display: grid;
            grid-template-columns: auto 1fr; 
            align-items: center;
            margin-bottom: 0; 
            padding: 5px; 
            background: rgba(255,255,255,0.05);
            border-radius: 6px; 
            transition: all 0.3s;
            border: 1px solid rgba(255,255,255,0.05);
            color: var(--yt-)
            gap: 6px;
        }

        .option-mdcm:hover {
            background: rgba(255,255,255,0.08);
            border-color: rgba(255,255,255,0.1);
        }
        .option-settings-mdcm {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 0;
          padding: 6px;
          background: rgba(255, 255, 255, 0.05);
          border-radius: 6px;
          transition: all 0.3s;
          border: 1px solid rgba(255, 255, 255, 0.05);
          gap: 6px;
        }

        .option-settings-mdcm:hover {
            background: rgba(255,255,255,0.08);
            border-color: rgba(255,255,255,0.1);
        }
            .tab-content {
            display: none;
        }
            .tab-content.active {
                display: block;
                margin-bottom: 10px;
            }

        .checkbox-mdcm {
            width: 14px; 
            height: 14px; 
            accent-color: var(--yt-enhance-menu-accent, --primary-custom) !important;
        }

        label {
            font-size: 12px; 
            color: var(--text-custom);
        }

        .slider-container-mdcm {
            background: rgba(255,255,255,0.05);
            padding: 10px; 
            border-radius: 6px; 
        }

        .slider-mdcm {
            width: 100%;
            height: 3px;
            accent-color: var(--yt-enhance-menu-accent, --primary-custom) !important;
            margin: 10px 0; 
        }

        .reset-btn-mdcm {
            padding: 5px 10px; 
            border: 1px solid rgba(255,255,255,0.2);
            background: rgba(255,255,255,0.1);
            color: var(--text-custom);
            border-radius: 4px;
            cursor: pointer;
            font-size: 11px; 
            transition: all 0.3s;
        }

        .reset-btn-mdcm:hover {
            background: rgba(255,255,255,0.2);
        }

        .quality-selector-mdcm select {
            position: relative;
            padding: 3px; 
            outline: none;
            border-radius: 4px;
            border: 1px solid rgba(255,255,255,0.2);
            background: var(--yt-enhance-menu-accent, --primary-custom) !important;
            color: var(--text-custom);
            width: fit-content;
            appearance: none;
            cursor: pointer;
            font-size: 11px; 
        }
       

        .quality-selector-mdcm {
            background: rgba(255,255,255,0.05);
            padding: 10px; 
            border-radius: 6px; 
        }

        .select-wrapper-mdcm {
          position: relative;
          display: inline-block;
        }

        .select-wrapper-mdcm select {
          -webkit-appearance: auto;
          -moz-appearance: auto;
        }
        
        .actions-mdcm {
            position: sticky;
            top: 0;
            padding: 12px 16px;
            backdrop-filter: blur(15px);
            background-color: var(--yt-enhance-menu-bg, #252525);
            display: flex;
            gap: 6px;
            width: 390px;
            border-radius: 0 0 16px 16px;
            justify-content: space-between;
            align-items: center;
        }

        .action-buttons-mdcm {
            display: flex;
            gap: 6px;
        }

        .action-btn-mdcm {
            flex: 1;
            padding: 8px; 
            border: none;
            border-radius: 6px; 
            background: var(--primary-custom);
            color: var(--text-custom);
            cursor: pointer;
            font-size: 12px; 
            font-weight: 500;
            transition: all 0.3s;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 4px; 
            box-shadow: 0 4px 12px rgba(255,0,0,0.2);
        }

        .action-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 16px rgba(255,0,0,0.3);
        }

        textarea.textarea-mdcm {
            width: 100%;
            height: 50px; 
            margin-top: 10px; 
            margin-bottom: 12px; 
            padding: 8px; 
            background: rgba(255,255,255,0.05);
            border: 1px solid rgba(255,255,255,0.1);
            border-radius: 6px;
            color: var(--text-custom);
            font-size: 11px; 
            resize: none;
            transition: all 0.3s;
        }

        textarea.textarea-mdcm:focus {
            outline: none;
            border-color: var(--primary-custom);
            background: rgba(255,255,255,0.08);
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .container-mdcm {
            animation: fadeIn 0.3s ease-out;
        }

        .developer-mdcm {
            font-size: 10px;
            color: var(--text-custom-secondary);
        }

        .developer-mdcm a {
            color: var(--primary-custom);
            text-decoration: none;
        }

        /* Styles for the import/export area */
        #importExportArea {
            display: none;
            padding: 16px;
            margin: 0px;
            background-color: var(--yt-enhance-menu-bg, #252525);
            border-radius: 16px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
        }

        #importExportArea.active {
            display: block;
            margin-top: 10px;
        }

        /* Style the textarea */
        #importExportArea textarea {
            width: 370px;
            height: 20px;
            margin-bottom: 10px;
            padding: 8px;
            border: 1px solid rgba(255, 255, 255, 0.2);
            border-radius: 6px;
            background-color: rgba(255, 255, 255, 0.05);
            color: var(--text-custom);
            font-size: 12px;
            resize: vertical;
        }

        /* Style the buttons */
        #importExportArea .action-buttons-mdcm  {
            display: flex;
            justify-content: space-between;
            gap: 10px;
        }

        #importExportArea .action-btn-mdcm {
            flex: 1;
            padding: 10px 16px;
            border: none;
            border-radius: 6px;
            background-color: var(--primary-custom);
            color: var(--text-custom);
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }

        #importExportArea .action-btn-mdcm:hover {
            background-color: var(--accent-custom);
        }
           
      #yt-stats {
      position: fixed;
      top: 60px;
      right: 20px;
      background: #1a1a1a;
      color: white;
      padding: 15px;
      border-radius: 10px;
      width: 320px;
      box-shadow: 0 4px 12px rgba(0,0,0,0.4);
      font-family: Arial, sans-serif;
      display: none;
      }
  #yt-stats-toggle {
      font-size: 12px;
      color: #fff;
      padding: 12px 20px;
      border-radius: 5px;
      cursor: pointer;
  }
  .stat-row {
      margin: 15px 0;
  }
  .progress {
      height: 6px;
      background: #333;
      border-radius: 3px;
      margin: 8px 0;
  }
  .progress-bar {
      height: 100%;
      transition: width 0.3s;
  }
  .total-bar { background: #44aaff; }
  .video-bar { background: #00ff88; }
  .shorts-bar { background: #ff4444; }
  #cinematics {
    position: absolute !important;
    width: 90vw !important;
    height: 100vh ;
  }
    #cinematics div {
        position: fixed;
      inset: 0px;
      pointer-events: none;
      transform: scale(1.5, 2);
  }
      #cinematics > div > div > canvas:nth-child(1), #cinematics > div > div > canvas:nth-child(2) {
   position: absolute !important;
    width: 90vw !important;
    height: 100vh ;
      }

    // .html5-video-player.unstarted-mode {
    //  background-image: url('https://avatars.githubusercontent.com/u/54366580?v=4');
    // background-repeat: no-repeat;
    // background-position: 50% 50%;
    // display: flex;
    // justify-content: center;
    // align-items: center;
    // }
    
        #yt-enhancement-panel {
            position: fixed;
            top: 60px;
            right: 20px;
            z-index: 9999;
        }
       
        .color-picker {
            width: 100%;
            margin: 0;
            padding: 0;
            border: none;
            background: none;
        }
        .slider {
            width: 100%;
        }
         #toggle-panel {
            z-index: 10000;
            color: white;
            padding: 5px;
            border: none;
            cursor: pointer;
            display: flex;
            justify-content: center;
            transition: all 0.5s ease;
            width: 43px;
            border-radius: 100px;
        }
            
        #icon-menu-settings {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 24px;
        height: 24px;
        padding: 7px;
        font-size: 20px;
        color: var(--yt-spec-icon-inactive);
        cursor: pointer;
        user-select: none;
        filter: drop-shadow(2px 4px 6px black);
        }
    
        .theme-option {
            margin-bottom: 15px;
        }
        .theme-option label {
            display: flex;
            align-items: center;
        }
       .theme-option {
    position: relative;
    width: auto;
    margin-bottom: 10px;
    padding: 10px;
    border-radius: 4px;
    cursor: pointer;
}

.theme-preview {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    border-radius: 10px;
    border: 1px solid #000;
    z-index: 1;
}

.theme-option input[type="radio"] {
    position: relative;
    z-index: 2;
    margin-right: 10px;
    cursor: pointer;
}

.theme-name {
    position: relative;
    z-index: 2;
    font-size: 15px;
    color: #fff;
}

.theme-option label {
    display: flex;
    align-items: center;
    width: 100%;
    position: relative;
    z-index: 2;
}

  .buttons-tranlate, .select-traductor {
        background: #000;
        font-size: 10px;
        border: none;
        color: #fbf4f4 !important;
        padding: 3px 0;
        margin-left: 10px;
        width: 70px;
        border-radius: 10px;
        }
        .buttons-tranlate:hover {
        cursor: pointer;
        background-color: #6b6b6b;
        }
         button.botones_div {
         margin: 0;
         padding: 0;
         }

        .tab-button:hover {
          background-color: #ec3203 !important;
          color: #ffffff !important;
          cursor: pointer;
        }

        .traductor-container {
            display: inline-block;
            align-items: center;
            gap: 8px;
            margin-top: 4px;
          }
         
        #eyes {
      opacity: 0;
      position: absolute;
      height: 24px;
      left: 0;
      width: 24px;
    }

    /* width */
    ::-webkit-scrollbar {
      width: 4px;
      height: 10px;
    }

    /* Track */
    ::-webkit-scrollbar-track {
      background: ##d5d5d5;

    }

    /* Handle */
    ::-webkit-scrollbar-thumb {
      background: #000;

    }

    .color-boxes {
      display: flex;
      gap: 8px;
    }
    .color-box {
      width: 20px;
      height: 20px;
      border: 1px solid rgb(221 221 221 / 60%);
      border-radius: 4px;
      cursor: pointer;
    }
    .color-box.selected {
      border: 2px solid var(--primary-custom); 
      filter: drop-shadow(0px 1px 6px red);
    }

    .containerButtons {
      display: flex;
      justify-content: center;
      align-items: center;
      flex-wrap: wrap;
      gap: 10px;
    }
    .containerButtons > button:hover {
      cursor: pointer;
    }
      
      body {
      padding: 0;
      margin: 0;
      overflow-y: scroll;
      overflow-x: hidden;
      }
      .style-scope.ytd-comments {
      overflow-y: auto;
      overflow-x: hidden;
      height: auto;
      }
      ytd-comment-view-model[is-reply] #author-thumbnail.ytd-comment-view-model yt-img-shadow.ytd-comment-view-model, ytd-comment-view-model[is-creator-reply] #author-thumbnail.ytd-comment-view-model yt-img-shadow.ytd-comment-view-model {
        width: 40px;
        height: 40px;
        border-radius: 50%;
      }
        img.yt-img-shadow {
        border-radius: 50% !important;
        }
        #author-thumbnail.ytd-comment-view-model yt-img-shadow.ytd-comment-view-model {
          width: 40px;
          height: 40px;
          border-radius: 50%;
          overflow: visible;
        }
      ytd-item-section-renderer.ytd-watch-next-secondary-results-renderer {
        --ytd-item-section-item-margin: 8px;
        overflow-y: auto;
        overflow-x: hidden;
        height: auto;
      }
      .right-section.ytcp-header {
      display: flex;
      flex: 1;
      align-items: center;
      gap: 45px;
      justify-content: end;
    }
      #meta.ytd-playlist-panel-video-renderer {
    min-width: 0;
    padding: 0 8px;
    display: flexbox;
    display: flex;
    flex-direction: column-reverse;
    flex: 1;
    flex-basis: 0.000000001px;
}

    .containerall {
        display: flex;
    align-items: center;
    justify-content: center;
    width: 50%;
    margin: auto;
}
    }
    .container .botoncalidades {
      margin: 3px 2px;
      width: 24.6%;
    }

    .botoncalidades:first-child {
      background-color: #0af;
    }

    .botoncalidades:last-child {
      background-color: red;
      width: 100px;
    }

    .selectcalidades,
    .botoncalidades,
    .selectcalidadesaudio {
      width: 50%;
      height: 27.8px;
      background-color: #fff;
      color: #000;
      font-size: 25px;
      text-align: center;
      border: 1px solid black;
      border-radius: 10px;
      border: none;
      font-size: 20px;
      margin: 2px 2px;
    }

    .botoncalidades {
      width: 70px;
      height: 30px;
      background-color: rgb(4, 156, 22);
      border: 0px solid #000;
      color: #fff;
      font-size: 20px;
      border-radius: 10px;
      margin: 2px 2px;
    }

    .botoncalidades:hover,
    .bntcontainer:hover {
      cursor: pointer;
    }

   .ocultarframe,
    .ocultarframeaudio {
      display: none;
    }
      .checked_updates {
      cursor: pointer;
      }

      #export-config, #import-config {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 10px;
        background-color: var(--yt-enhance-menu-accent, --primary-custom) !important;;
        color: #ffffff;
        border: none;
        padding: 5px;
      }
        #export-config:hover, #import-config:hover {
          background-color: #ff0000;
          color: #ffffff;
          cursor: pointer;
        }

        .yt-image-avatar-download {
          position: absolute;
          bottom: -10px;
          right: -14px;
          border: none;
          z-index: 1000;
          background: transparent;
          filter: drop-shadow(1px 0 6px red);
          color: var(--ytcp-text-primary);
          cursor: pointer;
        }

        .custom-classic-btn {
          display: flex;
          align-items: center;
          justify-content: center;
          background-color: rgba(255,255,255,0.1);
          border-radius: 50%;
          border: none;
          width: 48px;
          height: 48px;
          color: var(--yt-spec-icon-inactive);
          font-size: 24px;
          margin: 0px 8px;
          cursor: pointer;
        }
        .custom-classic-btn:hover {
          background-color: rgba(255,255,255,0.2);
        }
    `);


  // botons bottom video player

  const thumbnailVideo = `
  <button title="Image video" class="botones_div" type="button" id="imagen">

  <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-photo-down" width="24"
    height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none"
    stroke-linecap="round" stroke-linejoin="round">
    <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
    <path d="M15 8h.01"></path>
    <path d="M12.5 21h-6.5a3 3 0 0 1 -3 -3v-12a3 3 0 0 1 3 -3h12a3 3 0 0 1 3 3v6.5"></path>
    <path d="M3 16l5 -5c.928 -.893 2.072 -.893 3 0l4 4"></path>
    <path d="M14 14l1 -1c.653 -.629 1.413 -.815 2.13 -.559"></path>
    <path d="M19 16v6"></path>
    <path d="M22 19l-3 3l-3 -3"></path>
  </svg>
</button>
  `;
 

  const filterEyes = `
  <div style="position:relative; ">
  <button title="Filter eyes" class="botones_div" type="button">
    <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-brightness-half"
      width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"
      fill="none" stroke-linecap="round" stroke-linejoin="round">
      <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
      <path d="M12 9a3 3 0 0 0 0 6v-6z"></path>
      <path
        d="M6 6h3.5l2.5 -2.5l2.5 2.5h3.5v3.5l2.5 2.5l-2.5 2.5v3.5h-3.5l-2.5 2.5l-2.5 -2.5h-3.5v-3.5l-2.5 -2.5l2.5 -2.5z">
      </path>
    </svg>
    <input id="eyes" list="presetColors" type="color" value="#ffffff">
  <datalist id="presetColors">
    <option value="#000000" />
    <option value="#fbff00" />
    <option value="#ff0000" />
    <option value="#00ff00" />
    <option value="#0000ff" />
  </datalist>
  <div id="ojosprotect"
  style="position: fixed; pointer-events: none; width: 100%; height: 100%; left: 0px; top: 0px; opacity: 0.2; z-index: 10; display: block;">
  </div>
</div>
</button>
  `;

  const resetButton = `
  <button title="reset" class="botones_div" type="button" id="reset_button">
  <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-power" width="24"
    height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none"
    stroke-linecap="round" stroke-linejoin="round">
    <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
    <path d="M7 6a7.75 7.75 0 1 0 10 0"></path>
    <path d="M12 4l0 8"></path>
  </svg>
</button>
  `;

  const repeatVideo = `
  <button title="Repeat video" class="botones_div" type="button" id="repeatvideo">

  <svg  xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-repeat" width="24"
    height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none"
    stroke-linecap="round" stroke-linejoin="round">
    <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
    <path d="M4 12v-3a3 3 0 0 1 3 -3h13m-3 -3l3 3l-3 3"></path>
    <path d="M20 12v3a3 3 0 0 1 -3 3h-13m3 3l-3 -3l3 -3"></path>
  </svg>
</button>
  `;

  const downloadMp4Mp3 = `
  <button title="MP4" type="button" class="btn1 botones_div">
  <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-file-download"
    width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none"
    stroke-linecap="round" stroke-linejoin="round">
    <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
    <path d="M14 3v4a1 1 0 0 0 1 1h4"></path>
    <path d="M17 21h-10a2 2 0 0 1 -2 -2v-14a2 2 0 0 1 2 -2h7l5 5v11a2 2 0 0 1 -2 2z"></path>
    <path d="M12 17v-6"></path>
    <path d="M9.5 14.5l2.5 2.5l2.5 -2.5"></path>
  </svg>
</button>
<button title="MP3" type="button" class="btn2 botones_div">

  <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-file-music" width="24"
    height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none"
    stroke-linecap="round" stroke-linejoin="round">
    <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
    <path d="M14 3v4a1 1 0 0 0 1 1h4"></path>
    <path d="M17 21h-10a2 2 0 0 1 -2 -2v-14a2 2 0 0 1 2 -2h7l5 5v11a2 2 0 0 1 -2 2z"></path>
    <path d="M11 16m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0"></path>
    <path d="M12 16l0 -5l2 1"></path>
  </svg>
</button>
<button title="Close" type="button" class="btn3 botones_div">
<svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-circle-x" width="24"
  height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none"
  stroke-linecap="round" stroke-linejoin="round">
  <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
  <path d="M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0 -18 0"></path>
  <path d="M10 10l4 4m0 -4l-4 4"></path>
</svg>
</button>
  `;

  const donwloadExternal = `

  <button title="External Download" type="button" class="external_link botones_div">

  <svg class="icon icon-tabler icon-tabler-external-link" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
      <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
      <path d="M12 6h-6a2 2 0 0 0 -2 2v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2 -2v-6"></path>
      <path d="M11 13l9 -9"></path>
      <path d="M15 4h5v5"></path>
   </svg>
</button>

  `;
  const viewExternalVideo = `

  <button title="view External no cookie" type="button" class="view_external_link botones_div">

  <svg width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M3 16m0 1a1 1 0 0 1 1 -1h3a1 1 0 0 1 1 1v3a1 1 0 0 1 -1 1h-3a1 1 0 0 1 -1 -1z" /><path d="M4 12v-6a2 2 0 0 1 2 -2h12a2 2 0 0 1 2 2v12a2 2 0 0 1 -2 2h-6" /><path d="M12 8h4v4" /><path d="M16 8l-5 5" /></svg>
</button>

  `;

  const pictureToPicture = `
  <button title="Picture to picture" type="button" class="video_picture_to_picture botones_div">

  <svg width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M11 19h-6a2 2 0 0 1 -2 -2v-10a2 2 0 0 1 2 -2h14a2 2 0 0 1 2 2v4" /><path d="M14 14m0 1a1 1 0 0 1 1 -1h5a1 1 0 0 1 1 1v3a1 1 0 0 1 -1 1h-5a1 1 0 0 1 -1 -1z" /></svg>
</button>

  `;
  const screenShot = `
  <button title="Screenshot video" type="button" class="screenshot_video botones_div">
  <svg width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M15 8h.01" /><path d="M6 13l2.644 -2.644a1.21 1.21 0 0 1 1.712 0l3.644 3.644" /><path d="M13 13l1.644 -1.644a1.21 1.21 0 0 1 1.712 0l1.644 1.644" /><path d="M4 8v-2a2 2 0 0 1 2 -2h2" /><path d="M4 16v2a2 2 0 0 0 2 2h2" /><path d="M16 4h2a2 2 0 0 1 2 2v2" /><path d="M16 20h2a2 2 0 0 0 2 -2v-2" /></svg>
</button>

  `;

  const checkUpdates = `
  <button title="Check new updates" type="button" class="checked_updates botones_div">
  <svg width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M20 11a8.1 8.1 0 0 0 -15.5 -2m-.5 -4v4h4" /><path d="M4 13a8.1 8.1 0 0 0 15.5 2m.5 4v-4h-4" /></svg>
</button>
  `;

  const bufferVideo = `
  <button title="Buffer video" type="button" class="buffer_video botones_div">
 <svg width="24"  height="24"  viewBox="0 0 24 24"  fill="none"  stroke="currentColor"  stroke-width="2"  stroke-linecap="round"  stroke-linejoin="round"  class="icon icon-tabler icons-tabler-outline icon-tabler-align-box-right-stretch"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M15 17h2" /><path d="M3 5a2 2 0 0 1 2 -2h14a2 2 0 0 1 2 2v14a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2v-14z" /><path d="M11 12h6" /><path d="M13 7h4" /></svg>
</button>
  `;


  const menuBotones = `
    <main>
    <div class="container">
    <form>
      <div class="containerButtons">
      ${thumbnailVideo}
      ${bufferVideo}
      ${filterEyes}
      ${resetButton}
      ${repeatVideo}
      ${downloadMp4Mp3}
      ${donwloadExternal}
      ${viewExternalVideo}
      ${pictureToPicture}
      ${screenShot}
      ${checkUpdates}
      </div>
      <div>
      </div>
    </form>

    </div>
    <div class="content_collapsible_colors" style="margin-top: 10px">

    <form class="formulariodescarga" action="">
    <div class="containerall">
    <select class="selectcalidades  ocultarframe" required>
      <option selected disabled>Calidad del video / Quality video</option>
      <option value="360">360p Mp4</option>
      <option value="480">480p Mp4</option>
      <option value="720">720p HD Mp4 Default</option>
      <option value="1080">1080p FULL HD Mp4</option>
      <option value="4k">2160p 4K WEBM</option>
      <option value="8k">4320p 8K WEBM</option>
      </select>
      <iframe id="descargando"  style="z-index: 99; border: none; height: 27.4px; width: 50%;"  class="containerall ocultarframe" src="" frameborder="0"></iframe>

    </div>
    </form>
    <form class="formulariodescargaaudio" action="">
    <div class="containerall">
    <select class="selectcalidadesaudio ocultarframeaudio" required>
      <option selected disabled>Calidad del Audio / Quality Audio</option>
      <option value="flac">Audio FLAC UHQ</option>
      <option value="wav">Audio WAV UHQ</option>
      <option value="mp3">Audio MP3 Default</option>
      <option value="m4a">Audio M4A</option>
      <option value="aac">Audio AAC</option>
      <option value="opus">Audio OPUS</option>
      <option value="ogg">Audio OGG</option>
      </select>
      <iframe id="descargandomp3"  style="z-index: 99; border: none; height: 27.4px; width: 50%;"  class="containerall ocultarframeaudio" src="" frameborder="0"></iframe>

      </iframe>

    </div>
    </form>
      </main>
  `;

  

  // Define themes
  const themes = [
    {
      name: 'Default / Reload',
      gradient: '',
      textColor: '',
      raised: '',
      btnTranslate: '',
      CurrentProgressVideo: '',
      videoDuration: '',
      colorIcons: '',
      textLogo: '',
      primaryColor: '',
      secondaryColor: '',
    },
    {
      name: 'Midnight Blue',
      gradient: 'linear-gradient(135deg, #1e3a8a, #3b82f6)',
      textColor: '#ffffff',
      raised: '#f00',
      btnTranslate: '#000',
      CurrentProgressVideo: '#0f0',
      videoDuration: '#fff',
      colorIcons: '#fff',
      textLogo: '#f00',
    },
    {
      name: 'Forest Green',
      gradient: 'linear-gradient(135deg, #14532d, #22c55e)',
      textColor: '#ffffff',
      raised: '#303131',
      btnTranslate: '#000',
      CurrentProgressVideo: '#0f0',
      videoDuration: '#fff',
      colorIcons: '#fff',
      textLogo: '#f00',
    },
    {
      name: 'Sunset Orange',
      gradient: 'linear-gradient(135deg, #7c2d12, #f97316)',
      textColor: '#ffffff',
      raised: '#303131',
      btnTranslate: '#000',
      CurrentProgressVideo: '#0f0',
      videoDuration: '#fff',
      colorIcons: '#fff',
      textLogo: '#f00',
    },
    {
      name: 'Royal Purple',
      gradient: 'linear-gradient(135deg, #4c1d95, #8b5cf6)',
      textColor: '#ffffff',
      raised: '#303131',
      btnTranslate: '#000',
      CurrentProgressVideo: '#0f0',
      videoDuration: '#fff',
      colorIcons: '#fff',
      textLogo: '#f00',
    },
    {
      name: 'Cherry Blossom',
      gradient: 'linear-gradient(135deg, #a9005c, #fc008f)',
      textColor: '#ffffff',
      raised: '#fc008f',
      btnTranslate: '#000',
      CurrentProgressVideo: '#0f0',
      videoDuration: '#fff',
      colorIcons: '#fff',
      textLogo: '#f00',
    },
    {
      name: 'Red Dark',
      gradient: 'linear-gradient(135deg, #790909, #f70131)',
      textColor: '#ffffff',
      raised: '#303131',
      btnTranslate: '#000',
      CurrentProgressVideo: '#0f0',
      videoDuration: '#fff',
      colorIcons: '#fff',
      textLogo: '#f00',
    },
    {
      name: 'Raind ',
      gradient: 'linear-gradient(90deg, #3f5efb 0%, #fc466b) 100%',
      textColor: '#ffffff',
      raised: '#303131',
      btnTranslate: '#000',
      CurrentProgressVideo: '#0f0',
      videoDuration: '#fff',
      colorIcons: '#fff',
      textLogo: '#f00',
    },
    {
      name: 'Neon',
      gradient: 'linear-gradient(273deg, #ee49fd 0%, #6175ff 100%)',
      textColor: '#ffffff',
      raised: '#303131',
      btnTranslate: '#000',
      CurrentProgressVideo: '#0f0',
      videoDuration: '#fff',
      colorIcons: '#fff',
      textLogo: '#f00',
    },
    {
      name: 'Azure',
      gradient: 'linear-gradient(273deg, #0172af 0%, #74febd 100%)',
      textColor: '#ffffff',
      raised: '#303131',
      btnTranslate: '#000',
      CurrentProgressVideo: '#0f0',
      videoDuration: '#fff',
      colorIcons: '#fff',
      textLogo: '#f00',
    },
    {
      name: 'Butterfly',
      gradient: 'linear-gradient(273deg, #ff4060 0%, #fff16a 100%)',
      textColor: '#ffffff',
      raised: '#303131',
      btnTranslate: '#000',
      CurrentProgressVideo: '#0f0',
      videoDuration: '#fff',
      colorIcons: '#fff',
      textLogo: '#f00',
    },
    {
      name: 'Colombia',
      gradient:
        'linear-gradient(174deg, #fbf63f  0%, #0000bb 45%, #ff0000 99%)',
      textColor: '#ffffff',
      raised: '#303131',
      btnTranslate: '#000',
      CurrentProgressVideo: '#0f0',
      videoDuration: '#fff',
      colorIcons: '#fff',
      textLogo: '#f00',
    },
  ];

  // Create our enhancement panel
  const panel = $cl('div');

  panel.id = 'yt-enhancement-panel';

  // Generate theme options HTML
  const themeOptionsHTML = themes
    .map(
      (theme, index) => `
        <label >
          <div class="theme-option">
          <div class="theme-preview" style="background: ${theme.gradient};"></div>
          <input type="radio" name="theme" value="${index}" ${
              index === 0 ? 'checked' : ''
            }>
              <span style="${theme.name === 'Default / Reload Page' ? 'color: red; ' : '' }" class="theme-name">${theme.name}</span>
              </div>
        </label>
    `
    )
    .join('');

    const languageOptionsHTML = Object.entries(languagesTranslate)
    .map(([code, name]) => {
      const selected = code === languagesTranslate ? 'selected' : '';
      return `<option value="${code}" ${selected}>${name}</option>`;
    })
    .join('');



    function checkDarkModeActive() {
      const pref = document.cookie.split('; ').find(c => c.startsWith('PREF='));
      if (!pref) return 'light';
    
      const params = new URLSearchParams(pref.split('&').join('&'));
      const darkModes = ['400', '4000000', '40000400', '40000000'];
      return darkModes.includes(params.get('f6')) ? 'dark' : 'light';
    }

  let isDarkModeActive = checkDarkModeActive();


  // Use Trusted Types to set innerHTML
  const menuHTML = `
   <div class="container-mdcm">
    <div class="header-mdcm">
      <h1> <i class="fa-brands fa-youtube"></i> YouTube Tools</h1>
      <div class="icons-mdcm">
        <a href="https://update.greasyfork.org/scripts/460680/Youtube%20Tools%20All%20in%20one%20local%20download%20mp3%20mp4%20HIGT%20QUALITY%20return%20dislikes%20and%20more.user.js"
          target="_blank">
          <button class="icon-btn-mdcm">
            <i class="fa-solid fa-arrows-rotate"></i>
          </button>
        </a>
        <a href="https://github.com/DeveloperMDCM" target="_blank">
          <button class="icon-btn-mdcm">
            <i class="fa-brands fa-github"></i>
          </button>
        </a>
        <button class="icon-btn-mdcm" id="shareBtn-mdcm">
          <i class="fa-solid fa-share-alt"></i>
        </button>
        <button class="icon-btn-mdcm" id="importExportBtn">
          <i class="fa-solid fa-file-import"></i>
        </button>
        <button id="menu-settings-icon" class="icon-btn-mdcm tab-mdcm" data-tab="menu-settings">
          <i class="fa-solid fa-gear"></i>
        </button>
        <button class="icon-btn-mdcm close_menu_settings">
          <i class="fa-solid fa-xmark"></i>
        </button>
      </div>
    </div>

    <div class="tabs-mdcm">
      <button class="tab-mdcm active" data-tab="general">
        <i class="fa-solid fa-shield-halved"></i>
        General
      </button>
      <button class="tab-mdcm" data-tab="themes">
        <i class="fa-solid fa-palette"></i>
        Themes
      </button>
      <button class="tab-mdcm" data-tab="stats">
        <i class="fa-solid fa-square-poll-vertical"></i>
        Stats
      </button>
      <button class="tab-mdcm" data-tab="headers">
        <i class="fa-regular fa-newspaper"></i>
        Header
      </button>
    </div>


    <div id="general" class="tab-content active">

      <div class="options-mdcm">
        <label>
          <div class="option-mdcm">
            <input type="checkbox" class="checkbox-mdcm" id="hide-comments-toggle"> Hide Comments
          </div>
        </label>
        <label>
          <div class="option-mdcm">
            <input type="checkbox" class="checkbox-mdcm" id="hide-sidebar-toggle"> Hide Sidebar
          </div>
        </label>
        <label>
          <div class="option-mdcm">
            <input type="checkbox" class="checkbox-mdcm" id="autoplay-toggle"> Disable Autoplay
          </div>
        </label>
        <label>
          <div class="option-mdcm">
            <input type="checkbox" class="checkbox-mdcm" id="subtitles-toggle"> Disable Subtitles
          </div>
        </label>
        <label>
          <div class="option-mdcm">
            <input type="checkbox" class="checkbox-mdcm" checked id="dislikes-toggle"> Show Dislikes
          </div>
        </label>
        <label>
          <div class="option-mdcm">
            <input type="checkbox" class="checkbox-mdcm" id="themes-toggle"> Active Themes
          </div>
        </label>
        <label>
          <div class="option-mdcm">
            <input type="checkbox" class="checkbox-mdcm" id="translation-toggle"> Translate comments
          </div>
        </label>
        <label>
          <div class="option-mdcm">
            <input type="checkbox" class="checkbox-mdcm" id="avatars-toggle"> Download avatars
          </div>
        </label>
        <label>
          <div class="option-mdcm">
            <input type="checkbox" class="checkbox-mdcm" id="reverse-mode-toggle"> Reverse mode
          </div>
        </label>
        <label>
          <div class="option-mdcm">
            <input type="checkbox" class="checkbox-mdcm" checked id="wave-visualizer-toggle"> Wave visualizer Beta
          </div>
        </label>
        <div class="quality-selector-mdcm" style="grid-column: span 2;">
          <div class="select-wrapper-mdcm">
            <label>Effect wave visualizer:
              <select class="tab-button-active" id="select-wave-visualizer-select">
                <option value="linea">Line smooth</option>
                <option value="barras">Vertical bars</option>
                <option value="curva">Curved</option>
                <option value="picos">Smooth peaks</option>
                <option value="solida">Solid wave</option>
                <option value="dinamica">Dynamic wave</option>
                <option value="montana">Smooth mountain</option>
              </select>
            </label>
          </div>
        </div>
        <div class="quality-selector-mdcm" style="grid-column: span 2;">
          <div class="select-wrapper-mdcm">
            <label>Default video player quality:
              <select class="tab-button-active" id="select-video-qualitys-select">
                <option value="144">144</option>
                <option value="240">240</option>
                <option value="360">360</option>
                <option value="480">480</option>
                <option value="720">720</option>
                <option value="1080">1080</option>
                <option value="1440">1440</option>
                <option value="2160">2160</option>
              </select>
            </label>
          </div>
        </div>
        <div class="quality-selector-mdcm" style="grid-column: span 2;">
          <div class="select-wrapper-mdcm">
            <label>Language for translate comments: 
              <select class="tab-button-active" id="select-languages-comments-select">
              ${languageOptionsHTML}
              </select>
            </label>
          </div>
        </div>
        <div class="slider-container-mdcm" style="grid-column: span 2;">
          <label>Video Player Size: <span id="player-size-value">100</span>%</label>
          <input type="range" id="player-size-slider" class="slider-mdcm" min="50" max="150" value="100">
          <button class="reset-btn-mdcm" id="reset-player-size">Reset video size</button>
        </div>
      </div>
    </div>

    <div id="themes" class="tab-content">
      <div class="themes-hidden">
        <div class="options-mdcm" style="margin-bottom: 10px;">
          <div>
            <h4>Choose a Theme</h4>
            <p>Disable cinematic Lighting</p>
            ${isDarkModeActive === 'dark' ? '' : '<p style="color: red; margin: 10px 0;font-size: 11px;">Activate dark mode to use this option</p>'}
          </div>
        </div>
        <div class="options-mdcm">
          <label>
            <div class="theme-option option-mdcm">
              <input type="radio" class="radio-mdcm" name="theme" value="custom" checked>
              <span class="theme-name">Custom</span>
            </div>
          </label>
          <label>
            <div class="theme-option option-mdcm theme-selected-normal">
              <input type="radio" class="radio-mdcm" name="theme" value="normal">
              <span class="theme-name">Selected Themes</span>
            </div>
          </label>
        </div>
        <div class="themes-options">
          <div class="options-mdcm">
            ${themeOptionsHTML}
          </div>
        </div>
        <div class="theme-custom-options">
          <div class="options-mdcm">
            <div class="option-mdcm">
              <div class="card-items-end">
                <label>Progressbar Video:</label>
                <input type="color" id="progressbar-color-picker" class="color-picker-mdcm" value="#ff0000">
              </div>
            </div>
            <div class="option-mdcm">
              <div class="card-items-end">
                <label>Background Color:</label>
                <input type="color" id="bg-color-picker" class="color-picker-mdcm" value="#000000">
              </div>
            </div>
            <div class="option-mdcm">
              <div class="card-items-end">
                <label>Primary Color:</label>
                <input type="color" id="primary-color-picker" class="color-picker-mdcm" value="#ffffff">
              </div>
            </div>
            <div class="option-mdcm">
              <div class="card-items-end">
                <label>Secondary Color:</label>
                <input type="color" id="secondary-color-picker" class="color-picker-mdcm" value="#ffffff">
              </div>
            </div>
            <div class="option-mdcm">
              <div class="card-items-end">
                <label>Header Color:</label>
                <input type="color" id="header-color-picker" class="color-picker-mdcm" value="#000000">
              </div>
            </div>
            <div class="option-mdcm">
              <div class="card-items-end">
                <label>Icons Color:</label>
                <input type="color" id="icons-color-picker" class="color-picker-mdcm" value="#ffffff">
              </div>
            </div>
            <div class="option-mdcm">
              <div class="card-items-end">
                <label>Menu Color:</label>
                <input type="color" id="menu-color-picker" class="color-picker-mdcm" value="#000000">
              </div>
            </div>
            <div class="option-mdcm">
              <div class="card-items-end">
                <label>Line Color Preview:</label>
                <input type="color" id="line-color-picker" class="color-picker-mdcm" value="#ff0000">
              </div>
            </div>
            <div class="option-mdcm">
              <div class="card-items-end">
                <label>Time Color Preview:</label>
                <input type="color" id="time-color-picker" class="color-picker-mdcm" value="#ffffff">
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div id="stats" class="tab-content">
      <div id="yt-stats-toggle">
        <div class="stat-row">
          <div>Foreground Time</div>
          <div class="progress">
            <div class="progress-bar total-bar" id="usage-bar"></div>
          </div>
          <div id="total-time">0h 0m 0s</div>
        </div>
        <div class="stat-row">
          <div>Video Time</div>
          <div class="progress">
            <div class="progress-bar video-bar" id="video-bar"></div>
          </div>
          <div id="video-time">0h 0m 0s</div>
        </div>
        <div class="stat-row">
          <div>Shorts Time</div>
          <div class="progress">
            <div class="progress-bar shorts-bar" id="shorts-bar"></div>
          </div>
          <div id="shorts-time">0h 0m 0s</div>
        </div>
      </div>
    </div>

    <div id="headers" class="tab-content">
      <div class="options-mdcm">
        <label>Available in next update</label>
      </div>
    </div>


    <div id="menu-settings" class="tab-content">
      <div class="options-mdcm">
        <h4 style="margin: 10px 0">Menu Appearance</h4>
      </div>
      <div class="options-settings-mdcm">
        <div class="option-settings-mdcm">
          <label>Backgrounds:</label>
          <div class="color-boxes" id="bg-color-options">
            <div class="color-box" data-type="bg" data-value="#252525" style="background-color: #252525;"></div>
            <div class="color-box" data-type="bg" data-value="#1e1e1e" style="background-color: #1e1e1e;"></div>
            <div class="color-box" data-type="bg" data-value="#3a3a3a" style="background-color: #3a3a3a;"></div>
            <div class="color-box" data-type="bg" data-value="#4a4a4a" style="background-color: #4a4a4a;"></div>
            <div class="color-box" data-type="bg" data-value="#000000" style="background-color: #000000;"></div>
            <div class="color-box" data-type="bg" data-value="#00000000" style="background-color: #00000000;"></div>
            <div class="color-box" data-type="bg" data-value="#2d2d2d" style="background-color: #2d2d2d;"></div>
            <div class="color-box" data-type="bg" data-value="#444" style="background-color: #444;"></div>
          </div>
        </div>

        <div class="option-settings-mdcm">
          <label>Accent Colors:</label>
          <div class="color-boxes" id="bg-accent-color-options">
            <div class="color-box" data-type="accent" data-value="#ff0000" style="background-color: #ff0000;"></div>
            <div class="color-box" data-type="accent" data-value="#000000" style="background-color: #000000;"></div>
            <div class="color-box" data-type="accent" data-value="#009c37 " style="background-color: #009c37 ;"></div>
            <div class="color-box" data-type="accent" data-value="#0c02a0 " style="background-color: #0c02a0 ;"></div>
          </div>
        </div>

        <div class="option-settings-mdcm">
          <label>Titles Colors:</label>
          <div class="color-boxes" id="text-color-options">
            <div class="color-box" data-type="color" data-value="#ffffff" style="background-color: #ffffff;"></div>
            <div class="color-box" data-type="color" data-value="#cccccc" style="background-color: #cccccc;"></div>
            <div class="color-box" data-type="color" data-value="#b3b3b3" style="background-color: #b3b3b3;"></div>
            <div class="color-box" data-type="color" data-value="#00ffff" style="background-color: #00ffff;"></div>
            <div class="color-box" data-type="color" data-value="#00ff00" style="background-color: #00ff00;"></div>
            <div class="color-box" data-type="color" data-value="#ffff00" style="background-color: #ffff00;"></div>
            <div class="color-box" data-type="color" data-value="#ffcc00" style="background-color: #ffcc00;"></div>
            <div class="color-box" data-type="color" data-value="#ff66cc" style="background-color: #ff66cc;"></div>
          </div>
        </div>
      </div>
    </div>

    <div id="importExportArea">
      <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
        <h3>Import / Export Settings</h3>
        <button class="icon-btn-mdcm" id="closeImportExportBtn">
          <i class="fa-solid fa-xmark"></i>
        </button>
      </div>
      <textarea id="config-data" placeholder="Paste configuration here to import"></textarea>
      <div class="action-buttons-mdcm">
        <button id="export-config" class="action-btn-mdcm">Export</button>
        <button id="import-config" class="action-btn-mdcm">Import</button>
      </div>
    </div>

    <div id="shareDropdown">
      <a href="https://www.facebook.com/sharer/sharer.php?u=${urlSharedCode}" target="_blank" data-network="facebook"
        class="share-link"><i class="fa-brands fa-facebook"></i> Facebook</a><br>
      <a href="https://twitter.com/intent/tweet?url=${urlSharedCode}" target="_blank" data-network="twitter"
        class="share-link"><i class="fa-brands fa-twitter"></i> Twitter</a><br>
      <a href="https://api.whatsapp.com/send?text=${urlSharedCode}" target="_blank" data-network="whatsapp"
        class="share-link"><i class="fa-brands fa-whatsapp"></i> WhatsApp</a><br>
      <a href="https://www.linkedin.com/sharing/share-offsite/?url=${urlSharedCode}" target="_blank"
        data-network="linkedin" class="share-link"><i class="fa-brands fa-linkedin"></i> LinkedIn</a><br>
    </div>


  </div>
  <div class="actions-mdcm">
    <div class="developer-mdcm">
      Developed by <a href="https://github.com/DeveloperMDCM" target="_blank">DeveloperMDCM</a>
    </div>
    <span style="color: #fff" ;>v2.3.4.2</span>
  </div>
  `;
  const panelHTML = policy
    ? policy.createHTML(`
      ${menuHTML}
    `)
    : `
      ${menuHTML}
    `;

  panel.innerHTML = panelHTML;
  $ap(panel);
 

  function addIcon() {
    const topBar = $e('ytd-topbar-menu-button-renderer');
    if (!topBar || $id('icon-menu-settings')) return;
  
    const toggleButton = $cl('div');
    toggleButton.id = 'toggle-button';
  
    const icon = $cl('i');
    icon.id = 'icon-menu-settings';
    icon.classList.add('fa-solid', 'fa-gear');
  
    toggleButton.appendChild(icon);
    topBar.parentElement.insertBefore(toggleButton, topBar);
      // Toggle panel visibility
    let openMenu = false;
    toggleButton.addEventListener('click', () => {
      openMenu = !openMenu;
      // openMenu
      //   ? (toggleButton.style.backgroundColor = '#f00')
      //   : (toggleButton.style.backgroundColor = 'transparent');
      panel.style.display = panel.style.display === 'none' ? 'block' : 'none';
    });

    
    }

  
  addIcon();
  let openMenu = false;

  const close_menu_settings = $e('.close_menu_settings');
    close_menu_settings.addEventListener('click', () => {
      openMenu = !openMenu;
      panel.style.display = panel.style.display === 'none' ? 'block' : 'none';
    });

  // $ap(toggleButton);




  // Tab functionality
  const tabButtons = $m('.tab-mdcm');
  const tabContents = $m('.tab-content');

  tabButtons.forEach((button) => {
    button.addEventListener('click', () => {
      const tabName = button.getAttribute('data-tab');
      tabButtons.forEach((btn) => btn.classList.remove('active'));
      tabContents.forEach((content) => content.classList.remove('active'));
      button.classList.add('active');
      $id(tabName).classList.add('active');
    });
  });
  
  // Function to save settings
  function saveSettings() {
    const settings = {
      theme: $e('input[name="theme"]:checked').value,
      bgColorPicker: $id('bg-color-picker').value,
      progressbarColorPicker: $id('progressbar-color-picker').value,
      primaryColorPicker: $id('primary-color-picker').value,
      secondaryColorPicker: $id('secondary-color-picker').value,
      headerColorPicker: $id('header-color-picker').value,
      iconsColorPicker: $id('icons-color-picker').value,
      menuColorPicker: $id('menu-color-picker').value,
      lineColorPicker: $id('line-color-picker').value,
      timeColorPicker: $id('time-color-picker').value,
      dislikes: $id('dislikes-toggle').checked,
      themes: $id('themes-toggle').checked,
      translation: $id('translation-toggle').checked,
      avatars: $id('avatars-toggle').checked,
      reverseMode: $id('reverse-mode-toggle').checked,
      waveVisualizer: $id('wave-visualizer-toggle').checked,
      waveVisualizerSelected: $id('select-wave-visualizer-select').value,
      hideComments: $id('hide-comments-toggle').checked,
      hideSidebar: $id('hide-sidebar-toggle').checked,
      disableAutoplay: $id('autoplay-toggle').checked,
      // cinematicLighting: $id('cinematic-lighting-toggle').checked,
      disableSubtitles: $id('subtitles-toggle').checked,
      // fontSize: $id('font-size-slider').value,
      playerSize: $id('player-size-slider').value,
      selectVideoQuality: $id('select-video-qualitys-select').value,
      languagesComments: $id('select-languages-comments-select').value,
      // menuBgColor: $id('menu-bg-color-picker').value,
      // menuTextColor: $id('menu-text-color-picker').value,
      menu_developermdcm: {
        bg: selectedBgColor, 
        color: selectedTextColor, 
        accent: selectedBgAccentColor
      }
      // menuFontSize: $id('menu-font-size-slider').value,
    };

    GM_setValue('ytSettingsMDCM', JSON.stringify(settings));    
  }

  

  // Function to load settings
  function loadSettings() {
    const settings = JSON.parse(GM_getValue('ytSettingsMDCM', '{}'));
    
    if (settings.theme) {
      $e(`input[name="theme"][value="${settings.theme}"]`).checked = true;
    }
    settings.menu_developermdcm = settings.menu_developermdcm || {
      bg: "#252525",
      color: "#ffffff",
      accent: "#ff0000"
    };
    $id('bg-color-picker').value = settings.bgColorPicker || '#000000';
    $id('progressbar-color-picker').value = settings.progressbarColorPicker || '#ff0000';
    $id('primary-color-picker').value = settings.primaryColorPicker || '#ffffff';
    $id('secondary-color-picker').value = settings.secondaryColorPicker || '#ffffff';
    $id('header-color-picker').value = settings.headerColorPicker || '#000';
    $id('icons-color-picker').value = settings.iconsColorPicker || '#ffffff';
    $id('menu-color-picker').value = settings.menuColorPicker || '#000';
    $id('line-color-picker').value = settings.lineColorPicker || '#ff0000';
    $id('time-color-picker').value = settings.timeColorPicker || '#ffffff';
    $id('dislikes-toggle').checked = settings.dislikes || false;
    $id('themes-toggle').checked = settings.themes || false;
    $id('translation-toggle').checked = settings.translation || false;
    $id('avatars-toggle').checked = settings.avatars || false;
    $id('reverse-mode-toggle').checked = settings.reverseMode || false;
    $id('wave-visualizer-toggle').checked = settings.waveVisualizer || false;
    $id('select-wave-visualizer-select').value = settings.waveVisualizerSelected || 'dinamica';
    $id('hide-comments-toggle').checked = settings.hideComments || false;
    $id('hide-sidebar-toggle').checked = settings.hideSidebar || false;
    $id('autoplay-toggle').checked = settings.disableAutoplay || false;
    // $id('cinematic-lighting-toggle').checked = settings.cinematicLighting || false;
    $id('subtitles-toggle').checked = settings.disableSubtitles || false;
    // $id('font-size-slider').value = settings.fontSize || 16;
    $id('player-size-slider').value = settings.playerSize || 100;
    $id('select-video-qualitys-select').value = settings.selectVideoQuality || '720';
    $id('select-languages-comments-select').value = settings.languagesComments || 'en';
    // $id('menu-bg-color-picker').value = settings.menuBgColor || '#000000';
    // $id('menu-text-color-picker').value = settings.menuTextColor || '#ffffff';
    // $id('menu-font-size-slider').value = settings.menuFontSize || 14;
    // Asegurar existencia de menu_developermdcm
    
   
    selectedBgColor = settings.menu_developermdcm.bg;
    selectedTextColor = settings.menu_developermdcm.color;
    selectedBgAccentColor = settings.menu_developermdcm.accent;
    
 
    $m('#bg-color-options .color-box').forEach(el => {
      el.classList.toggle('selected', el.dataset.value === selectedBgColor);
    });

    $m('#text-color-options .color-box').forEach(el => {
      el.classList.toggle('selected', el.dataset.value === selectedTextColor);
    });

    $m('#bg-accent-color-options .color-box').forEach(el => {
      el.classList.toggle('selected', el.dataset.value === selectedBgAccentColor);
    });

    // Apply menu colors
    $sp('--yt-enhance-menu-bg', selectedBgColor);
    $sp('--yt-enhance-menu-text', selectedTextColor);
    $sp('--yt-enhance-menu-accent', selectedBgAccentColor);
    updateSliderValues();

    setTimeout(() => {
      applySettings();
      if(settings.dislikes) {
          videoDislike();
          shortDislike();
          showDislikes = true;
      }
    }, 500);
  }

  $m('.color-box').forEach(box => {
    box.addEventListener('click', () => {
      const type = box.dataset.type;
      const value = box.dataset.value;
  
      if (type === 'bg') {
        selectedBgColor = value; 
        $sp('--yt-enhance-menu-bg', value);
        $m('#bg-color-options .color-box').forEach(el => {
          el.classList.remove('selected');
        });
        box.classList.add('selected');
      } else if (type === 'color') {
        selectedTextColor = value;
        $sp('--yt-enhance-menu-text', value);
        $m('#text-color-options .color-box').forEach(el => {
          el.classList.remove('selected');
        });
        box.classList.add('selected');
      }
       else if (type === 'accent') {
        selectedBgAccentColor = value;
        $sp('--yt-enhance-menu-accent', value);
        $m('#bg-accent-color-options .color-box').forEach(el => {
          el.classList.remove('selected');
        });
        box.classList.add('selected');
      }
      saveSettings();
    });
  });
  
  
  function updateSliderValues() {
    $id('player-size-value').textContent = $id('player-size-slider').value;
    
  }

  $id('reset-player-size').addEventListener('click', () => {
    $id('player-size-slider').value = 100;
    updateSliderValues();
    applySettings();
  });

  // Function to apply settings
  function applySettings() {
    const formulariodescarga = $e('.formulariodescarga');
    const formulariodescargaaudio = $e('.formulariodescargaaudio');
      if (formulariodescarga != undefined) {
        formulariodescarga.classList.add('ocultarframe');
        formulariodescargaaudio.classList.add('ocultarframe');
      }
    const settings = {
      theme: $e('input[name="theme"]:checked').value,
      bgColorPicker: $id('bg-color-picker').value,
      progressbarColorPicker: $id('progressbar-color-picker').value,
      primaryColorPicker: $id('primary-color-picker').value,
      secondaryColorPicker: $id('secondary-color-picker').value,
      headerColorPicker: $id('header-color-picker').value,
      iconsColorPicker: $id('icons-color-picker').value,
      menuColorPicker: $id('menu-color-picker').value,
      lineColorPicker: $id('line-color-picker').value,
      timeColorPicker: $id('time-color-picker').value,
      dislikes: $id('dislikes-toggle').checked,
      themes: $id('themes-toggle').checked,
      translation: $id('translation-toggle').checked,
      avatars: $id('avatars-toggle').checked,
      reverseMode: $id('reverse-mode-toggle').checked,
      waveVisualizer: $id('wave-visualizer-toggle').checked,
      waveVisualizerSelected: $id('select-wave-visualizer-select').value,
      hideComments: $id('hide-comments-toggle').checked,
      hideSidebar: $id('hide-sidebar-toggle').checked,
      disableAutoplay: $id('autoplay-toggle').checked,
      // cinematicLighting: $id('cinematic-lighting-toggle').checked,
      disableSubtitles: $id('subtitles-toggle').checked,
      // fontSize: $id('font-size-slider').value,
      playerSize: $id('player-size-slider').value,
      selectVideoQuality: $id('select-video-qualitys-select').value,
      languagesComments: $id('select-languages-comments-select').value,
      // menuBgColor: $id('menu-bg-color-picker').value,
      // menuTextColor: $id('menu-text-color-picker').value,
      menu_developermdcm: {
        bg: selectedBgColor,
        color: selectedTextColor,
        accent: selectedBgAccentColor
      }
      // menuFontSize: $id('menu-font-size-slider').value,
    };
    $sp('--yt-enhance-menu-bg', settings.menu_developermdcm.bg);
    $sp('--yt-enhance-menu-text', settings.menu_developermdcm.color);
    $sp('--yt-enhance-menu-accent', settings.menu_developermdcm.accent);
   
    renderizarButtons();
   
  
    $id('shareBtn-mdcm').addEventListener('click', function(event) {
      event.stopPropagation(); 
      const dropdown = $id('shareDropdown');
      dropdown.style.display = dropdown.style.display === 'block' ? 'none' : 'block';
    });
    
    document.addEventListener('click', function(event) {
      event.stopPropagation();
      const dropdown = $id('shareDropdown');
      const shareButton = $id('shareBtn-mdcm');
      if (event.target !== shareButton) {
          dropdown.style.display = 'none';
      }
    });

    $id('importExportBtn').addEventListener('click', function() {
      $id('importExportArea').classList.toggle('active');
    });

    $id('closeImportExportBtn').addEventListener('click', function() {
        $id('importExportArea').classList.remove('active');
    });

   
  

    // Hide comments
    const commentsSection = $id('comments');
    if (commentsSection) {
      commentsSection.style.display = settings.hideComments ? 'none' : 'block';
    }
   
     // Active inactive Themes
     const themesMenuSection = $e('.themes-hidden');
     if (themesMenuSection) {
      themesMenuSection.style.display = settings.themes ? 'block' : 'none';
     }

    // Hide sidebar
    const sidebarSection = $e('#secondary > #secondary-inner');
 
    if (sidebarSection) {
      sidebarSection.classList.add('side-moi');
    const sidebarSection2 = $e('.side-moi');

    sidebarSection2.style.display = settings.hideSidebar ? 'none' : 'block';
    }

    // Disable autoplay
    const autoplayToggle = $e('.ytp-autonav-toggle-button');
    if (autoplayToggle) {
      const isCurrentlyOn =
        autoplayToggle.getAttribute('aria-checked') === 'true';
      if (settings.disableAutoplay && isCurrentlyOn) {
        autoplayToggle.click();
      } else if (!settings.disableAutoplay && !isCurrentlyOn) {
        autoplayToggle.click();
      }
    }
    // Disable subtitles
    const subtitleToggle = $e('.ytp-subtitles-button');
    if (subtitleToggle) {
      const isCurrentlyOn =
        subtitleToggle.getAttribute('aria-pressed') === 'true';
      if (settings.disableSubtitles && isCurrentlyOn) {
        subtitleToggle.click();
      } else if (!settings.disableSubtitles && !isCurrentlyOn) {
        subtitleToggle.click();
      }
    }
    // Disable cinematicLighting
    // const buttonSettingVideo = $e(".ytp-settings-button");
    // if(buttonSettingVideo && !settings.cinematicLighting) {
    //   buttonSettingVideo.click();
    //   setTimeout(() => {
    //     buttonSettingVideo.click();
    //   },50)
    // }
    

    // Adjust font size
    // $e('body').style.fontSize = `${settings.fontSize}px`;

    // Adjust player size
    const player = $e('video');
    if (player) {
      player.style.transform = `scale(${settings.playerSize / 100})`;
    }

    // selected video quality
    const video = $e('div#movie_player');
    let ytPlayerQuality = localStorage.getItem('yt-player-quality');
    $m('#select-video-qualitys-select, #select-languages-comments-select').forEach(el => {
      el.addEventListener('change', () => {
        applySettings();
      });
    });
    // $e('#select-languages-comments-select').addEventListener('change', () => {
    //   applySettings();
    // })
  
    if (video != undefined) {
      if (ytPlayerQuality) {
        let qualitySettings = JSON.parse(ytPlayerQuality);
        qualitySettings.data = JSON.stringify({ quality: settings.selectVideoQuality, previousQuality: 240 });
        localStorage.setItem('yt-player-quality', JSON.stringify(qualitySettings));
        
      } else {
        let defaultQualitySettings = {
          data: JSON.stringify({ quality: 720, previousQuality: 240 }),
          expiration: Date.now() + (365 * 24 * 60 * 60 * 1000), 
          creation: Date.now()
        };
        localStorage.setItem('yt-player-quality', JSON.stringify(defaultQualitySettings));
      }
      }
    

    // Apply menu appearance settings
    // $sp('--yt-enhance-menu-bg', settings.menuBgColor);
    // $sp('--yt-enhance-menu-text', settings.menuTextColor);
    // $sp('--yt-enhance-menu-font-size', `${settings.menuFontSize}px`);

    // Apply theme
    const selectedTheme = themes[settings.theme];
    const isThemeCustom = $e(`input[name="theme"][value="custom"]`).checked;
    const isThemeNormal = $e(`input[name="theme"][value="normal"]`).checked;
    const themeCustomOptions = $e('.theme-custom-options');
    const themeNormal = $e('.theme-selected-normal');
    if(isThemeCustom != undefined) {
      themeNormal.style.display = "flex"
      themeCustomOptions.style.display = "flex";
      $e('.themes-options').style.display = "none";
    }
    if(isThemeNormal) {
      $e(`input[name="theme"][value="custom"]`).checked = false;
    }




    function checkDarkMode() {
      
      if(settings.themes) {
        
        if (isDarkModeActive === 'dark' && !isThemeCustom) {
          // Apply theme
          $e('.themes-options').style.display = "block";
          themeNormal.style.display = "none";
          themeCustomOptions.style.display = "none";

          if(settings.theme === '0') {
            GM_addStyle(`
              .botones_div {
               background-color: transparent;
               border: none;
               color: #ccc !important;
               user-select: none;
             }
               `);
            return;
          } 
            
            $sp('--yt-spec-base-background', selectedTheme.gradient);
            $sp('--yt-spec-text-primary', selectedTheme.textColor);
            $sp('--yt-spec-text-secondary', selectedTheme.textColor);
            $sp('--yt-spec-menu-background', selectedTheme.gradient);
            $sp('--yt-spec-icon-inactive', selectedTheme.textColor);
            $sp('--yt-spec-brand-icon-inactive', selectedTheme.textColor);
            $sp('--yt-spec-brand-icon-active', selectedTheme.gradient);
            $sp('--yt-spec-static-brand-red', selectedTheme.gradient); // line current time
            $sp('--yt-spec-raised-background', selectedTheme.raised);
            $sp('--yt-spec-static-brand-red', selectedTheme.CurrentProgressVideo);
            $sp('--yt-spec-static-brand-white', selectedTheme.textColor);
            $sp('--ytd-searchbox-background', selectedTheme.gradient);
            $sp('--ytd-searchbox-text-color', selectedTheme.textColor);
            $sp('--ytcp-text-primary', settings.textColor);
            GM_addStyle(`
  
              .botones_div {
              background-color: transparent;
              border: none;
              color: #999999;
              user-select: none;
            }
              .ytp-menuitem[aria-checked=true] .ytp-menuitem-toggle-checkbox {
              background:  ${selectedTheme.gradient} !important;
              }
            #background.ytd-masthead { background: ${selectedTheme.gradient}  !important; }
            .ytp-swatch-background-color {
            background: ${
              selectedTheme.gradient
            } !important;
          }
          #shorts-container, #page-manager.ytd-app {
            background: ${selectedTheme.gradient.replace(/(#[0-9a-fA-F]{6})/g, `$1${36}`)};
          }
            ytd-engagement-panel-title-header-renderer[shorts-panel] #header.ytd-engagement-panel-title-header-renderer {
            background: ${selectedTheme.gradient}  !important;}
            .buttons-tranlate {
            background: ${selectedTheme.btnTranslate} !important;
            }
            .badge-shape-wiz--thumbnail-default {
            color: ${selectedTheme.videoDuration} !important;
            background: ${selectedTheme.gradient} !important;
            }
            #logo-icon {
            color:  ${selectedTheme.textLogo} !important;
          }
          .yt-spec-button-shape-next--overlay.yt-spec-button-shape-next--text {
            color:  ${selectedTheme.iconsColor} !important;
          }
          .ytd-topbar-menu-button-renderer #button.ytd-topbar-menu-button-renderer {
            color:  ${selectedTheme.iconsColor} !important;
          }
          .yt-spec-icon-badge-shape--style-overlay .yt-spec-icon-badge-shape__icon {
            color:  ${selectedTheme.iconsColor} !important;
          }
          .ytp-svg-fill {
            fill:  ${selectedTheme.iconsColor} !important;
          }
          #ytp-id-30,#ytp-id-17,#ytp-id-19,#ytp-id-20{
            fill:  ${selectedTheme.iconsColor} !important;
          }
  
  
            `);
          
        } else if(isDarkModeActive === 'dark' && isThemeCustom) {
          $sp('--yt-spec-base-background', settings.bgColorPicker);
          $sp('--yt-spec-text-primary', settings.primaryColorPicker);
          $sp('--yt-spec-text-secondary', settings.secondaryColorPicker);
          $sp('--yt-spec-menu-background', settings.menuColorPicker);
          $sp('--yt-spec-icon-inactive', settings.iconsColorPicker);
          $sp('--yt-spec-brand-icon-inactive', settings.primaryColorPicker);
          $sp('--yt-spec-brand-icon-active', settings.primaryColorPicker);
          $sp('--yt-spec-raised-background', settings.headerColorPicker);
          $sp('--yt-spec-static-brand-red', settings.lineColorPicker);
          $sp('--yt-spec-static-brand-white', settings.timeColorPicker);
          $sp('--ytd-searchbox-background', settings.primaryColorPicker);
          $sp('--ytd-searchbox-text-color', settings.secondaryColorPicker);
          $sp('--ytcp-text-primary', settings.primaryColorPicker);
          GM_addStyle(`
            .html5-video-player {
                color: ${settings.primaryColorPicker} !important;
              }
              .ytp-volume-slider-handle:before, .ytp-volume-slider-handle, .ytp-tooltip.ytp-preview:not(.ytp-text-detail) {
                background-color: ${settings.iconsColorPicker} !important;
              }
                .ytp-autonav-toggle-button[aria-checked=true] {
                  background-color: ${settings.iconsColorPicker} !important;
                }
                  .tp-yt-iron-icon {
                   fill: ${settings.iconsColorPicker} !important;
                  }
          
             .botones_div {
            background-color: transparent;
            border: none;
            color: ${settings.iconsColorPicker} !important;
            user-select: none;
          }
              #container.ytd-searchbox {
              color: red !important;
              }
            .ytp-menuitem[aria-checked=true] .ytp-menuitem-toggle-checkbox {
            background:  ${settings.primaryColorPicker} !important;
            }
            .yt-spec-icon-shape {
              display: flex;
              align-items: center;
              justify-content: center;
              width: 100%;
              height: 100%;
              color: ${settings.iconsColorPicker} !important;
          }
            .ytp-time-current, .ytp-time-separator, .ytp-time-duration {
              color: ${settings.iconsColorPicker} !important;
            }
            #background.ytd-masthead { background: ${settings.headerColorPicker}  !important; }
            .ytp-swatch-background-color {
            background: ${
              settings.progressbarColorPicker
            } !important;
          }
        #shorts-container, #page-manager.ytd-app {
            background: ${settings.bgColorPicker}36;
            }
            ytd-engagement-panel-title-header-renderer[shorts-panel] #header.ytd-engagement-panel-title-header-renderer {
            background: ${settings.bgColorPicker}  !important;}
  
            .badge-shape-wiz--thumbnail-default {
            color: ${settings.timeColorPicker} !important;
             background: ${settings.secondaryColor} !important;
            }
             #logo-icon {
             color:  ${settings.primaryColorPicker} !important;
          }
          .yt-spec-button-shape-next--overlay.yt-spec-button-shape-next--text {
            color:  ${settings.iconsColorPicker} !important;
          }
          .ytd-topbar-menu-button-renderer #button.ytd-topbar-menu-button-renderer {
            color:  ${settings.iconsColorPicker} !important;
          }
          .yt-spec-icon-badge-shape--style-overlay .yt-spec-icon-badge-shape__icon {
            color:  ${settings.iconsColorPicker} !important;
          }
          .ytp-svg-fill {
            fill:  ${settings.iconsColorPicker} !important;
          }
          #ytp-id-30,#ytp-id-17,#ytp-id-19,#ytp-id-20{
            fill:  ${settings.iconsColorPicker} !important;
          }
            `);
        } else {
          GM_addStyle(`
            .botones_div {
             background-color: transparent;
             border: none;
             color: #000 !important;
             user-select: none;
           }
             `);
        }
       
      } else {
        GM_addStyle(`
          .botones_div {
           background-color: transparent;
           border: none;
           color: #ccc !important;
           user-select: none;
         }
           `);
      }
        
    }

       
    GM_addStyle(`
      #columns.style-scope.ytd-watch-flexy {
        flex-direction: ${settings.reverseMode ? 'row-reverse' : 'row'} !important;
        padding-left: ${settings.reverseMode ? '20px' : '0'} !important;
        }
        #secondary.style-scope.ytd-watch-flexy {display: ${settings.hideSidebar ? 'none' : 'block'} !important;}


        #icon-menu-settings {
         color: ${settings.iconsColorPicker} !important;
        }
        .ytp-chrome-bottom {
          width: ${settings.hideSidebar ? '100%' : ''} !important;
          ${settings.hideSidebar ? 'left: 0;' : ''}
        }
          .ytp-progress-bar-container {
            left: ${settings.hideSidebar ? '4px' : ''} !important;
          }
      `);

    checkDarkMode();

    function checkForVideo() {
      if(!settings.waveVisualizer) {
        cleanup(false);
        return;
      }
      const video = $e('video');
      const miniPlayer = $e('.ytp-miniplayer-ui');
      if ((video && document.location.href.includes('watch')) || miniPlayer) {
          if (isFullscreen()) {
              hideCanvas();
              return;
          }
          if (video === currentVideo && isSetup) {
              if (controlPanel && video.paused === false) {
                  showCanvas();
              }
          } else {
              cleanup(true)
              setupAudioAnalyzer(video);
          }
      }
  }

  // checkForVideo();
   
    let currentUrl = window.location.href;
    let urlCheckInterval = setInterval(function () {
      if (window.location.href !== currentUrl) {
        currentUrl = window.location.href;
        checkUrlChange();
      }
    }, 1000);

    function checkUrlChange() {
      setTimeout(() => {
        applySettings();
      }, 1000);
      clearInterval(urlCheckInterval);
    }

    function downloadDescriptionVideo() {
      if($e('#button_copy_description')) return;
      const buttomHTML = `
      <div id="button_copy_description" style="display: flex; justify-content: end; align-items: center;margin-top: 10px;" >
        <button id="copy-description" class="botones_div" type="button" style="cursor: pointer;">
         <i style="font-size: 20px;" class="fa-solid fa-copy"></i>     
        </button>
      </div>
    `;
     const containerDescription = $e('#bottom-row.style-scope.ytd-watch-metadata');
     containerDescription.insertAdjacentHTML('beforebegin', buttomHTML);
     $id('copy-description').addEventListener('click', () => {
      const ldJson = [...document.querySelectorAll('script[type="application/ld+json"]')];
      for (let script of ldJson) {
        try {
          const data = JSON.parse(script.innerText);
          
          if (data['@type'] === 'VideoObject') {
            const description = 
              `📅 Date published: ${data.uploadDate || 'No available'}\n` +
              `Author: ${data.author || 'No available'}\n` +
              `🎬 Name video: ${data.name || 'No available'}\n` +
              `🖼️ Thumbnail: ${Array.isArray(data.thumbnailUrl) ? data.thumbnailUrl.join(', ') : data.thumbnailUrl || 'No available'}\n` +
              `📝 description: ${data.description || 'No available'}\n\n\n` +
              `🎭 Category: ${data.genre || 'No available'}\n`;
              
              navigator.clipboard.writeText(`${description}`)
          }
        } catch (e) {
          Notify('error', 'Error data JSON');
        } finally {
          Notify('success', 'Description video copied');
        }
      }
    });
    
    }

    downloadDescriptionVideo();



    async function traductor() {
      const texto = $m('#content-text');
      if ($e('.buttons-tranlate')) return;
    
      const languages = languagesTranslate;
      const idiomaDestino = $id('select-languages-comments-select').value;
    
      for (let i = 0; i < texto.length; i++) {
       
        const optionsHTML = Object.entries(languages)
          .map(([code, name]) => {
            const selected = code === idiomaDestino ? 'selected' : '';
            return `<option value="${code}" ${selected}>${name}</option>`;
          })
          .join('');
    
        const controlsHTML = `
          <div class="traductor-container" data-index="${i}">
          <button class="buttons-tranlate" id="btn${i}"> Translate <i class="fa-solid fa-language"></i></button>
          <select class="select-traductor" id="select${i}">
           ${optionsHTML}
          </select>
          </div>
        `;
     
        texto[i].insertAdjacentHTML('afterend', controlsHTML);
      }
      
      const botones = $m('.buttons-tranlate');
      const selects = $m('.select-traductor');
    
      botones.forEach((boton, i) => {
        boton.addEventListener('click', () => {
          const selectedLang = selects[i].value;
          const urlLista = `?client=dict-chrome-ex&sl=auto&tl=${selectedLang}&q=` + texto[i].textContent;
    
          fetch(apiGoogleTranslate + urlLista)
            .then((response) => response.json())
            .then((datos) => {
              texto[i].textContent = datos[0][0];
              botones[i].textContent = 'Translated';
            })
            .catch((err) => {
              console.error('Error en la traducción:', err);
            });
        });
      });
    }
    

 
    function limpiarHTML(selector) {
      $m(selector).forEach((button) => button.remove());
    }

    function checkScroll () {
      const avatars = $m('#author-thumbnail-button #img.style-scope.yt-img-shadow');
  
      if (avatars.length > 0 && settings.avatars) {
        limpiarHTML('.yt-image-avatar-download');
        agregarBotonesDescarga();
      }
    
      const divEl = $e('#content-text');
      const divEl2 = $e('ytd-item-section-renderer[static-comments-header] #contents');
    
      if (settings.translation) {
        if (divEl !== undefined || divEl2 !== undefined) {
          limpiarHTML('.buttons-tranlate');
          limpiarHTML('.select-traductor');
          traductor();
        }
      }
  
    }

    window.onscroll = () => {
      checkScroll();
    }


  const contentScrollable = $e('.anchored-panel.style-scope.ytd-shorts #contents.style-scope.ytd-item-section-renderer.style-scope.ytd-item-section-renderer');
  if (contentScrollable) {
    const observer = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          contentScrollable.addEventListener('scroll', () => {
            checkScroll();          
          });
        }
      });
    }, { threshold: 0.1 });
  
    observer.observe(contentScrollable);
  } 
    
    function agregarBotonesDescarga() {
      const avatars = $m('#author-thumbnail-button #img.style-scope.yt-img-shadow');
    
    
      avatars.forEach((img) => {
        
        if (img.parentElement.querySelector('.yt-image-avatar-download')) return;
       
        const button = $cl('button');
        button.innerHTML = '<i class="fa fa-download"></i>';
        button.classList.add('yt-image-avatar-download');
      
        button.onclick = async function () {
          try {
            const imageUrl = img.src.split('=')[0];
            const response = await fetch(imageUrl);
            const blob = await response.blob();
            const blobUrl = URL.createObjectURL(blob);
    
            const parentComment = img.closest('ytd-comment-thread-renderer, ytd-comment-renderer');
            const nameElement = parentComment?.querySelector('#author-text');
            let authorName = nameElement ? nameElement.textContent.trim() : 'avatar';
            authorName = authorName.replace(/[\/\\:*?"<>|]/g, '');
    
            const link = $cl('a');
            link.href = blobUrl;
            link.download = `${authorName}_avatar.jpg` || 'avatar.jpg';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            URL.revokeObjectURL(blobUrl);
          } catch (error) {
            console.error('Error al descargar la imagen:', error);
          }
        };
        
        img.parentElement.style.position = 'relative'; 
        img.parentElement.appendChild(button);
      });
    }

    const BUTTON_CLASS = 'custom-classic-btn';

   
    const redirectToClassic = () => {
      const videoId = window.location.pathname.split('/').pop();
      const classicUrl = `https://www.youtube.com/watch?v=${videoId}`;
     
      window.open(classicUrl, '_blank');
     
     $e('video.video-stream.html5-main-video').pause();
      
  };


   
  const createButton = () => {
    const button = $cl('button');
    button.classList.add(BUTTON_CLASS);
    button.innerHTML = '<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-screen-share"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M21 12v3a1 1 0 0 1 -1 1h-16a1 1 0 0 1 -1 -1v-10a1 1 0 0 1 1 -1h9" /><path d="M7 20l10 0" /><path d="M9 16l0 4" /><path d="M15 16l0 4" /><path d="M17 4h4v4" /><path d="M16 9l5 -5" /></svg>'; 
    button.title = 'Classic mode';
    button.onclick = redirectToClassic;
    return button;
  };

  const insertButtons = () => {
      const isShortsPage = document.location.pathname.startsWith('/shorts');

      if (isShortsPage) {
         $m('#actions').forEach(actionsContainer => {
              if (!actionsContainer.querySelector(`.${BUTTON_CLASS}`)) {
                  actionsContainer.prepend(createButton());
              }
          });
      } else {
          $m(`.${BUTTON_CLASS}`).forEach(button => button.remove());
      }
  };

  const observeDOM = () => {
      const observer = new MutationObserver(() => {
          insertButtons();
          addIcon();
          // obs.disconnect();
      });
      observer.observe(document.body, {
          childList: true,
          subtree: true
      });
  };

    insertButtons();
    observeDOM();


    const targetNode = $e('body');

    if (targetNode != undefined) {
      const element = $e('ytd-item-section-renderer[static-comments-header] #contents');
      if(element != undefined && settings.theme !== 'custom') {
        const observerElementDom = (elem) => {
          const observer = new IntersectionObserver(entries => {

              if(entries[0].isIntersecting) {

                element.style.background = `${selectedTheme.gradient ?? ''}`;
              } else {return}
          })

          return observer.observe($e(`${elem}`))

        }
        observerElementDom('ytd-item-section-renderer[static-comments-header] #contents')
      }
    }
    
    // Stats 
    
    function formatTime(seconds) {
      if (isNaN(seconds)) return '0h 0m 0s';
      seconds = Math.floor(seconds);
      const h = Math.floor(seconds / 3600);
      const m = Math.floor((seconds % 3600) / 60);
      const s = seconds % 60;
      return `${h}h ${m}m ${s}s`;
    }

  function updateUI() {
      $id('total-time').textContent = formatTime(usageTime);
      $id('video-time').textContent = formatTime(videoTime);
      $id('shorts-time').textContent = formatTime(shortsTime);

      const maxTime = 86400; // 24 hours
      $id('usage-bar').style.width =
          `${(usageTime / maxTime) * 100}%`;
      $id('video-bar').style.width =
          `${(videoTime / maxTime) * 100}%`;
      $id('shorts-bar').style.width =
          `${(shortsTime / maxTime) * 100}%`;
  }

  function detectContentType(videoElement) {
      if (/\/shorts\//.test(window.location.pathname)) return 'shorts';
    
      let parent = videoElement;
      while ((parent = parent.parentElement) !== null) { 
          if (parent.classList.contains('shorts-container') ||
              parent.classList.contains('reel-video') ||
              parent.tagName === 'YTD-REEL-VIDEO-RENDERER') {
              return 'shorts';
          }
      }

    
      if (videoElement.closest('ytd-watch-flexy') ||
          videoElement.closest('#primary-inner')) {
          return 'video';
      }
      if (videoElement.closest('ytd-thumbnail') ||
          videoElement.closest('ytd-rich-item-renderer')) {
          return 'video';
      }

      return null;
    }

    function findActiveVideo() {
        const videos = $m('video');
        for (const video of videos) {
            if (!video.paused && !video.ended && video.readyState > 2) {
                return video;
            }
        }
        return null;
    }
    

    function cleanup(fullCleanup = false) {
      if (fullCleanup && animationId) { 
          cancelAnimationFrame(animationId);
          animationId = null;
      }
      
      // Remueve los event listeners que afectan la UI
      if (currentVideo) {
          currentVideo.removeEventListener('play', showCanvas);
          currentVideo.removeEventListener('pause', hideCanvas);
          currentVideo.removeEventListener('ended', hideCanvas);
      }
      
      if (fullCleanup) {
          // Remueve  UI and disconnect from video
          if (canvas && canvas.parentNode) {
              canvas.parentNode.removeChild(canvas);
              canvas = null;
              ctx = null;
          }
          if (controlPanel && controlPanel.parentNode) {
              controlPanel.parentNode.removeChild(controlPanel);
              controlPanel = null;
          }
          if (source) {
              try {
                  source.disconnect();
              } catch (err) {
                  console.error("Error desconectando el source:", err);
              }
              source = null;
          }
          if (audioCtx) {
              try {
                  audioCtx.close();
              } catch (err) {
                  console.error("Error cerrando AudioContext:", err);
              }
              audioCtx = null;
          }
          if (currentVideo && currentVideo[PROCESSED_FLAG]) {
              delete currentVideo[PROCESSED_FLAG];
          }
          currentVideo = null;
          isSetup = false;
      } else {
          if (canvas) {
              canvas.style.opacity = '0';
          }
          if (controlPanel) {
              controlPanel.style.opacity = '0';
          }
      }
  }
  

    function createCanvasOverlay() {
        if (canvas) return; 
        const parent = document.body;
        canvas = document.createElement('canvas');
        canvas.id = 'wave-visualizer-canvas';
        canvas.width = window.innerWidth; 
        canvas.height = canvasHeight;
        canvas.style.position = 'fixed';
        canvas.style.left = '0';
        canvas.style.top = '0';
        canvas.style.width = '100%';
        canvas.style.pointerEvents = 'none';
        canvas.style.backgroundColor = 'transparent';
        canvas.style.zIndex = '10000';
        canvas.style.opacity = '0';
        canvas.style.transition = 'opacity 0.3s';

        parent.appendChild(canvas);
        ctx = canvas.getContext('2d');
    }
  
  
    function createControlPanelWave() {
      if (controlPanel) return; 

      controlPanel = $cl('div');
      controlPanel.id = 'wave-visualizer-control';
      const selectAppend = $id('select-wave-visualizer-select');      
      waveStyle = settings.waveVisualizerSelected;
      
      selectAppend.addEventListener('change', (e) => {
          waveStyle = e.target.value;
          selectAppend.value = e.target.value;
          saveSettings();
      });

  }


  function showCanvas() {    
    const canvas = $id('wave-visualizer-canvas');
    if (audioCtx && audioCtx.state === 'suspended') {
        audioCtx.resume();
    } 
    if (canvas) {
        canvas.style.opacity = '1';
        if (controlPanel) controlPanel.style.opacity = '1';
    }
}

    // setting Audio y Analyser
    function setupAudioAnalyzer(video) {
        if (video[PROCESSED_FLAG]) {
            Notify('error', "This video already has a MediaElementSource, skipping setup");
            return;
        }
        video[PROCESSED_FLAG] = true;
        cleanup(false);
        currentVideo = video;
        createCanvasOverlay();
        createControlPanelWave();
    
        
      
        if (!audioCtx) {
            const AudioContext = window.AudioContext || window.webkitAudioContext;
            audioCtx = new AudioContext();
        }
        
        analyser = audioCtx.createAnalyser();
        analyser.fftSize = 2048;
        analyser.smoothingTimeConstant = 0.85;
        bufferLength = analyser.fftSize;
        dataArray = new Uint8Array(bufferLength);
        smoothedData = new Array(bufferLength).fill(128);
        try {
            source = audioCtx.createMediaElementSource(video);
            source.connect(analyser);
            analyser.connect(audioCtx.destination);
        } catch (e) {
            Notify('error', "MediaElementSource or error:", e);
            cleanup(true);
            return setupAudioAnalyzer(video); // clean full
        }
        video.removeEventListener('play', showCanvas);
        video.removeEventListener('pause', hideCanvas);
        video.removeEventListener('ended', hideCanvas);

        video.addEventListener('play', showCanvas);
        video.addEventListener('pause', hideCanvas);
        video.addEventListener('ended', hideCanvas);
      
        const updateCanvasSize = () => {
            if (canvas) {
                canvas.width = window.innerWidth;
                canvas.height = canvasHeight;
            }
        };

        window.removeEventListener('resize', updateCanvasSize);
        window.addEventListener('resize', updateCanvasSize);
      
        draw();
        isSetup = true;
      }
      function draw() {
          animationId = requestAnimationFrame(draw);
          
          if (parseFloat(canvas.style.opacity) <= 0) return;

          analyser.getByteTimeDomainData(dataArray);
          for (let i = 0; i < bufferLength; i++) {
              smoothedData[i] += smoothingFactor * (dataArray[i] - smoothedData[i]);
          }
          ctx.clearRect(0, 0, canvas.width, canvas.height);
          
          let sliceWidth = canvas.width / bufferLength;

          switch(waveStyle) {
            
          case 'linea': {
              ctx.lineWidth = 2;
              ctx.strokeStyle = 'lime';
              ctx.beginPath();
              let x = 0;
              for (let i = 0; i < bufferLength; i++) {
                  let amplitude = Math.max(0, smoothedData[i] - 128) * scale;
                  if (i === 0) ctx.moveTo(x, amplitude);
                  else ctx.lineTo(x, amplitude);
                  x += sliceWidth;
              }
              ctx.stroke();
              break;
          }
          case 'barras': {
              let x = 0;
              for (let i = 0; i < bufferLength; i += 5) {
                  let amplitude = Math.max(0, smoothedData[i] - 128) * scale;
                  ctx.fillStyle = 'cyan';
                  ctx.fillRect(x, 0, sliceWidth * 4, amplitude);
                  x += sliceWidth * 5;
              }
              break;
          }
          case 'curva': {
              ctx.lineWidth = 2;
              ctx.strokeStyle = 'yellow';
              ctx.beginPath();
              ctx.moveTo(0, Math.max(0, smoothedData[0] - 128) * scale);
              for (let i = 0; i < bufferLength - 1; i++) {
                  let x0 = i * sliceWidth;
                  let x1 = (i + 1) * sliceWidth;
                  let y0 = Math.max(0, smoothedData[i] - 128) * scale;
                  let y1 = Math.max(0, smoothedData[i + 1] - 128) * scale;
                  let cp1x = x0 + sliceWidth / 3;
                  let cp1y = y0;
                  let cp2x = x1 - sliceWidth / 3;
                  let cp2y = y1;
                  ctx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x1, y1);
              }
              ctx.stroke();
              break;
          }
          case 'picos': {
              ctx.fillStyle = 'magenta';
              let x = 0;
              for (let i = 0; i < bufferLength; i += 5) {
                  let amplitude = Math.max(0, smoothedData[i] - 128) * scale;
                  ctx.beginPath();
                  ctx.arc(x, amplitude, 2, 0, Math.PI * 2);
                  ctx.fill();
                  x += sliceWidth * 5;
              }
              break;
          }
          case 'solida': {
              ctx.beginPath();
              let x = 0;
              ctx.moveTo(0, 0);
              for (let i = 0; i < bufferLength; i++) {
                  let amplitude = Math.max(0, smoothedData[i] - 128) * scale;
                  ctx.lineTo(x, amplitude);
                  x += sliceWidth;
              }
              ctx.lineTo(canvas.width, 0);
              ctx.closePath();
              ctx.fillStyle = 'rgba(0,255,0,0.3)';
              ctx.fill();
              break;
          }
          case 'dinamica': {
              let gradient = ctx.createLinearGradient(0, 0, canvas.width, 0);
              gradient.addColorStop(0, 'red');
              gradient.addColorStop(0.5, 'purple');
              gradient.addColorStop(1, 'blue');
              ctx.lineWidth = 3;
              ctx.strokeStyle = gradient;
              ctx.beginPath();
              let x = 0;
              for (let i = 0; i < bufferLength; i++) {
                  let amplitude = Math.max(0, smoothedData[i] - 128) * scale;
                  if (i === 0) ctx.moveTo(x, amplitude);
                  else ctx.lineTo(x, amplitude); 
                  x += sliceWidth;
              }
              ctx.stroke();
              break;
          }
          case 'montana': {
              ctx.beginPath();
              let x = 0;
              ctx.moveTo(0, 0);
              for (let i = 0; i < bufferLength; i++) {
                  let amp = (smoothedData[i] - 128) * scale * 0.8;
                  ctx.lineTo(x, amp);
                  x += sliceWidth;
              }
              ctx.lineTo(canvas.width, 0);
              ctx.closePath();
              ctx.fillStyle = 'rgba(128,128,255,0.4)';
              ctx.fill();
              break;
          }
            
          default:
              break;
          }
      }
   
     

  const observer = new MutationObserver(() => {
      const newVideo = findActiveVideo();
      if (newVideo !== activeVideo) {
          activeVideo = newVideo;
          if (activeVideo) {
              activeType = detectContentType(activeVideo);     
              
          }
      }
  });

        checkForVideo();
 
  setInterval(() => {
        const now = Date.now();
        // checkForVideo();
        const delta = (now - lastUpdate) / 1000;
        if (document.visibilityState === 'visible') {
            usageTime += delta;
        }
      
        if (activeVideo && !activeVideo.paused) {
            if (activeType === 'video') {
                videoTime += delta;
            } else if (activeType === 'shorts') {
                shortsTime += delta;
            }
        }
        lastUpdate = now;
        updateUI();
  }, UPDATE_INTERVAL);






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

  // end stats
  saveSettings();
  
  }

  let validoBotones = true;
  function renderizarButtons() {
    const addButton = $e('.style-scope .ytd-watch-metadata');
    const addButton2 = $e('#contents');

    if (addButton != undefined && validoBotones) {
        validoBotones = false;
        const isVisible = !!(
          addButton.offsetWidth ||
          addButton.offsetHeight ||
          addButton.getClientRects().length
        );
        if (isVisible) {
          addButton.insertAdjacentHTML("beforebegin", menuBotones);
        } else if (addButton2 != undefined) {
          addButton.insertAdjacentHTML("beforebegin", menuBotones);
        }
    }

    const formulariodescarga      = $e('.formulariodescarga');
    const formulariodescargaaudio = $e('.formulariodescargaaudio');
    const framedescarga         = $e('#descargando');
    const framedescargamp3      = $e('#descargandomp3');
    const btn1mp4               = $e('.btn1');
    const btn2mp3               = $e('.btn2');
    const btn3cancel            = $e('.btn3');
    const selectcalidades       = $e('.selectcalidades');
    const selectcalidadesaudio  = $e('.selectcalidadesaudio');
    

    [formulariodescarga, formulariodescargaaudio].forEach(form =>
      form?.addEventListener('click', e => e.preventDefault())
    );
    
    selectcalidades?.addEventListener('change', e => {
      framedescarga.src = `https://loader.to/api/button/?url=${window.location.href}&f=${e.target.value}&color=0af`;
      framedescarga.classList.remove('ocultarframe');
    });
    
    selectcalidadesaudio?.addEventListener('change', e => {
      framedescargamp3.src = `https://loader.to/api/button/?url=${window.location.href}&f=${e.target.value}&color=049c16`;
      framedescargamp3.classList.remove('ocultarframeaudio');
    });
    
    btn3cancel?.addEventListener('click', () => {
      formulariodescarga.style.display = 'none';
      formulariodescargaaudio.style.display = 'none';
    });
    
    btn1mp4?.addEventListener('click', () => {
      selectcalidades?.classList.remove('ocultarframe');
      framedescarga?.classList.add('ocultarframe');
      formulariodescarga?.classList.remove('ocultarframe');
      formulariodescarga.style.display = '';
      selectcalidadesaudio?.classList.add('ocultarframeaudio');
      formulariodescargaaudio?.classList.add('ocultarframe');
      formulariodescarga?.reset();
    });
    
    btn2mp3?.addEventListener('click', () => {
      formulariodescargaaudio?.classList.remove('ocultarframe');
      formulariodescarga?.classList.add('ocultarframe');
      framedescargamp3?.classList.remove('ocultarframeaudio');
      formulariodescargaaudio.style.display = '';
      selectcalidadesaudio?.classList.remove('ocultarframeaudio');
      framedescargamp3?.classList.add('ocultarframeaudio');
      formulariodescargaaudio?.reset();
    });
      // Invertir contenido

      // const background_image = $e('#background_image');
      // const color_bg = $e('#color_bg');
      // const alertShown = localStorage.getItem('alertShown');
      // const alertShownBg = localStorage.getItem('alertShownBg');
      // if (!alertShown) {
      //   color_bg.addEventListener('change', () => {
      //     alert('disable cinematic mode in the video');
      //     localStorage.setItem('alertShown', true);
      //   });
      // }
      // if (!alertShownBg) {
      //   background_image.addEventListener('input', () => {
      //     alert('disable cinematic mode in the video');
      //     localStorage.setItem('alertShownBg', true);
      //   });
      // }



      const btnImagen = $e('#imagen');
      const formularioButtons = $e('#eyes');
      
      function initClickEvent() {
        const bufferVideo = $e('.buffer_video');
        
        if (!bufferVideo) {
         
          return;
        }
      
        // Evita duplicar el evento
        if (!bufferVideo.dataset.listenerAdded) {
          bufferVideo.addEventListener("click", () => {
            const video = $e("video.video-stream.html5-main-video");
      
            if (!video) {
              console.log("No se encontró el video en la página.");
              return;
            }
      
            const event = new MouseEvent("contextmenu", {
              bubbles: true,
              cancelable: true
            });
      
            video.dispatchEvent(event);
    
            setTimeout(() => {
              const option = $e("body > div.ytp-popup.ytp-contextmenu > div > div > div:nth-child(7)");
              if (option) {
                option.click();
              } else {
                console.log("Opción no encontrada, intenta aumentar el tiempo de espera.");
              }
            }, 1000);
          });
      
          bufferVideo.dataset.listenerAdded = "true"; 
        }
      }
      
      setInterval(initClickEvent, 2000);
     
      

      // valido modo oscuro y venta de video
      // Repeat video button
      let countRepeat = 0; // count
      const repeat = $e('#repeatvideo'); // Repeat button
      const imarepeat = $e('.icon-tabler-repeat'); // img repeat
      const videoFull = $e(
        '#movie_player > div.html5-video-container > video'
      );
      if(repeat != undefined) {

        repeat.onclick = () => {
          if (
            $e('#cinematics > div') != undefined ||
            videoFull != undefined
          ) {
            countRepeat += 1;
            setInterval(() => {
              switch (countRepeat) {
                case 1:
                  document
                    .querySelector(
                      '#movie_player > div.html5-video-container > video'
                    )
                    .setAttribute('loop', 'true');
                  imarepeat.innerHTML = `  <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-repeat-off" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
                      <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
                      <path d="M4 12v-3c0 -1.336 .873 -2.468 2.08 -2.856m3.92 -.144h10m-3 -3l3 3l-3 3"></path>
                      <path d="M20 12v3a3 3 0 0 1 -.133 .886m-1.99 1.984a3 3 0 0 1 -.877 .13h-13m3 3l-3 -3l3 -3"></path>
                      <path d="M3 3l18 18"></path>
                   </svg> `; // img repeat
                  break;
                case 2:
                  countRepeat = 0;
                  document
                    .querySelector(
                      '#movie_player > div.html5-video-container > video'
                    )
                    .removeAttribute('loop');
                  imarepeat.innerHTML = ` <svg  xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-repeat" width="24"
                      height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none"
                      stroke-linecap="round" stroke-linejoin="round">
                      <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
                      <path d="M4 12v-3a3 3 0 0 1 3 -3h13m-3 -3l3 3l-3 3"></path>
                      <path d="M20 12v3a3 3 0 0 1 -3 3h-13m3 3l-3 -3l3 -3"></path>
                    </svg>`;
                  break;
              }
            }, 1000);
          }
          }
      }

      // Background transparent

      const cinematica = $e('#cinematics > div');
      if (cinematica != undefined) {
        cinematica.style =
          'position: fixed; inset: 0px; pointer-events: none; transform: scale(1.5, 2)';
      }
      const btnReset = $e('#reset_button'); // Reset button
      if (btnReset != undefined) {
        btnReset.addEventListener('click', function () {
          if (localStorage.getItem('colores') != null) {
            localStorage.removeItem('colores');
            $e('#ojosprotect').style.backgroundColor =
              'transparent';
            setTimeout(() => {
              location.reload();
            }, 400);
          }
        });
      }

      if (btnImagen != undefined) {
        btnImagen.onclick = () => {
          if (
            $e('#cinematics > div') != undefined ||
            videoFull != undefined
          ) {
            const parametrosURL = new URLSearchParams(window.location.search);
            let enlace = parametrosURL.get('v');
            
            const imageUrl = `https://i.ytimg.com/vi/${enlace}/maxresdefault.jpg`;
            
            fetch(imageUrl)
              .then((response) => {
                if (!response.ok) {
                  throw new Error(`HTTP error! Status: ${response.status}`);
                }
                return response.blob();
              })
              .then((blob) => {
                const imageSizeKB = blob.size / 1024;
               
                if (imageSizeKB >= 20) {
                  window.open(
                    `https://i.ytimg.com/vi/${enlace}/maxresdefault.jpg`,
                    'popUpWindow',
                    'height=500,width=400,left=100,top=100,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no, status=yes'
                  );
                  const imageUrlObject = URL.createObjectURL(blob);
                 
                  const enlaceDescarga = $cl('a');
                  enlaceDescarga.href = imageUrlObject;
                  const titleVideo = $e(
                    'h1.style-scope.ytd-watch-metadata'
                  ).innerText;
                  enlaceDescarga.download = `${titleVideo}_maxresdefault.jpg`;
                  enlaceDescarga.click();
                  
                  URL.revokeObjectURL(imageUrlObject);
                } else {
                  console.log(
                    'La imagen no excede los 20 KB. No se descargará.'
                  );
                }
              })
              .catch((error) => {
                alert('No found image');
                console.error('Error al obtener la imagen:', error);
              });
          }
        };
      }
      // for background image file photo higt quality
      // const fileInput = $id('background_image');
      // const backgroundDiv = $e('ytd-app');

      // const storedImage = localStorage.getItem('backgroundImage');
      // if (storedImage) {
      //   backgroundDiv.style = `background-size: contain; background-repeat: repeat; background-image: url(${storedImage}) !important`;
      // }

      // fileInput.addEventListener('change', (event) => {
      //   const file = event.target.files[0];
      //   if (file) {
      //     const reader = new FileReader();
      //     reader.onload = function (e) {
      //       const imageUrl = e.target.result;
      //       localStorage.setItem('backgroundImage', imageUrl);
      //       backgroundDiv.style.backgroundImage = `url(${imageUrl})`;
      //     };
      //     reader.readAsDataURL(file);
      //   }
      // });


      const externalLink = $e('.external_link');
      if (externalLink != undefined) {
        externalLink.onclick = () => {
          const parametrosURL = new URLSearchParams(window.location.search); // Url parametros
          let enlace;
          enlace = parametrosURL.get('v');
          window.open(
            `https://www.y2mate.com/es/convert-youtube/${enlace}`,
            'popUpWindow',
            'height=800,width=1000,left=50%,top=100,resizable=no,scrollbars=yes,toolbar=no,menubar=yes,location=no,directories=yes, status=no'
          );
        };
      }
      const viewExternalLink = $e('.view_external_link');
      if (viewExternalLink != undefined) {
        viewExternalLink.onclick = () => {
          $e('video').click();
          const parametrosURL = new URLSearchParams(window.location.search); // Url parametros
          let enlace;
          enlace = parametrosURL.get('v');
          window.open(
            `https://www.youtube.com/embed/${enlace}?rel=0&controls=2&color=white&iv_load_policy=3&showinfo=0&modestbranding=1&autoplay=1`
          );
        };
      }
      const viewPictureToPicture = $e(
        '.video_picture_to_picture'
      );
      if (viewPictureToPicture != undefined) {
        viewPictureToPicture.onclick = () => {
          const video = $e('video');
          if ('pictureInPictureEnabled' in document) {
            if (!document.pictureInPictureElement) {
        
              video
                .requestPictureInPicture()
                .then(() => {
                })
                .catch((error) => {
                  console.error(
                    'Error al activar el modo Picture-in-Picture:',
                    error
                  );
                });
            } else {
              // video picture
            }
          } else {
            alert('Picture-in-Picture not supported');
          }
        };

        // Filtro de pantalla
        if (formularioButtons != undefined) {
          formularioButtons.addEventListener('input', function () {
            if (
              $e('#cinematics > div') != undefined ||
              videoFull != undefined
            ) {
              $e('#ojosprotect').style.backgroundColor =
                formularioButtons.value;
            }
          });
        }
        clearInterval(renderizarButtons);
      }

      const checked_updates = $e('.checked_updates');

      if (checked_updates != undefined) {
        checked_updates.onclick = () => {
          window.open(
            `https://update.greasyfork.org/scripts/460680/Youtube%20Tools%20All%20in%20one%20local%20download%20mp3%20mp4%20HIGT%20QUALITY%20return%20dislikes%20and%20more.user.js`
          );
        };
      }

      const screenShotVideo = $e('.screenshot_video');
      if (screenShotVideo != undefined) {
        screenShotVideo.onclick = () => {
          const video = $e('video');
          const canvas = $cl('canvas');
          canvas.width = video.videoWidth;
          canvas.height = video.videoHeight;
          const context = canvas.getContext('2d');
          context.drawImage(video, 0, 0, canvas.width, canvas.height);
          const imagenURL = canvas.toDataURL('image/png');
          const enlaceDescarga = $cl('a');
          enlaceDescarga.href = imagenURL;
          const titleVideo = $e(
            'h1.style-scope.ytd-watch-metadata'
          ).innerText;
          enlaceDescarga.download = `${video.currentTime.toFixed(
            0
          )}s_${titleVideo}.png`;
          enlaceDescarga.click();
        };
      } else {
        const containerButtons = $e('.containerButtons');

        if (containerButtons != undefined) {
          containerButtons.innerHTML = '';
        }
      }
      clearInterval(renderizarButtons);
    }




  console.log('Script en ejecución by: DeveloperMDCM');
  const HEADER_STYLE = 'color: #F00; font-size: 24px; font-family: sans-serif;';
  const MESSAGE_STYLE = 'color: #00aaff; font-size: 16px; font-family: sans-serif;';
  const CODE_STYLE = 'font-size: 14px; font-family: monospace;';

  console.log(
    '%cYoutube Tools Extension NEW UI\n' +
      '%cRun %c(v2.3.4.2)\n' +
      'By: DeveloperMDCM.',
    HEADER_STYLE,
    CODE_STYLE,
    MESSAGE_STYLE
  );

  if (!localStorage.getItem('notification-developerMDCM')) {
    Notify('info', 'Youtube Tools by: DeveloperMDCM :)');
    localStorage.setItem('notification-developerMDCM', true);
  }






  // Add event listeners to all inputs
  const inputs = $m('input');
  inputs.forEach((input) => {
    input.addEventListener('change', applySettings);
    if (input.type === 'range') {
      input.addEventListener('change', () => {
        updateSliderValues();
        applySettings();
      });
    }
  });

  // Export configuration

//   Settings saved
//   const settings = GM_getValue('ytSettingsMDCM', '{}');
//   $id('config-data').value = settings;

  $id('export-config').addEventListener('click', () => {
    const settings = GM_getValue('ytSettingsMDCM', '{}');
    $id('config-data').value = settings;
    const configData = settings;
    try {
      JSON.parse(configData); // Validate JSON
      GM_setValue('ytSettingsMDCM', configData);
      setTimeout(() => {
        Notify('success', 'Configuration export successfully!');
      }, 1000);
    } catch (e) {
      Notify('error', 'Invalid configuration data. Please check and try again.');
    }
  });
  // Import configuration
  $id('import-config').addEventListener('click', () => {
    const configData = $id('config-data').value;
    try {
      JSON.parse(configData); // Validate JSON
      GM_setValue('ytSettingsMDCM', configData);
      setTimeout(() => {
        Notify('success', 'Configuration imported successfully!');
        window.location.reload();
      }, 1000);
      window.location.reload();
    } catch (e) {
      Notify('error', 'Invalid configuration data. Please check and try again.');
    }
  });
  panel.style.display = 'none';

  // var for wave
  let currentVideo = null;
  
  let waveStyle = 'dinamica';
  let audioCtx = null;
  let analyser = null;
  let source = null;
  let animationId = null;
  let canvas = null;
  let ctx = null;
  let controlPanel = null;
  let bufferLength = 0;
  let dataArray = null;
  let smoothedData = [];
  let isSetup = false;
  const smoothingFactor = 0.05;
  const canvasHeight = 240;
  const scale = canvasHeight / 90;
  
  const PROCESSED_FLAG = 'wave_visualizer_processed';
  // Load saved settings
  // Visible element DOM
  function checkElement(selector, callback) {
    const interval = setInterval(() => {
      if ($e(selector)) {
        clearInterval(interval);
        callback();
      }
    }, 100);
  }

  const checkActiveWave = $id('wave-visualizer-toggle');
  checkActiveWave.addEventListener('change', () => {
    const waveVisualizer = $e('#wave-visualizer-toggle');
    if (waveVisualizer.checked) {
      Notify('success', 'Wave visualizer enabled');
    } else {
      hideCanvas();
      Notify('success', 'Wave visualizer disabled realod page');
      setTimeout(() => {
        window.location.reload();
      }, 1000);
    }
  });

  checkElement('ytd-topbar-menu-button-renderer', loadSettings);
  // validate change url SPA youtube
  document.addEventListener('yt-navigate-finish', () => {
    if (!document.location.href.includes('watch')) {    
      hideCanvas();
    }
    });
})();