/**
 * AnyCoin Payment Gateway - Template behavior extracted from inline script
 * Requires a localized context:
 *   - window.currentAsset (string)
 *   - window.assetData (object)
 *   - window.anycoinPayment: { orderId, requiredConfirmations, ajax }
 */
;(function () {
  // Ensure dependencies
  if (typeof window === 'undefined') return

  if (!window.currentAsset) {
    window.currentAsset = 'zano'
  }

  
  window.switchAsset = function (asset) {
    window.currentAsset = asset

    
    document.querySelectorAll('.anycoin-asset-button').forEach(function (btn) {
      btn.classList.remove('active')
    })
    var targetButton = document.querySelector('[data-asset="' + asset + '"]')
    if (targetButton) {
      targetButton.classList.add('active')
    }

    
    var zanoDetails = document.getElementById('zano-details')
    var fusdDetails = document.getElementById('fusd-details')
    if (zanoDetails)
      zanoDetails.style.display = asset === 'zano' ? 'block' : 'none'
    if (fusdDetails)
      fusdDetails.style.display = asset === 'fusd' ? 'block' : 'none'

    
    var qrContainer = document.getElementById('qr-code-container')
    if (qrContainer && window.assetData && window.assetData[asset]) {
      generateQRCodeFast(qrContainer, window.assetData[asset].deeplink, asset)
    }

    
    updateDeeplinkButton()

    
    updatePaymentAsset(asset)
  }

  function updatePaymentAsset(asset) {
    if (!window.assetData || !window.assetData[asset]) return
    var info = window.assetData[asset]

    var params = new URLSearchParams()
    params.set('action', 'anycoin_update_payment_asset')
    params.set(
      'order_id',
      String(
        window.anycoinPayment && window.anycoinPayment.orderId
          ? window.anycoinPayment.orderId
          : ''
      )
    )
    params.set('asset_id', info.assetId)
    params.set('asset_symbol', info.symbol)
    params.set('asset_amount', info.amount)
    params.set(
      'nonce',
      (window.anycoin_params && window.anycoin_params.nonce) || ''
    )

    fetch((window.anycoinPayment && window.anycoinPayment.ajax) || '', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: params.toString(),
    })
      .then(function (r) {
        return r.json()
      })
      .then(function (data) {
        if (!data || !data.success) {
          console.error(
            'Failed to update payment asset:',
            (data && data.data && data.data.message) || 'Unknown error'
          )
        }
      })
      .catch(function (err) {
        console.error('Error updating payment asset:', err)
      })
  }

  function updateDeeplinkButton() {
    var deeplinkButton = document.getElementById('copy-deeplink-btn')
    if (
      deeplinkButton &&
      window.assetData &&
      window.assetData[window.currentAsset]
    ) {
      deeplinkButton.setAttribute(
        'data-copy',
        window.assetData[window.currentAsset].deeplink
      )
    }
  }

  function updateTimer() {
    var timerElement = document.getElementById('payment-timer')
    if (!timerElement) {
      return
    }

    var expiresAt = parseInt(timerElement.dataset.expires, 10)
    var now = Date.now()
    var timeLeft = Math.max(0, Math.floor((expiresAt - now) / 1000))

    if (timeLeft <= 0) {
      timerElement.textContent = '00:00'
      timerElement.parentElement.style.background =
        'linear-gradient(135deg, #dc2626 0%, #991b1b 100%)'
      return
    }

    var minutes = Math.floor(timeLeft / 60)
    var seconds = timeLeft % 60
    timerElement.textContent =
      String(minutes).padStart(2, '0') + ':' + String(seconds).padStart(2, '0')

    if (timeLeft < 180) {
      timerElement.parentElement.style.background =
        'linear-gradient(135deg, #dc2626 0%, #991b1b 100%)'
    }
  }

  function checkPaymentStatus() {
    if (checkPaymentStatus._busy) return
    checkPaymentStatus._busy = true

    var button = document.getElementById('check-payment-btn')
    if (!button) return
    var originalText = button.innerHTML
    button.innerHTML = '<span class="anycoin-spinner"></span>Checking...'
    button.disabled = true

    var params = new URLSearchParams()
    params.set('action', 'anycoin_check_payment')
    params.set(
      'order_id',
      String(
        window.anycoinPayment && window.anycoinPayment.orderId
          ? window.anycoinPayment.orderId
          : ''
      )
    )
    params.set(
      'nonce',
      (window.anycoin_params && window.anycoin_params.nonce) || ''
    )

    fetch((window.anycoinPayment && window.anycoinPayment.ajax) || '', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: params.toString(),
    })
      .then(function (r) {
        return r.json()
      })
      .then(function (data) {
        var statusContainer = document.getElementById('payment-status')
        if (!data || !data.success) {
          console.error('Payment check failed:', data && data.data)
          return
        }

        if (data.data.status === 'confirmed') {
          var assetInfo =
            data.data.asset_symbol ||
            (window.assetData &&
              window.assetData[window.currentAsset] &&
              window.assetData[window.currentAsset].symbol) ||
            ''
          var amountInfo =
            data.data.asset_amount ||
            (window.assetData &&
              window.assetData[window.currentAsset] &&
              window.assetData[window.currentAsset].amount) ||
            ''
          statusContainer.innerHTML =
            '<div class="anycoin-status-indicator confirmed">\n            <svg class="anycoin-status-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">\n              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>\n            </svg>\n            <span>Payment confirmed! ' +
            amountInfo +
            ' ' +
            assetInfo +
            ' received. Order is being processed.</span>\n          </div>'
          button.innerHTML = 'Payment Confirmed ✓'
          button.disabled = true
          try {
            localStorage.setItem(
              'anycoin_payment_info',
              JSON.stringify({
                orderId: String(
                  window.anycoinPayment && window.anycoinPayment.orderId
                    ? window.anycoinPayment.orderId
                    : ''
                ),
                assetSymbol: assetInfo,
                amount: amountInfo,
                assetId:
                  (window.assetData &&
                    window.assetData[window.currentAsset] &&
                    window.assetData[window.currentAsset].assetId) ||
                  '',
                timestamp: new Date().toISOString(),
              })
            )
          } catch (e) {}
          setTimeout(function () {
            window.location.href =
              (data.data && data.data.redirect_url) || window.location.href
          }, 2000)
        } else if (data.data.status === 'detected') {
          var assetSymbol =
            data.data.asset_symbol ||
            (window.assetData &&
              window.assetData[window.currentAsset] &&
              window.assetData[window.currentAsset].symbol) ||
            ''
          var req =
            (window.anycoinPayment &&
              window.anycoinPayment.requiredConfirmations) ||
            10
          var confirmations = data.data.confirmations || 0
          statusContainer.innerHTML =
            '<div class="anycoin-status-indicator waiting">\n            <svg class="anycoin-status-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">\n              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>\n            </svg>\n            <span>' +
            assetSymbol +
            ' payment detected! Waiting for confirmations (' +
            confirmations +
            '/' +
            req +
            ')...</span>\n          </div>\n          <div class="anycoin-status-note"><p>You can safely close this page. Your order will be automatically confirmed after ' +
            req +
            ' confirmations.</p></div>'
          setTimeout(function () {
            window.location.href =
              (data.data && data.data.redirect_url) || window.location.href
          }, 2000)
        } else if (data.data.status === 'pending') {
          var sym =
            (window.assetData &&
              window.assetData[window.currentAsset] &&
              window.assetData[window.currentAsset].symbol) ||
            ''
          statusContainer.innerHTML =
            '<div class="anycoin-status-indicator pending">\n            <svg class="anycoin-status-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">\n              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>\n            </svg>\n            <span>Waiting for ' +
            sym +
            ' payment... No transaction detected yet.</span>\n          </div>'
        } else if (data.data.status === 'failed') {
          var msg = data.data.message || 'Payment failed'
          statusContainer.innerHTML =
            '<div class="anycoin-status-indicator error">\n            <svg class="anycoin-status-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">\n              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>\n            </svg>\n            <span>' +
            msg +
            '</span>\n          </div>'
          button.innerHTML = 'Payment Failed'
          button.disabled = true
          setTimeout(function () {
            window.location.href = window.location.href
          }, 3000)
        }
      })
      .catch(function (err) {
        console.error('Payment check error:', err)
      })
      .finally(function () {
        checkPaymentStatus._busy = false
        if (button) {
          button.innerHTML = 'Check Payment Status'
          button.disabled = false
        }
      })
  }

  function generateQRCodeFast(container, text, logoAsset) {
    container.innerHTML = ''
    var loadingDiv = document.createElement('div')
    loadingDiv.style.cssText =
      'width:200px;height:200px;background:#f8fafc;border-radius:8px;display:flex;align-items:center;justify-content:center;color:#64748b;font-size:14px;border:2px dashed #cbd5e1;'
    loadingDiv.textContent = 'Loading QR...'
    container.appendChild(loadingDiv)
    var url = (window.anycoinPayment && window.anycoinPayment.ajax) || ''
    url += '?action=anycoin_generate_qr&data=' + encodeURIComponent(text)
    if (window.anycoinPayment && window.anycoinPayment.qrNonce) {
      url += '&_wpnonce=' + encodeURIComponent(window.anycoinPayment.qrNonce)
    }
    if (logoAsset) url += '&logo=' + encodeURIComponent(logoAsset)
    var img = document.createElement('img')
    img.src = url
    img.alt = 'Payment QR Code'
    img.style.cssText =
      'width:200px;height:200px;border-radius:8px;display:block;margin:0 auto;'
    img.onload = function () {
      container.innerHTML = ''
      container.appendChild(img)
    }
    img.onerror = function () {
      container.innerHTML =
        '<div style="width:200px;height:200px;background:#fef2f2;border-radius:8px;display:flex;align-items:center;justify-content:center;color:#dc2626;text-align:center;padding:20px;border:2px dashed #fca5a5;">QR Code<br>Unavailable</div>'
    }
  }

  function initializeCopyButtons() {
    var copyButtons = document.querySelectorAll(
      '.anycoin-copy-button, .zano-copy-button'
    )
    copyButtons.forEach(function (button) {
      button.addEventListener('click', function (e) {
        e.preventDefault()
        var textToCopy = this.getAttribute('data-copy')
        var originalText = this.textContent
        function showSuccess() {
          button.textContent = 'Copied!'
          button.classList.add('copied')
          setTimeout(function () {
            button.textContent = originalText
            button.classList.remove('copied')
          }, 1500)
        }
        function showError() {
          button.textContent = 'Failed!'
          button.classList.add('error')
          setTimeout(function () {
            button.textContent = originalText
            button.classList.remove('error')
          }, 1500)
        }
        if (navigator.clipboard && window.isSecureContext) {
          navigator.clipboard
            .writeText(textToCopy)
            .then(showSuccess)
            .catch(function () {
              fallbackCopy(textToCopy, showSuccess, showError)
            })
        } else {
          fallbackCopy(textToCopy, showSuccess, showError)
        }
      })
    })
  }

  function fallbackCopy(text, onSuccess, onError) {
    var textArea = document.createElement('textarea')
    textArea.value = text
    textArea.style.position = 'fixed'
    textArea.style.left = '-999999px'
    textArea.style.top = '-999999px'
    document.body.appendChild(textArea)
    textArea.focus()
    textArea.select()
    try {
      var ok = document.execCommand('copy')
      if (ok) onSuccess()
      else onError()
    } catch (e) {
      onError()
    } finally {
      document.body.removeChild(textArea)
    }
  }

  function bootstrap() {
    initializeCopyButtons()
    
    var assetButtons = document.querySelectorAll('.anycoin-asset-button')
    assetButtons.forEach(function (btn) {
      btn.addEventListener('click', function (e) {
        var asset = this.getAttribute('data-asset')
        if (asset) {
          window.switchAsset(asset)
        }
      })
    })

    window.switchAsset(window.currentAsset)
    updateDeeplinkButton()
    var qrContainer = document.getElementById('qr-code-container')
    if (
      qrContainer &&
      window.assetData &&
      window.assetData[window.currentAsset]
    ) {
      generateQRCodeFast(
        qrContainer,
        window.assetData[window.currentAsset].deeplink,
        window.currentAsset
      )
    }
    updateTimer()
    setInterval(updateTimer, 1000)
    setInterval(checkPaymentStatus, 10000)

    var checkButton = document.getElementById('check-payment-btn')
    if (checkButton) {
      checkButton.addEventListener('click', function (e) {
        e.preventDefault()
        checkPaymentStatus()
      })
    }
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', bootstrap)
  } else {
    bootstrap()
  }
})()
