(function ($, Drupal, drupalSettings, once) {
  'use strict'

  Drupal.behaviors.alfaScanDisplay = {
    attach (context) {
      once('alfaScanDisplay', context.querySelector('body')).forEach(() => {
        const nodeId = drupalSettings?.siteimprove_accessibility?.node?.id

        if (!nodeId) {
          return
        }

        const apiUrl = `/siteimprove-accessibility/alfa-scan/node/${nodeId}`

        fetch(apiUrl, {
          method: 'GET',
          headers: { 'Accept': 'application/json' },
          credentials: 'include'
        })
          .then(response => {
            if (!response.ok) {
              throw new Error(`AlfaScan fetch failed with status ${response.status}`)
            }
            return response.json()
          })
          .then(data => {
            if (!data.scan_results) {
              return
            }

            // Pass results to alfaRendererSPRI
            if (Drupal.alfaActions?.alfaRendererSPRI) {
              $('.alfa-scan-date').text(data.changed)
              Drupal.alfaActions.alfaRendererSPRI({ failedItems: data.scan_results })
            }
            else {
              return
            }
          })
          .catch(error => console.error('Error fetching AlfaScan data.'))
      })
    },
  }

  Drupal.behaviors.alfaScanPageCheck = {
    attach(context) {
      once('alfaScanDisplay', '.siteimprove-scan-button', context).forEach((el) => {
        el.addEventListener('click', () => {
          const preview = document.getElementById('edit-preview');
          const icon = el.querySelector('.icon');

          if (icon) {
            icon.classList.add('is-loading');
          }

          preview.click();

          const form = document.querySelector('form');
          if (form) {
            form.addEventListener('submit', () => {
              if (icon) {
                icon.classList.remove('is-loading');
              }
            });
          }
        });
      });
    },
  };

  Drupal.siteimproveAccessibility = Drupal.siteimproveAccessibility || {}

  Drupal.siteimproveAccessibility.complianceDashboard = {
    /**
     * Fetches daily stats data from the server.
     * @returns {Promise<Object | null>}
     */
    async getData () {
      try {
        const response = await fetch('/siteimprove-accessibility/daily-stats', {
          headers: { 'Accept': 'application/json' },
        })

        if (!response.ok) {
          throw new Error(`HTTP error! Status: ${response.status}`)
        }

        return await response.json()
      }
      catch (error) {
        console.error('Failed to fetch daily stats:', error)
        return null
      }
    },
  }

  Drupal.behaviors.complianceDashboard = {
    attach (context) {
      once('complianceDashboard', context.querySelectorAll('#compliance-dashboard')).forEach((el) => {
        (async () => {
          const stats = await Drupal.siteimproveAccessibility.complianceDashboard.getData()
          if (stats && Drupal.alfaActions?.alfaRendererCD) {
            Drupal.alfaActions.alfaRendererCD(stats)
          }
        })()
      })
    }
  }

  Drupal.behaviors.siteimproveScanReport = {
    attach (context) {
      const containerId = 'siteimprove-scan-report'

      once('siteimprove-scan-report', `#${containerId}`, context).forEach((element) => {
        this.initializeReport(element)
      })
    },

    async initializeReport (element) {
      try {
        const issues = await this.fetchData('/siteimprove-accessibility/issues')
        const pagesCallback = this.createPagesCallback()
        this.renderReport(issues, pagesCallback, element.id)
      }
      catch (error) {
        this.handleError(error)
      }
    },

    async fetchData (url, params = {}) {
      const response = await fetch(this.buildUrl(url, params), {
        method: 'GET',
        headers: this.getRequestHeaders(),
        credentials: 'same-origin',
      })

      if (!response.ok) {
        throw new Error(Drupal.t('Request failed with status @status', { '@status': response.status }))
      }

      return await response.json()
    },

    createPagesCallback () {
      return async (params) => this.fetchData('/siteimprove-accessibility/pages-with-issues', params)
    },

    buildUrl (baseUrl, params = {}) {
      const url = new URL(baseUrl, window.location.origin)
      const processedParams = {}

      Object.entries(params).forEach(([key, value]) => {
        processedParams[key] = typeof value === 'object' && value !== null
          ? encodeURIComponent(JSON.stringify(value))
          : value
      })

      url.search = new URLSearchParams(processedParams).toString()
      return url.pathname + url.search
    },

    getRequestHeaders () {
      return new Headers({ 'Content-Type': 'application/json' })
    },

    renderReport (issues, pagesCallback, containerId) {
      if (Drupal.alfaActions?.alfaRendererIssueReporting && issues.length) {
        Drupal.alfaActions.alfaRendererIssueReporting(issues, pagesCallback, containerId)
      }
      else {
        $('.siteimprove-component-placeholder').hide();
        $('.siteimprove-empty-issues-container').show();
      }
    },

    handleError (error) {
      Drupal.announce(Drupal.t('Failed to load accessibility data. Please try again later.'), 'assertive')
    },
  }

})(jQuery, Drupal, drupalSettings, once)
