 
let currencyRates = {}

fetch('https://open.er-api.com/v6/latest/USD')
   .then(res => res.json())
   .then(data => {
      currencyRates = data.rates
      console.log(currencyRates)            

      const ratesForm = document.forms.rates
      const firstField = ratesForm.first_field
      const secondField = ratesForm.second_field
      const firstList = ratesForm.first_list
      const secondList = ratesForm.second_list

      
      for (const key in currencyRates) {
        const newOption = new Option(key, currencyRates[key])
        firstList.append(newOption)
        secondList.append(newOption.cloneNode(true))
      }
      
      ratesForm.addEventListener("input", (event) => {
         const actionEl = event.target

         const firstCurrency = parseFloat(firstList.value)
         const secondCurrency = parseFloat(secondList.value)
      
         const firstAmount = parseFloat(firstField.value)
         const secondAmount = parseFloat(secondField.value)

         if (actionEl.closest(".input_container.col1") || actionEl.closest(".select_container.col2")) {
            if (firstAmount) {
               secondField.value = ((firstAmount * secondCurrency) / firstCurrency).toFixed(2)
            } else {
               secondField.value = 0
            }           
         }

         if (actionEl.closest(".input_container.col2") || actionEl.closest(".select_container.col1")) {
            if (secondAmount) {
               firstField.value = ((secondAmount * firstCurrency) / secondCurrency).toFixed(2)
            } else {
               firstField.value = 0
            } 
         }         

      })
      
   })
