/**
 * NIP-07 browser extension helpers + relay profile fetch
 */

export function hasNostrExtension() {
  return typeof window !== 'undefined' && !!window.nostr
}

export async function getPublicKey() {
  return window.nostr.getPublicKey()
}

export async function signEvent(event) {
  return window.nostr.signEvent(event)
}

const RELAYS = [
  'wss://relay.damus.io',
  'wss://relay.nostr.band',
  'wss://nos.lol',
]

/**
 * Fetch a Nostr kind:0 profile from relays via WebSocket.
 * Races multiple relays, returns first result.
 * Returns { name, picture } or null on timeout/error.
 */
export function fetchNostrProfile(pubkeyHex, timeoutMs = 5000) {
  return new Promise((resolve) => {
    let resolved = false
    const connections = []

    const done = (result) => {
      if (resolved) return
      resolved = true
      connections.forEach(ws => { try { ws.close() } catch {} })
      resolve(result)
    }

    setTimeout(() => done(null), timeoutMs)

    for (const relay of RELAYS) {
      try {
        const ws = new WebSocket(relay)
        connections.push(ws)

        ws.onopen = () => {
          const subId = 'p_' + Math.random().toString(36).slice(2, 8)
          ws.send(JSON.stringify(['REQ', subId, { kinds: [0], authors: [pubkeyHex], limit: 1 }]))
        }

        ws.onmessage = (msg) => {
          try {
            const data = JSON.parse(msg.data)
            if (data[0] === 'EVENT' && data[2]?.kind === 0) {
              const profile = JSON.parse(data[2].content)
              done({
                name: profile.name || profile.display_name || null,
                picture: profile.picture || null,
              })
            }
          } catch {}
        }

        ws.onerror = () => {}
      } catch {}
    }
  })
}
