import { bareNostrUser } from '@nostr/gadgets/metadata'

import { fetchNostrUser, inputToPubkey } from './nostr.js'
import { debounce } from './utils.js'
import { npubEncode } from '@nostr/tools/nip19'

export default class NostrName extends HTMLElement {
  static observedAttributes = ['pubkey']

  constructor() {
    super()
    this.set()
  }

  connectedCallback() {
    this.set()
  }

  attributeChangedCallback() {
    this.set()
  }

  set: () => void = debounce(async () => {
    let input = this.getAttribute('pubkey')
    if (input) {
      this.textContent = bareNostrUser(input).shortName
      let [pubkey, hints] = await inputToPubkey(input)
      if (pubkey) {
        this.title = npubEncode(pubkey)
        let nu = await fetchNostrUser(pubkey, hints || [])
        this.textContent = nu.shortName
      }
    }
  }, 200)
}

window.customElements.define('nostr-name', NostrName)
