"use strict";
(function () {
  const
    control_automaticSelectionDiv = document.getElementById("AutomaticSelectionDiv"),
    control_chooseNotaryForm = document.getElementById("ChooseNotaryForm"),
    control_finishButton = document.getElementById("FinishButton"),
    control_manualSelectionDiv = document.getElementById("ManualSelectionDiv"),
    control_selectedIsManualSelection = document.querySelector("input[name='IsManualSelection']:checked"),
    control_selectedLawyer_UID = document.getElementById("SelectedLawyer_UID"),
    control_selectionRadioButtons = document.getElementsByName("IsManualSelection"),
    control_selectLawyerButtons = document.querySelectorAll(".availablelawyer__select__button");

  function _bindEvents() {
    control_selectLawyerButtons?.forEach(btn => {
      btn.addEventListener("click", _selectLawyer);
    });

    control_selectionRadioButtons.forEach(radio => {
      radio.addEventListener("change", _radioOptionChanged)
    });
  }

  function _init() {
    _bindEvents();
    _showHideManualSelection(control_selectedIsManualSelection.value === "true");
  }

  function _radioOptionChanged(sender) {
    let isManualSelection = sender?.target?.value ?? "true";
    _showHideManualSelection(isManualSelection === "true");
  }

  function _selectLawyer(e) {
    let btn = e.target.closest("button");
    let tr = btn.closest("tr");
    tr.classList.add("table-primary");
    jfa.components.dialog.confirm({
      title: "Choose this notary public?",
      message: "Are you sure you want to choose this notary public?",
      callbackyes: function () {
        control_selectedLawyer_UID.value = btn.dataset.uid;

        const urlObj = new URL(control_chooseNotaryForm.action);
        urlObj.search = '';
        control_chooseNotaryForm.action = urlObj.toString();
        control_chooseNotaryForm.submit();
      },
      yesLabel: "Choose"
    });
  }

  function _showHideManualSelection(isManualSelection) {
    if (isManualSelection) {
      jfa.utilities.element.show(control_manualSelectionDiv);
      jfa.utilities.element.hide(control_automaticSelectionDiv);
      jfa.utilities.element.disable(control_finishButton);
    }
    else {
      jfa.utilities.element.hide(control_manualSelectionDiv);
      jfa.utilities.element.show(control_automaticSelectionDiv);
      jfa.utilities.element.enable(control_finishButton);
    }
  }

  _init();
})();