/**
 * AnyCoin Payment Gateway - Frontend script for payment page
 */

jQuery(document).ready(function ($) {
  // Initialize buttons
  var copyButtons = $('.anycoin-copy-button')
  var checkPaymentButton = $('.anycoin-check-payment-button, .check-payment')
  var statusIndicator = $('.anycoin-status-indicator')
  var confirmationProgress = $('.confirmation-progress')
  var isCheckingPayment = false
  var paymentCheckInterval = null


  copyButtons.on('click', function (e) {
    e.preventDefault()
    var $button = $(this)
    var textToCopy = $button.data('copy')
    var originalText = $button.text()

    
    console.log('Copy button clicked:', {
      text: textToCopy,
      button: $button[0],
      hasClipboardAPI: !!navigator.clipboard,
      isSecureContext: window.isSecureContext,
    })

    
    function showSuccess() {
      $button.text('Copied!').addClass('copied')
      setTimeout(function () {
        $button.text(originalText).removeClass('copied')
      }, 1500)
    }

    
    function showError() {
      $button.text('Failed!').addClass('error')
      setTimeout(function () {
        $button.text(originalText).removeClass('error')
      }, 1500)
    }

    
    if (navigator.clipboard && window.isSecureContext) {
      navigator.clipboard
        .writeText(textToCopy)
        .then(function () {
          showSuccess()
        })
        .catch(function (err) {
          console.log('Clipboard API failed, trying fallback:', err)
          
          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 successful = document.execCommand('copy')
      if (successful) {
        onSuccess()
      } else {
        onError()
      }
    } catch (err) {
      console.error('Fallback copy failed:', err)
      onError()
    } finally {
      document.body.removeChild(textArea)
    }
  }

  
  function checkPayment() {
    if (isCheckingPayment) {
      return
    }

    var button = checkPaymentButton.first()
    var orderId = $('.anycoin-payment-status').data('order-id')

    if (!orderId) {
      console.error('No order ID found')
      return
    }

    
    isCheckingPayment = true

    
    var originalText = button.text()
    button
      .text(anycoin_params.checking_text)
      .prop('disabled', true)
      .addClass('checking')

    
    if (!button.find('.checking-animation').length) {
      button.prepend('<span class="checking-animation"></span>')
    }

    
    $.ajax({
      url: anycoin_params.ajax_url,
      type: 'POST',
      data: {
        action: 'anycoin_check_payment',
        order_id: orderId,
        nonce: anycoin_params.nonce,
      },
      success: function (response) {
        isCheckingPayment = false

        if (response.success) {
          
          if (response.data.status === 'confirmed') {
            statusIndicator
              .removeClass('pending detected')
              .addClass('confirmed')
            statusIndicator.html(anycoin_params.confirmed_text)
            button.hide() 

            
            if (paymentCheckInterval) {
              clearInterval(paymentCheckInterval)
            }

            if (confirmationProgress.length) {
              confirmationProgress.find('.progress').css('width', '100%')
              confirmationProgress
                .find('.current-confirmations')
                .text(response.data.required_confirmations)
            }

            
            setTimeout(function () {
              window.location.href = response.data.redirect_url
            }, 3000)
          } else if (response.data.status === 'detected') {
            var confirmations = response.data.confirmations || 0
            var requiredConfirmations =
              response.data.required_confirmations || 10
            var confirmationText = anycoin_params.detected_text.replace(
              '%s',
              confirmations + '/' + requiredConfirmations
            )

            statusIndicator
              .removeClass('pending confirmed failed')
              .addClass('detected')
            statusIndicator.html(confirmationText)

            if (confirmationProgress.length) {
              var progressPercent =
                (confirmations / requiredConfirmations) * 100
              confirmationProgress.show()
              confirmationProgress
                .find('.progress')
                .css('width', progressPercent + '%')
              confirmationProgress
                .find('.current-confirmations')
                .text(confirmations)
            }

            button
              .text(originalText)
              .prop('disabled', false)
              .removeClass('checking')
            button.find('.checking-animation').remove()
          } else if (response.data.status === 'failed') {
            
            statusIndicator
              .removeClass('pending detected confirmed')
              .addClass('failed')
            statusIndicator.html(
              response.data.message || anycoin_params.failed_text
            )
            button.hide() 

            
            if (paymentCheckInterval) {
              clearInterval(paymentCheckInterval)
            }

            
            setTimeout(function () {
              alert('Payment failed or expired. Please try again.')
              window.location.href =
                response.data.redirect_url || window.location.origin
            }, 2000)
          } else {
            
            statusIndicator
              .removeClass('detected confirmed failed')
              .addClass('pending')
            statusIndicator.html(anycoin_params.pending_text)

            
            button
              .text(originalText)
              .prop('disabled', false)
              .removeClass('checking')
            button.find('.checking-animation').remove()
          }
        } else {
          
          console.error('Error checking payment:', response.data.message)

          
          button
            .text(originalText)
            .prop('disabled', false)
            .removeClass('checking')
          button.find('.checking-animation').remove()
        }
      },
      error: function (xhr, status, error) {
        isCheckingPayment = false
        console.error('AJAX error:', error)

        
        button
          .text(originalText)
          .prop('disabled', false)
          .removeClass('checking')
        button.find('.checking-animation').remove()
      },
    })
  }

  
  checkPaymentButton.on('click', function (e) {
    e.preventDefault()
    checkPayment()
  })


  if (checkPaymentButton.length > 0) {
    
    setTimeout(function () {
      checkPayment()
    }, 3000)

    
    paymentCheckInterval = setInterval(function () {
      checkPayment()
    }, 10000)
  }
})


