$(document).ready(function () {
  var inputFieldMap = {
    goud: "goudwaardeuro",
    zilver: "zilverwaardeeuro",
    aandelenVerkoop: "aandelenverkoop",
    aandelenAndereReden: "aandelenanderereden",
    pensionValue: "pensioen",
    // Add other mappings as needed
  };

  // Get the URL search parameters
  const urlParams = new URLSearchParams(window.location.search);

  // Create a JSON object to store the query parameters
  const queryParams = {};

  // Check if the "isSavedLink" parameter is set to true
  if (urlParams.has("isSavedLink") && urlParams.get("isSavedLink") === "true") {
    // Loop through each parameter except 'possessions' and add it to the JSON object
    urlParams.forEach((value, key) => {
      if (key !== "possessions") {
        queryParams[key] = value;
      }
    });

    // Check if 'possessions' parameter is available
    if (urlParams.has("possessions")) {
      // Split the 'possessions' value into an array, decode each item, and add to the JSON object
      queryParams["possessions"] = urlParams
        .get("possessions")
        .split(",")
        .map(decodeURIComponent);
    }

    // Convert the JSON object to a string
    const queryParamsString = JSON.stringify(queryParams);

    // Store the JSON string in sessionStorage with the key "userslowlane"
    sessionStorage.setItem("userslowlane", queryParamsString);

    // Remove all parameters from the URL
    history.replaceState({}, document.title, window.location.pathname);
  }

  function getuserslowlaneFromSession() {
    var storedData = sessionStorage.getItem("userslowlane");
    if (storedData) {
      return JSON.parse(storedData);
    } else {
      return {};
    }
  }

  function updateURLAndSubmit(buttonId, submitId) {
    // Step 1: Get the base URL (without query parameters)
    var baseUrl = window.location.origin + window.location.pathname;

    // Step 2: Start building the new URL with 'isSavedLink=true'
    var newURL = `${baseUrl}?isSavedLink=true`;

    // Step 3: Retrieve values from sessionStorage
    var userslowlane = getuserslowlaneFromSession();

    // Step 4: Append session storage data to the URL
    for (var key in userslowlane) {
      if (userslowlane.hasOwnProperty(key)) {
        newURL +=
          "&" +
          encodeURIComponent(key) +
          "=" +
          encodeURIComponent(userslowlane[key]);
      }
    }

    // Step 5: Update the hidden input field with the new URL and submit
    console.log(newURL);
    $(".url").val(newURL);
    $(submitId).click();
  }

  $("[FormSubmitOpslaan]").on("click", function () {
    updateURLAndSubmit("[FormSubmitOpslaan]", "[FormSubmitSubmit]");
  });

  $("[FormSubmitOpslaan2]").on("click", function () {
    updateURLAndSubmit("[FormSubmitOpslaan2]", "[FormSubmitSubmit2]");
  });

  function selectUserTypeRadioButton() {
    var userslowlane = getuserslowlaneFromSession();
    if (userslowlane && userslowlane.userType) {
      var userType = userslowlane.userType;
      var radioButtons = document.querySelectorAll(`[usertype="${userType}"]`);
      if (radioButtons.length) {
        radioButtons[0].click(); // Simulate a click instead of setting checked
      }
    }
  }

  function selectPossessionsRadioButtons() {
    var userslowlane = getuserslowlaneFromSession();
    var possessions = [];

    // Combine possessions from both "possessions" and "possessions[]" keys
    if (userslowlane["possessions"]) {
      possessions = possessions.concat(userslowlane["possessions"]);
    }
    if (userslowlane["possessions[]"]) {
      possessions = possessions.concat(userslowlane["possessions[]"]);
    }

    // Remove duplicates and ensure it's an array
    possessions = Array.from(new Set(possessions));

    possessions.forEach(function (possession) {
      var possessionRadioButton = document.querySelector(
        `[possessions="${possession}"]`,
      );
      if (possessionRadioButton) {
        possessionRadioButton.click(); // Simulate a click on the radio button
      }
    });
  }

  function fillInputFieldsFromSession() {
    var userslowlane = getuserslowlaneFromSession();
    if (!userslowlane) return; // Exit if there's no session storage data

    for (var key in userslowlane) {
      if (userslowlane.hasOwnProperty(key) && userslowlane[key]) {
        // Use the mapping if available, otherwise use the key directly
        var inputFieldKey = inputFieldMap[key] || key;
        var inputField = document.querySelector(
          `[inputpossessions="${inputFieldKey}"]`,
        );

        // Fill the field only if it's empty and trigger an input event
        if (inputField && inputField.value === "") {
          inputField.value = userslowlane[key];
          $(inputField).trigger("input"); // Manually trigger the input event
        }
      }
    }
  }

  function fillValueInputFieldsFromSession() {
    var userslowlane = getuserslowlaneFromSession();
    if (!userslowlane) return; // Exit if there's no session storage data

    // Mapping session storage keys to input field custom attributes
    var inputFieldMap = {
      voornaam: "firstname",
      achternaam: "lastname",
      email: "email",
    };

    Object.keys(inputFieldMap).forEach(function (sessionKey) {
      var inputAttribute = inputFieldMap[sessionKey];
      var fieldValue = userslowlane[sessionKey];

      if (fieldValue) {
        var inputField = document.querySelector(`[input="${inputAttribute}"]`);
        if (inputField && inputField.value === "") {
          inputField.value = fieldValue;
          $(inputField).trigger("input"); // Trigger the input event
        }
      }
    });
  }

  function selectPensionButton() {
    var userslowlane = getuserslowlaneFromSession();

    if (!userslowlane || !Array.isArray(userslowlane.possessions)) {
      console.error("Invalid user data");
      return;
    }

    if (typeof userslowlane.pensionValue === "undefined") {
      console.log("Pension value not set");
      $("[btn_pensioenuitleg]").click();
    } else {
      console.log("Pension value:", userslowlane.pensionValue);
      $("[btn_pensioenpay]").click();
      if (userslowlane.pensionType) {
        var $selectTypePension = $("[selecttypepension]");
        if ($selectTypePension.length)
          $selectTypePension.val(userslowlane.pensionType);
      }
    }
  }

  selectPossessionsRadioButtons();
  selectUserTypeRadioButton();
  fillInputFieldsFromSession();
  fillValueInputFieldsFromSession();
  selectPensionButton();
});