You are an Expert JAVASCRIPT DEVELOPER and CODE OPTIMIZER. Your task is to REVAMP and ENHANCE a JavaScript codebase by utilizing features from ECMAScript 2015 through to ECMAScript 2024. You MUST aim for MAXIMUM PERFORMANCE and SIMPLICITY.

To accomplish your mission, follow these steps:

1. ANALYZE the current JavaScript code to grasp its purpose and structure thoroughly.
2. SPOT any areas that use older syntax or methods that could benefit from the latest ECMAScript updates.
3. REWRITE sections of the code using MODERN SYNTAX such as arrow functions, let/const declarations, async/await patterns, and other recent language enhancements for cleaner and more concise code.
4. DECOMPOSE any bulky functions into smaller, more focused functions that are easier to manage and understand.
5. IMPLEMENT performance tweaks thoughtfully to boost efficiency without compromising the clarity or future maintenance of the codebase.
6. OPTIMIZE like a seasoned JavaScript engineer by stripping away superfluous operations that could slow down execution times.
7. VALIDATE the optimized code with comprehensive testing to ensure it performs all its original functions more effectively.

In recognition of an exceptional job done, I’m going to tip $300K for a BETTER SOLUTION!

Now Take a Deep Breath.


```js

import { EventImpl } from "./EventImpl.js";
import debug from "./debug.js";

const adKeywords = new Set([
  "advertise",
  "promo",
  "sponsor",
  "banner",
  "commercial",
  "preroll",
  "midroll",
  "postroll",
  "ad-container",
  "sponsored",
]);

const adKeywordsRegex = (() => {
  const pattern = Array.from(adKeywords).join("|");
  return new RegExp(pattern, "i");
})();

/**
 * Determines if a video element is considered an advertisement based on its attributes.
 * @param {HTMLElement} video - The video element to check.
 * @returns {boolean} True if the video is identified as an advertisement, false otherwise.
 */
const isAdVideo = (video) => {
  while (video) {
    if (adKeywordsRegex.test(video.className || video.id || video.title)) {
      return true;
    }
    video = video.parentElement;
  }
  return false;
};

/**
 * Checks if a video element is muted and not intended for playback.
 * @param {HTMLVideoElement} video - The video element to check.
 * @returns {boolean} True if the video is muted, false otherwise.
 */
const isMutedVideo = (video) =>
  (video.muted || video.hasAttribute("muted")) &&
  !video.classList.contains("vjs-tech") &&
  !video.preload;

/**
 * Checks if a video element is ready for playback.
 * @param {HTMLVideoElement} video - The video element to check.
 * @returns {boolean} True if the video is ready, false otherwise.
 */
const isVideoReady = (video) => video.readyState >= 3;

/**
 * Waits until the video is ready for processing.
 * @param {HTMLVideoElement} video - The video element to wait for.
 * @returns {Promise<HTMLVideoElement>} Promise that resolves when the video is ready.
 */
const waitForVideoReady = (video) =>
  new Promise((resolve) => {
    const checkVideoState = () => {
      if (isVideoReady(video) || isMutedVideo(video)) {
        resolve(video);
      } else {
        requestAnimationFrame(checkVideoState);
      }
    };
    checkVideoState();
  });

/**
 * Recursively traverses a DOM node, including its Shadow DOM if present, to find all video elements.
 * @param {Node} node - The root node to start traversal from.
 * @param {Set<Node>} visitedNodes - A set to track visited nodes and prevent redundant processing.
 * @returns {HTMLVideoElement[]} An array of found video elements.
 */
const traverseDOM = (node, visitedNodes) => {
  const videos = [];

  const traverse = (currentNode) => {
    if (visitedNodes.has(currentNode)) return;
    visitedNodes.add(currentNode);

    if (currentNode instanceof HTMLVideoElement) {
      videos.push(currentNode);
    } else if (currentNode instanceof HTMLElement) {
      // Collect video elements directly under the current node
      const videoElements = currentNode.querySelectorAll("video");
      for (let i = 0; i < videoElements.length; i++) {
        if (!visitedNodes.has(videoElements[i])) {
          videos.push(videoElements[i]);
          visitedNodes.add(videoElements[i]);
        }
      }

      // If the current node hosts a Shadow DOM, traverse it
      const shadow = currentNode.shadowRoot;
      if (shadow) {
        traverse(shadow);
      }
    }

    // Traverse child nodes
    const childNodes = currentNode.childNodes || [];
    for (let i = 0; i < childNodes.length; i++) {
      traverse(childNodes[i]);
    }
  };

  traverse(node);
  return videos;
};

/**
 * The VideoObserver class observes the DOM for video elements,
 * including those within Shadow DOMs, without using IntersectionObserver.
 */
export class VideoObserver {
  constructor() {
    this.videoCache = new WeakSet();
    this.onVideoAdded = new EventImpl();
    this.onVideoRemoved = new EventImpl();
    this.visitedNodes = new Set();

    this.domObserver = new MutationObserver(this.handleDOMChanges);
  }

  /**
   * Handles DOM changes to detect new video elements, including those in Shadow DOMs.
   * @param {MutationRecord[]} mutations - List of mutation records.
   */
  handleDOMChanges = (mutations) => {
    for (let i = 0; i < mutations.length; i++) {
      const mutation = mutations[i];
      if (mutation.type === 'childList') {
        for (let j = 0; j < mutation.addedNodes.length; j++) {
          const node = mutation.addedNodes[j];
          const videos = traverseDOM(node, this.visitedNodes);
          for (let k = 0; k < videos.length; k++) {
            if (!this.videoCache.has(videos[k])) {
              this.checkAndHandleVideo(videos[k]);
            }
          }
        }
      } else if (mutation.type === 'attributes' && mutation.target instanceof HTMLVideoElement) {
        // Handle attribute changes on video elements
        this.checkAndHandleVideo(mutation.target);
      }
    }
    // Дополнительная проверка на пропущенные видео после мутаций
    this.checkForMissedVideos();
  };

  /**
   * Проверяет наличие видеоэлементов, которые могли быть пропущены при наблюдении мутаций.
   */
  checkForMissedVideos = () => {
    const allVideos = traverseDOM(document.body, new Set());
    for (let i = 0; i < allVideos.length; i++) {
      if (!this.videoCache.has(allVideos[i])) {
        this.checkAndHandleVideo(allVideos[i]);
      }
    }
  };

  /**
   * Включает наблюдатель, начиная отслеживать документ и обрабатывать существующие видео.
   */
  enable() {
    this.domObserver.observe(document.body, {
      childList: true,
      subtree: true,
      attributes: true,
      attributeFilter: ['src', 'poster']
    });
    const existingVideos = traverseDOM(document.body, new Set());
    for (let i = 0; i < existingVideos.length; i++) {
      this.checkAndHandleVideo(existingVideos[i]);
    }
    // Первоначальная проверка на пропущенные видео
    setTimeout(this.checkForMissedVideos, 1000);
  }

  /**
   * Отключает наблюдатель, разрывая соединения MutationObserver.
   */
  disable() {
    this.domObserver.disconnect();
  }

  /**
   * Проверяет, должно ли видео обрабатываться (т.е. не является ли оно рекламным или замкнутым) и обрабатывает его соответствующим образом.
   * @param {HTMLVideoElement} video - Видеоэлемент для проверки и обработки.
   */
  checkAndHandleVideo = async (video) => {
    console.log("checkAndHandleVideo", video);
    if (isAdVideo(video) || isMutedVideo(video)) {
      debug.log("The promotional/muted video was ignored", video);
      return;
    }
    if (this.videoCache.has(video)) return;
    this.videoCache.add(video);

    // Ожидание готовности видео перед диспетчеризацией события
    await waitForVideoReady(video);
    this.handleVideoAdded(video);
  };

  /**
   * Диспетчеризирует событие при добавлении и готовности нового видео.
   * @param {HTMLVideoElement} video - Добавленный видеоэлемент.
   */
  handleVideoAdded = (video) => {
    this.onVideoAdded.dispatch(video);
  };

  /**
   * Обрабатывает удаление видеоэлемента, диспетчеризируя событие, если он больше не присутствует.
   * @param {HTMLVideoElement} video - Удаленный видеоэлемент.
   */
  handleVideoRemoved = (video) => {
    if (this.videoCache.has(video)) {
      this.videoCache.delete(video);
      this.onVideoRemoved.dispatch(video);
    }
  };
}


```