import { Element } from '../core/element.js'

class CopyLink extends Element {
  init() {
    this._copiedLabel = this.button.getAttribute('data-label-copied');
    this._isCopied = false;
    this._heading = this.button.parentElement;
    this.listenClick(this.button);
  }

  get button () {
    return this.element;
  }

  get anchor () {
    return this._heading && this._heading.id ? `#${this._heading.id}` : '';
  }

  get url () {
    return window.location.origin + window.location.pathname + window.location.search;
  }

  get anchoredUrl () {
    return this.url + this.anchor;
  }

  get isCopied () {
    return this._isCopied;
  }

  set isCopied (value) {
    this._isCopied = value;
    if (value && this._tooltip) {
      this._tooltip.innerText = this._copiedLabel;
      this.button.setAttribute('aria-label', this._copiedLabel);
    }
  }

  createTooltip() {
    const tooltip = document.createElement("span");
    tooltip.id = `${this.button.id}-tooltip`;
    tooltip.className = 'fr-tooltip fr-placement';
    tooltip.setAttribute('aria-hidden', 'true');
    this.button.setAttribute('aria-describedby', tooltip.id);
    this._heading.insertAdjacentElement('beforeend', tooltip);
    return tooltip;
  }

  removeTooltip() {
    if (this._tooltip) {
      this._tooltip.remove();
      this._tooltip = null;
    }
  }

  handleClick () {
    navigator.clipboard.writeText(this.anchoredUrl).then(() => {
      if (this._tooltip) return;
      this._tooltip = this.createTooltip();
      this.isCopied = true;

      setTimeout(() => {
        if (typeof window.dsfr === 'function') {
          window.dsfr(this._tooltip).tooltip.show();
          window.dsfr(this._tooltip).tooltip.isEnabled = false;
          setTimeout(this._handleTimeout.bind(this), 1500);
        }
      }, 10);
    });
  }

  _handleTimeout () {
    window.dsfr(this._tooltip).tooltip.hide();
    this.isCopied = false;
    this.removeTooltip();
  }
}

export default CopyLink;
