document.addEventListener('DOMContentLoaded', function () {
  function setupConfirmation(buttonId, formId, message) {
    const button = document.getElementById(buttonId)
    const form = document.getElementById(formId)

    if (!button || !form) return

    button.addEventListener('click', function (event) {
      const message = form.getAttribute('data-confirm')
      if (confirm(message)) {
        form.submit()
      } else {
        event.preventDefault()
      }
    })
  }

  setupConfirmation('ecc-reset', 'ecc-reset-form')
  setupConfirmation('ecc-delete', 'ecc-delete-form')
  setupConfirmation('ecc-uninstall', 'ecc-uninstall-form')

  function toggleDeleteSection() {
    const mode = document.querySelector('input[name="easy_cc_critical_css_mode"]:checked')?.value
    const section = document.getElementById('ecc-delete-section')
    if (!section) return

    // Only show when mode is auto
    section.style.display = (mode === 'auto') ? '' : 'none'
  }

  function toggleAutoModeStatus() {
    const mode = document.querySelector('input[name="easy_cc_critical_css_mode"]:checked')?.value
    const statusContainer = document.getElementById('auto-mode-status-container')
    if (!statusContainer) return

    // Only show when mode is auto
    statusContainer.style.display = (mode === 'auto') ? '' : 'none'
  }

  function toggleSettingVisibility(settingId, behavior = false) {
    const mode = document.querySelector('input[name="easy_cc_critical_css_mode"]:checked')?.value
    const behaviorValue = behavior ? document.querySelector('input[name="easy_cc_secondary_css_behavior"]:checked')?.value : null
    const container = document.getElementById(settingId)

    if (container) {
      const row = container.closest("tr") // Get parent <tr>
      if (behaviorValue) {
        row.style.display = (mode === "manual" || behaviorValue === "remaining") ? "none" : "table-row"
      } else {
        row.style.display = (mode === "manual") ? "none" : "table-row"
      }
    }
  }

  function updateExcludeCssLabel() {
    var mode = document.querySelector('input[name="easy_cc_critical_css_mode"]:checked')?.value
    var container = document.getElementById('exclude-css-files-container')
    if (!container) return

    var row = container.closest('tr')
    var labelEl = null
    if (row) {
      labelEl = row.querySelector('th')
    }
    var descEl = container.querySelector('.description')
    if (!labelEl || !descEl) return

    if (mode === 'manual') {
      if (easyCriticalCss.excludeLabelManual) labelEl.textContent = easyCriticalCss.excludeLabelManual
      if (easyCriticalCss.excludeDescManual) descEl.innerHTML = easyCriticalCss.excludeDescManual
    } else {
      if (easyCriticalCss.excludeLabelAuto) labelEl.textContent = easyCriticalCss.excludeLabelAuto
      if (easyCriticalCss.excludeDescAuto) descEl.innerHTML = easyCriticalCss.excludeDescAuto
    }
  }

  // Add event listeners on setting changes
  function setupToggleListeners() {
    document.querySelectorAll('input[name="easy_cc_critical_css_mode"]').forEach((el) => {
      el.addEventListener('change', () => {
        toggleSettingVisibility('secondary-css-behavior-container')
        toggleSettingVisibility('forced-critical-selectors-container')
        toggleSettingVisibility('forced-secondary-selectors-container', true)
        toggleSettingVisibility('add-common-secondary-container', true)
        toggleSettingVisibility('ignore-cross-domain-css-container')
        toggleSettingVisibility('serve-css-from-files-container')
        toggleSettingVisibility('regenerate-triggers-container')
        toggleSettingVisibility('expired-css-behavior-container')
        toggleSettingVisibility('cloudflare-email-container')
        toggleSettingVisibility('cloudflare-api-key-container')
        toggleSettingVisibility('cloudflare-zone-id-container')
        toggleDeleteSection()
        toggleAutoModeStatus()
        updateExcludeCssLabel()
      })
    })

    document.querySelectorAll('input[name="easy_cc_secondary_css_behavior"]').forEach((el) => {
      el.addEventListener('change', () => {
        toggleSettingVisibility('forced-secondary-selectors-container', true)
        toggleSettingVisibility('add-common-secondary-container', true)
      })
    })
  }
  setupToggleListeners()

  // Cloudflare Change/Undo button logic
  function updateCloudflareChanged(key, add) {
    var hidden = document.getElementById('easy_cc_cloudflare_changed')
    if (!hidden) return
    var arr = hidden.value ? hidden.value.split(',') : []
    if (add) {
      if (!arr.includes(key)) arr.push(key)
    } else {
      arr = arr.filter(function(k) { return k !== key })
    }
    hidden.value = arr.join(',')
  }

  document.querySelectorAll('.ecc-cloudflare-change').forEach(function(btn) {
    btn.addEventListener('click', function() {
      var key = btn.getAttribute('data-cloudflare-key')
      var field = document.querySelector('input[data-cloudflare-key="' + key + '"]')
      var undoBtn = document.querySelector('.ecc-cloudflare-undo[data-cloudflare-key="' + key + '"]')
      if (field) {
        field.disabled = false
        field.value = ''
        field.focus()
        btn.style.display = 'none'
        if (undoBtn) undoBtn.style.display = ''
        updateCloudflareChanged(key, true)
      }
    })
  })

  document.querySelectorAll('.ecc-cloudflare-undo').forEach(function(btn) {
    btn.addEventListener('click', function() {
      var key = btn.getAttribute('data-cloudflare-key')
      var field = document.querySelector('input[data-cloudflare-key="' + key + '"]')
      var changeBtn = document.querySelector('.ecc-cloudflare-change[data-cloudflare-key="' + key + '"]')
      if (field) {
        field.disabled = true
        var masked = field.getAttribute('data-original-masked')
        if (masked !== null) field.value = masked
        btn.style.display = 'none'
        if (changeBtn) changeBtn.style.display = ''
        updateCloudflareChanged(key, false)
      }
    })
  })

  // Advanced settings toggle
  const toggleButton = document.getElementById('ecc-toggle-advanced')
  const advancedSettings = document.getElementById('ecc-advanced-settings')

  if (toggleButton && advancedSettings) {
    toggleButton.addEventListener('click', function(e) {
      e.preventDefault()

      const isVisible = advancedSettings.style.display !== 'none'

      if (isVisible) {
        advancedSettings.style.display = 'none'
        toggleButton.innerHTML = '<span class="dashicons dashicons-arrow-right"></span> Show Advanced Settings'
        toggleButton.classList.remove('expanded')
      } else {
        advancedSettings.style.display = 'block'
        toggleButton.innerHTML = '<span class="dashicons dashicons-arrow-down"></span> Hide Advanced Settings'
        toggleButton.classList.add('expanded')
      }
    })
  }

  // Auto mode status details toggle
  document.querySelectorAll('.ecc-status-toggle').forEach(function(btn) {
    btn.addEventListener('click', function(e) {
      e.preventDefault()
      const statusContainer = this.closest('.ecc-auto-mode-status')
      if (!statusContainer) return

      const details = statusContainer.querySelector('.ecc-status-details')
      if (!details) return

      const isVisible = details.style.display !== 'none'
      details.style.display = isVisible ? 'none' : 'block'
      this.textContent = isVisible ? 'Details' : 'Hide'
    })
  })

  // Auto mode status refresh button
  document.querySelectorAll('.ecc-status-refresh').forEach(function(btn) {
    btn.addEventListener('click', function(e) {
      e.preventDefault()

      btn.disabled = true
      btn.textContent = 'Refreshing...'

      fetch(`${easyCriticalCss.restUrl}refresh-auto-mode-status`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-WP-Nonce': easyCriticalCss.nonce
        }
      })
      .then(response => {
        if (!response.ok) {
          throw new Error('HTTP ' + response.status + ': ' + response.statusText)
        }
        return response.json()
      })
      .then(data => {
        // Update status display
        const statusContainer = btn.closest('.ecc-auto-mode-status')
        if (!statusContainer) return

        const allOk = data.all_ok
        const activeKeyOk = data.active_key
        const localOk = data.local_ok
        const restApiOk = data.rest_api_ok

        // Update main status
        const icon = statusContainer.querySelector('.ecc-status-icon')
        const text = statusContainer.querySelector('.ecc-status-text')
        const statusClass = allOk ? 'ecc-status-ready' : 'ecc-status-blocked'

        icon.style.color = allOk ? '#1e7e34' : '#b12331'
        icon.textContent = allOk ? '✓' : '✕'
        text.textContent = allOk ? 'Auto mode ready' : 'Auto mode cannot run'

        statusContainer.className = 'ecc-auto-mode-status ' + statusClass

        // Update details
        const checks = statusContainer.querySelectorAll('.ecc-check')
        const detailItems = statusContainer.querySelectorAll('.ecc-status-details li')

        // Map checks/detailItems to the correct data: 0=Active API Key, 1=Local Install, 2=REST API Reachable
        if (checks[0]) {
          checks[0].className = 'ecc-check ' + (activeKeyOk ? 'ecc-check-ok' : 'ecc-check-fail')
          checks[0].textContent = activeKeyOk ? '✓' : '✕'
        }

        if (checks[1]) {
          checks[1].className = 'ecc-check ' + (localOk ? 'ecc-check-ok' : 'ecc-check-fail')
          checks[1].textContent = localOk ? '✓' : '✕'
        }

        if (checks[2]) {
          checks[2].className = 'ecc-check ' + (restApiOk ? 'ecc-check-ok' : 'ecc-check-fail')
          checks[2].textContent = restApiOk ? '✓' : '✕'
        }

        // Helper: replace any plain text error nodes with an <em>, or remove them when OK
        function setDetailMessage(li, ok, message) {
          if (!li) return
          const em = li.querySelector('em')
          // Remove any plain text nodes (text nodes that are not the <strong> or <span>)
          const textNodes = Array.from(li.childNodes).filter(function(n) {
            return n.nodeType === Node.TEXT_NODE && n.textContent.trim().length > 0
          })

          if (!ok) {
            if (em) return // already present
            // remove existing plain text nodes so we don't duplicate messages
            textNodes.forEach(function(n) { n.remove() })
            const newEm = document.createElement('em')
            newEm.textContent = message
            li.appendChild(newEm)
          } else {
            if (em) em.remove()
            // also remove any lingering plain text error nodes
            textNodes.forEach(function(n) { n.remove() })
          }
        }

        // Active API Key (detailItems[0])
        setDetailMessage(detailItems[0], activeKeyOk, 'No active API key')
        // Local Install (detailItems[1])
        setDetailMessage(detailItems[1], localOk, 'Site is local')
        // REST API Reachable (detailItems[2])
        setDetailMessage(detailItems[2], restApiOk, 'Generator cannot reach the site')
        
        btn.disabled = false
        btn.textContent = 'Refresh'
      })
      .catch(error => {
        console.error('Error refreshing auto mode status:', error)
        btn.disabled = false
        btn.textContent = 'Refresh'
      })
    })
  })

  // Run on page load
  toggleSettingVisibility('secondary-css-behavior-container')
  toggleSettingVisibility('forced-critical-selectors-container')
  toggleSettingVisibility('forced-secondary-selectors-container', true)
  toggleSettingVisibility('add-common-secondary-container', true)
  toggleSettingVisibility('ignore-cross-domain-css-container')
  toggleSettingVisibility('serve-css-from-files-container')
  toggleSettingVisibility('regenerate-triggers-container')
  toggleSettingVisibility('expired-css-behavior-container')
  toggleSettingVisibility('cloudflare-email-container')
  toggleSettingVisibility('cloudflare-api-key-container')
  toggleSettingVisibility('cloudflare-zone-id-container')
  toggleDeleteSection()
  toggleAutoModeStatus()
  updateExcludeCssLabel()

  // Subscription notification actions
  document.addEventListener('click', function (e) {
    // Handle dismiss button
    if (e.target.closest('.ecc-subscription-notice .notice-dismiss')) {
      e.preventDefault()

      fetch(`${eccSubscriptionNotice.restUrl}dismiss-notification`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-WP-Nonce': eccSubscriptionNotice.nonce
        }
      })
      .then(response => {
        if (!response.ok) {
          throw new Error('HTTP ' + response.status + ': ' + response.statusText)
        }
        return response.json()
      })
      .catch(error => {
        console.log('Notification dismiss via REST failed:', error)
      })
      return
    }

    // Handle activate button
    if (e.target.closest('#ecc-activate-auto-generation')) {
      e.preventDefault()
      const activateBtn = e.target.closest('#ecc-activate-auto-generation')
      const autoRadio = document.querySelector('input[name="easy_cc_critical_css_mode"][value="auto"]')

      if (autoRadio) {
        // We're on the settings page: click the radio button
        autoRadio.click()
        activateBtn.classList.add('disabled')
        activateBtn.textContent = 'Activated'
      } else {
        activateBtn.classList.add('disabled')
        activateBtn.textContent = 'Activating...'

        fetch(`${eccSubscriptionNotice.restUrl}activate-auto`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-WP-Nonce': eccSubscriptionNotice.nonce
          },
          body: JSON.stringify({})
        })
        .then(response => response.json())
        .then(data => {
          if (data && !data.code) {
            const notice = activateBtn.closest('.ecc-subscription-notice')
            if (notice) notice.innerHTML = '<p style="font-weight:600;">Success</p><p>Auto-generation has been activated.</p>'
          } else {
            throw new Error(data.message || 'Failed')
          }
        })
        .catch(error => {
          console.error('Activation via REST failed:', error)
          activateBtn.classList.remove('disabled')
          activateBtn.textContent = 'Activate Auto Generation'
        })
      }
    }
  })
})
