import { Controller } from "@hotwired/stimulus"

// Connects to data-controller="settings--nostr-pubkey"
export default class extends Controller {
  static targets = [ "noExtension", "setPubkey", "pubkeyBech32Input" ]
  static values  = { userAddress: String, pubkeyHex: String, sharedSecret: String }

  connect () {
    if (window.nostr) {
      if (this.hasSetPubkeyTarget) {
        this.setPubkeyTarget.disabled = false
      }
    } else {
      this.noExtensionTarget.classList.remove("hidden")
    }
  }

  async setPubkey () {
    this.setPubkeyTarget.disabled = true

    try {
      const signedEvent = await window.nostr.signEvent({
        created_at: Math.floor(Date.now() / 1000),
        kind: 1,
        tags: [],
        content: `Connect my public key to ${this.userAddressValue} (confirmation ${this.sharedSecretValue})`
      })

      const res = await fetch("/settings/set_nostr_pubkey", {
        method: "POST", credentials: "include", headers: {
          "Accept": "application/json", 'Content-Type': 'application/json',
          "X-CSRF-Token": this.csrfToken
        }, body: JSON.stringify({ signed_event: signedEvent })
      });

      window.location.reload()
    } catch (error) {
      console.warn('Unable to verify pubkey:', error.message)
      this.setPubkeyTarget.disabled = false
    }
  }

  get csrfToken () {
    const element = document.head.querySelector('meta[name="csrf-token"]')
    return element.getAttribute("content")
  }
}
