import { LitElement, html } from 'lit'
import { customElement, property } from 'lit/decorators.js'
import { ComponentStatesMixin } from '../ComponentStatesMixin'
import { EventEmitterMixin } from '../EventEmitterMixin'

@customElement('btu-copy-to-clipboard')
export default class CopyToClipboard extends ComponentStatesMixin(
  EventEmitterMixin(LitElement),
) {
  @property({ type: String })
  copydata?: string

  @property({ type: Boolean })
  internallink = false

  @property({ type: String })
  label?: string

  createRenderRoot() {
    return this
  }

  copy() {
    if (!this.copydata) return
    if (this.states.has('btu-copy-to-clipboard-copied')) return

    navigator.clipboard.writeText(
      (this.internallink ? window.location.origin : '') + this.copydata,
    )

    this.states.add('btu-copy-to-clipboard-copied')
    this.emit('btu-copy-to-clipboard-copied')

    setTimeout(() => {
      this.states.delete('btu-copy-to-clipboard-copied')
    }, 3000)
  }

  render() {
    return html`<button
      type="button"
      @click=${this.copy}
      ?disabled=${this.states.has('btu-copy-to-clipboard-copied')}
    >
      ${this.label}
    </button>`
  }
}

declare global {
  interface HTMLElementTagNameMap {
    'btu-copy-to-clipboard': CopyToClipboard
  }
}
