/*!
 * HotPocket by BTHLabs (https://hotpocket.app/)
 * Copyright 2025-present BTHLabs <contact@bthlabs.pl> (https://bthlabs.pl/)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
((HotPocket) => {
  class ViewAssociationView {
    constructor (app) {
      this.app = app;
      this.onWindowResizeTimeout = null;
    }
    clearOnWindowResizeTimeout () {
      if (this.onWindowResizeTimeout) {
        window.clearTimeout(this.onWindowResizeTimeout);
        this.onWindowResizeTimeout = null;
      }
    }
    onLoad = (event) => {
      document.addEventListener('HotPocket:ViewAssociationView:loadEmbed', this.onWindowResize);

      window.addEventListener('resize', (event) => {
        this.clearOnWindowResizeTimeout();
        this.onWindowResizeTimeout = window.setTimeout(
          this.onWindowResize, 300,
        );
      });
      this.onWindowResize();

      for (let shareButton of document.querySelectorAll('#ViewAssociationView .ui-share-button')) {
        if (navigator.share) {
          shareButton.addEventListener('click', this.onShareButtonClick);
        } else {
          shareButton.remove();
        }
      }

      const uiPlugin = this.app.plugin('UI');
      for (let controlButton of document.querySelectorAll('#ViewAssociationView .ui-controls > a.btn')) {
        if (uiPlugin.jsEnabled === true) {
          if (controlButton.classList.contains('ui-noscript-show')) {
            controlButton.remove();
          }
        } else {
          if (controlButton.classList.contains('ui-noscript-hide')) {
            controlButton.remove();
          }
        }
      }
    };
    onWindowResize = (event) => {
      const widthReference = document.querySelector('#ViewAssociationView .ui-width-reference');

      const youtubeIFrame = document.querySelector('#ViewAssociationView .ui-youtube-iframe');
      if (youtubeIFrame) {
        const width = widthReference.offsetWidth - 8;
        const height = Math.ceil(width / 1.6);
        youtubeIFrame.setAttribute('width', width);
        youtubeIFrame.setAttribute('height', height);
      }
    };
    onShareButtonClick = (event) => {
      event.preventDefault();

      navigator.share({
        title: document.title,
        url: event.target.href,
      });

      return false;
    };
  }

  HotPocket.addPlugin('UI.ViewAssociationView', (app) => {
    return new ViewAssociationView(app);
  });
})(window.HotPocket);
