import { Application } from "@hotwired/stimulus"

const application = Application.start()

// Configure Stimulus development experience
application.debug = false
window.Stimulus   = application

export { application }

// Transition for turbo_frames
// URL: https://dev.to/nejremeslnici/how-to-use-view-transitions-in-hotwire-turbo-1kdi
// Alternative turbo_stream URL: https://evilmartians.com/chronicles/the-future-of-full-stack-rails-turbo-view-transitions
addEventListener("turbo:before-frame-render", (event) => {
  if (document.startViewTransition) {
    const originalRender = event.detail.render
    event.detail.render = (currentElement, newElement) => {
      document.startViewTransition(()=> originalRender(currentElement, newElement))
    }
  }
})

// URL: https://edforshaw.co.uk/hotwire-turbo-stream-animations
// and: https://stackoverflow.com/questions/61306601/css-animation-on-table-row-how-to-affect-height
// Alternative Hotwire Animate (Wrapper for Animate.css)
// URL: https://railshackathon.com/entries/12 https://yozu.co.uk/tech-blog-turbocharged-animations-introducing-hotwire-animate/
// Discussion about hotwire animation: https://discuss.hotwired.dev/t/are-transitions-and-animations-on-hotwire-roadmap/1547/10
document.addEventListener("turbo:before-stream-render", (event) => {
    // Add a class to an element we are about to add to the page
    // as defined by its "data-stream-enter-class"
    if (event.target.firstElementChild instanceof HTMLTemplateElement) {
      var enterAnimationClass = event.target.templateContent.firstElementChild.dataset.streamEnterClass
      if (enterAnimationClass) {
        event.target.templateElement.content.firstElementChild.classList.add(enterAnimationClass)
      }
    }
    // Add a class to an element we are about to remove from the page
    // as defined by its "data-stream-exit-class"
   var elementToRemove = document.getElementById(event.target.target)
   if (elementToRemove) {
     var streamExitClass = elementToRemove.dataset.streamExitClass
     if (streamExitClass) {
       // Intercept the removal of the element
       event.preventDefault()
      //  elementToRemove.classList.remove(elementToRemove.dataset.streamEnterClass)
       elementToRemove.classList.add(streamExitClass)
       // Wait for its animation to end before removing the element
       elementToRemove.addEventListener("animationend", function() {
         event.target.performAction()
       })
     }
   }
  })
