import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static targets = ["select", "current"]
  static values = { url: String }

  connect() {        
  }
  
  disconnect() {    
  }


  changeLocale() {
    
    this.currentTarget.textContent = this.selectTarget.options[this.selectTarget.selectedIndex].textContent

    // Create form data to send
    const formData = new FormData()
    formData.append("locale", this.selectTarget.value)
    
    // Make the PUT request using fetch
    fetch(this.urlValue, {
      method: "PUT",
      headers: {
        'Accept': "text/vnd.turbo-stream.html",
        "X-CSRF-Token": this.getMetaValue("csrf-token")
      },
      body: formData
    })
    .then (response => response.text())
    .then(html => {
      
      Turbo.renderStreamMessage(html)
      document.documentElement.setAttribute('lang', this.selectTarget.value)                

      requestAnimationFrame(() => {
        document.querySelectorAll('.animation-element').forEach((animationElement) => {
          animationElement.style.opacity = 1
        })    
        
      })
      
    })
    .catch((err) => {
      console.info('rejected', err)
    })
    
  }
  
  // Helper method to get CSRF token
  getMetaValue(name) {
    const element = document.head.querySelector(`meta[name="${name}"]`)
    return element.getAttribute("content")
  }
}