/*!
 * 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 HotPocketUIPasteboardLinkPlugin {
    constructor (app) {
    }
    onLoad (event) {
      let canCopy = false;
      if (navigator.clipboard && navigator.clipboard.writeText) {
        canCopy = true;
      }

      for (let pasteboardLink of document.querySelectorAll('.ui-pasteboard-link')) {
        if (canCopy === false) {
          pasteboardLink.classList.add('d-none');
        } else {
          pasteboardLink.addEventListener('click', this.onClick);
        }
      }
    }
    onClick = (event) => {
      event.stopPropagation();
      event.preventDefault();

      const icon = event.target.querySelector('i.bi');
      icon.classList.replace('bi-clipboard-fill', 'bi-clipboard');

      navigator.clipboard.writeText(event.target.href).
        then(() => {
          icon.classList.replace('bi-clipboard', 'bi-clipboard-fill');
        }).
        catch((reason) => {
          console.error('HotPocket.UI.PasteboardLink.onClick()', reason);
          window.alert('Could not copy the link :(');
        });

      return false;
    };
  }

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