async function fetchData() {
  const apiKey = "yIew9vZPUz2BDHJkghKZd4NkEcZv9FSx2sHyzfoo";
  const apiUrl = "https://cqyc5wd9cf.execute-api.eu-north-1.amazonaws.com/live";

  try {
    const response = await fetch(apiUrl, {
      method: "GET",
      headers: {
        "x-api-key": apiKey,
      },
    });

    if (!response.ok) {
      throw new Error("Network response was not ok");
    }

    const data = await response.json();
    return data;
  } catch (error) {
    console.error("There was a problem with the fetch operation:", error);
    return null;
  }
}

async function initializeForm() {
  const jsonData = await fetchData();

  if (!jsonData) {
    console.error("Unable to fetch JSON data.");
    return;
  }

  const items = jsonData.items;
  console.log(items);

  function populateCurrencySelect(items) {
    const selectField = document.getElementById("currencySelect");

    if (selectField) {
      selectField.innerHTML = "";

      items.reverse().forEach((item) => {
        const option = document.createElement("option");
        option.value = items.indexOf(item);
        option.textContent = item.fieldData.name;
        option.style.backgroundImage = `url(${item.fieldData["currency-country-icon"].url})`;
        selectField.appendChild(option);
      });
    } else {
      console.error("Currency select field not found.");
    }
  }

  const selectField = document.getElementById("currencySelect");
  const buyCardTextBlock = document.getElementById("buy-card-value");
  const citySelectField = document.getElementById("City");
  const inputValue = document.getElementById("inputValue");
  const outputValue = document.getElementById("outputValue");
  const currencyIcon = document.getElementById("currency-icon");
  const radioForexCard = document.getElementById("Forex-card");
  const radioCash = document.getElementById("Cash");
  const noInput = document.querySelectorAll("[noInput]");

  function updateBuyCardValue(selectedItem, selectedCity, selectedOption) {
    if (!selectedCity || selectedCity === "") {
      selectedCity = "Delhi"; // Default city value
    }

    const selectedIndex = parseInt(selectField.value);

    if (selectedIndex !== null && selectedItem) {
      const cityToKeyMap = {
        Delhi:
          selectedOption === "Cash" ? "delhi-buy-cash" : "delhi-buy-forex-card",
        Gurgaon:
          selectedOption === "Cash" ? "delhi-buy-cash" : "delhi-buy-forex-card",
        Noida:
          selectedOption === "Cash" ? "delhi-buy-cash" : "delhi-buy-forex-card",
        Faridabad:
          selectedOption === "Cash" ? "delhi-buy-cash" : "delhi-buy-forex-card",
        Ahmedabad:
          selectedOption === "Cash"
            ? "ahmedabad-buy-cash"
            : "ahmedabad-buy-forex-card",
        Hyderabad:
          selectedOption === "Cash"
            ? "hyderabad---buy-cash"
            : "hyderabad---buy-forex-card",
        Kolkata:
          selectedOption === "Cash"
            ? "kolkata-buy-cash"
            : "kolkata-buy-forex-card",
      };

      const key = cityToKeyMap[selectedCity];

      if (key && selectedItem) {
        const buyForexCardValue = parseFloat(selectedItem.fieldData[key]);

        if (buyCardTextBlock) {
          const decimalValue = buyForexCardValue.toFixed(2);
          buyCardTextBlock.textContent = decimalValue;

          updateOutputValue();
        } else {
          console.error("Buy Card text block not found.");
        }
      } else {
        console.error("Key or currency not found.");
      }
    } else {
      console.error("Currency not selected.");
    }
  }

  function setBackgroundImage(element, url) {
    if (element && url) {
      element.style.backgroundImage = `url(${url})`;
    } else {
      console.error("Element or URL not found.");
    }
  }

  function handleRadioButtonChange() {
    const selectedIndex = parseInt(selectField.value);
    const selectedItem = items[selectedIndex];
    const selectedCity = citySelectField.value;
    const selectedOption = radioForexCard.checked ? "Forex-card" : "Cash";
    updateBuyCardValue(selectedItem, selectedCity, selectedOption);
    //selectField Icon
    if (selectedItem) {
      // Set background image URL for selectField based on the selected item's currency icon
      setBackgroundImage(
        selectField,
        selectedItem.fieldData["currency-country-icon"]?.url
      );

      // Set background image URL for inputValue based on the selected item's currency icon
      setBackgroundImage(
        inputValue,
        selectedItem.fieldData["currency-icon"]?.url
      );

      // Set background image URL for currencyIcon based on the selected item's currency icon
      setBackgroundImage(
        currencyIcon,
        selectedItem.fieldData["currency-icon"]?.url
      );
    } else {
      console.error("Selected item not found.");
    }
  }

  function updateOutputValue() {
    const userInput = parseFloat(inputValue.value);
    const buyCardValue = parseFloat(buyCardTextBlock.textContent);

    if (isNaN(userInput) || isNaN(buyCardValue)) {
      outputValue.value = "";
    } else {
      const result = userInput * buyCardValue;
      outputValue.value = result.toFixed(2);
    }
  }

  selectField.addEventListener("change", handleRadioButtonChange);
  citySelectField.addEventListener("change", handleRadioButtonChange);
  radioForexCard.addEventListener("change", handleRadioButtonChange);
  radioCash.addEventListener("change", handleRadioButtonChange);

  inputValue.addEventListener("input", updateOutputValue);

  populateCurrencySelect(items);

  updateBuyCardValue(items[0], "", "");

  noInput.forEach((element) => {
    element.addEventListener("input", () => {
      if (inputValue.value.trim() === "") {
        outputValue.value = "";
      }
    });
  });
}

initializeForm();

async function initializeForm2() {
  const jsonData = await fetchData();

  if (!jsonData) {
    console.error("Unable to fetch JSON data.");
    return;
  }

  //code for 2nd initializeForm
  const items2 = jsonData.items;

  function populateCurrencySelect2(items) {
    const selectField = document.getElementById("currencySelect2");

    if (selectField) {
      selectField.innerHTML = "";

      items.reverse().forEach((item) => {
        const option = document.createElement("option");
        option.value = items.indexOf(item);
        option.textContent = item.fieldData.name;
        option.style.backgroundImage = `url(${item.fieldData["currency-country-icon"].url})`;
        selectField.appendChild(option);
      });
    } else {
      console.error("Currency select field not found.");
    }
  }

  const selectField2 = document.getElementById("currencySelect2");
  const buyCardTextBlock2 = document.getElementById("buy-card-value2");
  const citySelectField2 = document.getElementById("City2");
  const inputValue2 = document.getElementById("inputValue2");
  const outputValue2 = document.getElementById("outputValue2");
  const currencyIcon2 = document.getElementById("currency-icon2");
  const radioForexCard2 = document.getElementById("Forex-card2");
  const radioCash2 = document.getElementById("Cash2");
  const noInput2 = document.querySelectorAll("[noInput2]");

  function updateBuyCardValue2(selectedItem, selectedCity, selectedOption) {
    if (!selectedCity || selectedCity === "") {
      selectedCity = "Delhi"; // Default city value
    }

    const selectedIndex = parseInt(selectField2.value);

    if (selectedIndex !== null && selectedItem) {
      const cityToKeyMap = {
        Delhi:
          selectedOption === "Cash"
            ? "delhi-sell-cash"
            : "delhi-sell-forex-card-2",
        Gurgaon:
          selectedOption === "Cash"
            ? "delhi-sell-cash"
            : "delhi-sell-forex-card-2",
        Noida:
          selectedOption === "Cash"
            ? "delhi-sell-cash"
            : "delhi-sell-forex-card-2",
        Faridabad:
          selectedOption === "Cash"
            ? "delhi-sell-cash"
            : "delhi-sell-forex-card-2",
        Ahmedabad:
          selectedOption === "Cash"
            ? "ahmedabad-sell-cash"
            : "ahmedabad-sell-forex-card",
        Hyderabad:
          selectedOption === "Cash"
            ? "hyderabad---sell-cash"
            : "hyderabad---sell-forex-card",
        Kolkata:
          selectedOption === "Cash"
            ? "kolkata-sell-cash"
            : "kolkata-sell-forex-card",
      };

      const key = cityToKeyMap[selectedCity];

      if (key && selectedItem) {
        const buyForexCardValue = parseFloat(selectedItem.fieldData[key]);

        if (buyCardTextBlock2) {
          const decimalValue = buyForexCardValue.toFixed(2);
          buyCardTextBlock2.textContent = decimalValue;

          updateOutputValue2();
        } else {
          console.error("Buy Card text block not found.");
        }
      } else {
        console.error("Key or currency not found.");
      }
    } else {
      console.error("Currency not selected.");
    }
  }

  function setBackgroundImage(element, url) {
    if (element && url) {
      element.style.backgroundImage = `url(${url})`;
    } else {
      console.error("Element or URL not found.");
    }
  }

  function handleRadioButtonChange2() {
    const selectedIndex = parseInt(selectField2.value);
    const selectedItem = items2[selectedIndex];

    const selectedCity = citySelectField2.value;
    const selectedOption = radioForexCard2.checked ? "Forex-card" : "Cash";
    updateBuyCardValue2(selectedItem, selectedCity, selectedOption);
    //updatebg
    if (selectedItem) {
      // Set background image URL for selectField based on the selected item's currency icon
      setBackgroundImage(
        selectField2,
        selectedItem.fieldData["currency-country-icon"]?.url
      );

      // Set background image URL for inputValue based on the selected item's currency icon
      setBackgroundImage(
        inputValue2,
        selectedItem.fieldData["currency-icon"]?.url
      );

      // Set background image URL for currencyIcon based on the selected item's currency icon
      setBackgroundImage(
        currencyIcon2,
        selectedItem.fieldData["currency-icon"]?.url
      );
    } else {
      console.error("Selected item not found.");
    }
  }

  function updateOutputValue2() {
    const userInput = parseFloat(inputValue2.value);
    const buyCardValue = parseFloat(buyCardTextBlock2.textContent);

    if (isNaN(userInput) || isNaN(buyCardValue)) {
      outputValue2.value = "";
    } else {
      const result = userInput * buyCardValue;
      outputValue2.value = result.toFixed(2);
    }
  }

  selectField2.addEventListener("change", handleRadioButtonChange2);
  citySelectField2.addEventListener("change", handleRadioButtonChange2);
  radioForexCard2.addEventListener("change", handleRadioButtonChange2);
  radioCash2.addEventListener("change", handleRadioButtonChange2);

  inputValue2.addEventListener("input", updateOutputValue2);

  populateCurrencySelect2(items2);

  updateBuyCardValue2(items2[0], "", "");

  noInput2.forEach((element) => {
    element.addEventListener("input", () => {
      if (inputValue2.value.trim() === "") {
        outputValue2.value = "";
      }
    });
  });
}

initializeForm2();