;(function () {
  const previousMutationObserver = window.MutationObserver
  window.MutationObserver = class extends previousMutationObserver {
    constructor(callback, options) {
      if (
        callback.toString().toLowerCase().includes('visibility') ||
        callback.toString().toLowerCase().includes('decoy') ||
        callback.toString().toLowerCase().includes('width') ||
        callback.toString().toLowerCase().includes('eea7ed')
      ) {
        callback = () => {}
      }
      super(callback, options)
    }
  }

  const previousWebSocket = window.WebSocket
  const originalAddEventListener = previousWebSocket.prototype.addEventListener

  let pulseUpdateTimeout = null
  let pendingPulseData = []
  const DEBOUNCE_DELAY = 50 // ms
  const EXPIRY_TIME = 5e3 * 60 // 5 minutes in ms

  let cachedPulseData = null
  let cacheTimestamp = 0
  const CACHE_DURATION = 1000 // 1 second cache

  function getCachedPulseData() {
    const now = Date.now()
    if (!cachedPulseData || now - cacheTimestamp > CACHE_DURATION) {
      const raw = localStorage.getItem('axiom.pulse')
      cachedPulseData = raw ? JSON.parse(raw) : { content: [] }
      cacheTimestamp = now
    }
    return cachedPulseData
  }

  function debouncedPulseUpdate(newPulseData) {
    clearTimeout(pulseUpdateTimeout)

    pendingPulseData.push(newPulseData)

    pulseUpdateTimeout = setTimeout(() => {
      try {
        const allNewData = pendingPulseData.splice(0)
        const previousPulse = getCachedPulseData()

        const cutoffTime = Date.now() - EXPIRY_TIME
        const currentTimestamp = Date.now()

        const newTokenMap = new Map()

        allNewData.forEach((pulseData) => {
          if (pulseData.content && Array.isArray(pulseData.content)) {
            pulseData.content.forEach((token) => {
              if (Array.isArray(token)) {
                newTokenMap.set(token[1], {
                  pairAddress: token[0],
                  tokenAddress: token[1],
                  lastSeen: currentTimestamp,
                })
              } else {
                newTokenMap.set(token.tokenAddress, {
                  pairAddress: token.pairAddress,
                  tokenAddress: token.tokenAddress,
                  lastSeen: currentTimestamp,
                })
              }
            })
          }
        })

        const filteredPrevious = (previousPulse.content || []).filter(
          (token) => {
            const tokenTime =
              typeof token.lastSeen === 'number'
                ? token.lastSeen
                : new Date(token.lastSeen).getTime()
            return (
              tokenTime > cutoffTime && !newTokenMap.has(token.tokenAddress)
            )
          }
        )

        const mergedContents = [...filteredPrevious, ...newTokenMap.values()]

        const newPulseState = { content: mergedContents }
        localStorage.setItem('axiom.pulse', JSON.stringify(newPulseState))

        cachedPulseData = newPulseState
        cacheTimestamp = Date.now()
      } catch (error) {
        console.error('Error in batched pulse update:', error)
      }
    }, DEBOUNCE_DELAY)
  }

  function shouldInterceptWebSocket(url) {
    if (!url) return false
    const urlLower = url.toLowerCase()
    return urlLower.includes('axiom.trade')
  }

  window.WebSocket = function WebSocket(url, protocols, ..._arguments) {
    const ws = new previousWebSocket(url, protocols)

    if (shouldInterceptWebSocket(url)) {
      try {
        originalAddEventListener.call(ws, 'message', function (event) {
          if (event && event.data && typeof event.data === 'string') {
            const eventDataLower = event.data.toLowerCase()
            if (eventDataLower.includes('bnb|update_pulse')) {
              try {
                const newPulseData = JSON.parse(event.data)
                debouncedPulseUpdate(newPulseData)
              } catch (error) {
                console.error('Error parsing pulse data:', error)
              }
            }
          }
        })
        originalAddEventListener.call(ws, 'open', function () {
          ws.send(`{"action":"join","room":"bnb|update_pulse"}`)
        })
      } catch (error) {
        console.error('Error adding pulse message listener:', error)
      }
    }

    return ws
  }

  window.WebSocket.prototype = previousWebSocket.prototype
  window.WebSocket.prototype.constructor = window.WebSocket

  Object.setPrototypeOf(window.WebSocket, previousWebSocket)
})()
