import Slideshow from '@brandcode/slideshow'

((Drupal, once) => {
  'use strict'

  const checkNodeForChanges = async (id, lastCheckTimestamp) => {
    try {
      const response = await fetch(`/api/slide_set/changed/${id}`, {
        headers: {
          Accept: 'application/vnd.api+json',
        },
      })

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

      const data = await response.json()

      return data.changed > lastCheckTimestamp
    } catch (error) {
      console.error('Fehler beim Prüfen der Node-Änderungen:', error)
      return false
    }
  }

  Drupal.behaviors.slideshow = {
    attach(context) {
      for (const slideset of once('slideset', '.slide-set', context)) {
        new Slideshow(slideset, { mode: 'detect' })

        if (slideset.dataset.id) {
          const startTimestamp = Math.floor(Date.now() / 1000)

          setInterval(async () => {
            const hasChanges = await checkNodeForChanges(slideset.dataset.id, startTimestamp)
            if (hasChanges) {
              window.location.reload()
            }
          }, 60000)
        }
      }
    },
  }
})(Drupal, once)
