$(function () {
  $('.genealogy-tree ul').hide();
  $('.genealogy-tree > ul').show();

  $('.genealogy-tree li').each(function () {
    if ($(this).children('ul').length > 0) {
      $(this).addClass('has-children');
      if (!$(this).children('.toggle-icon').length) {
        
      }
    } else {
      $(this).addClass('no-children');
    }
  });

  $('.genealogy-tree').on('click', '.has-children > .toggle-icon', function (e) {
    const $li = $(this).closest('li');
    const $children = $li.children('ul');
    const isVisible = $children.is(':visible');

    if (isVisible) {
      $children.slideUp('fast');
      $(this).text('+');
    } else {
      $children.slideDown('fast');
      $(this).text('−');
    }

    e.stopPropagation();
  });
});


// Add user prompt
function openAddUserForm(parentId, side) {
    const name = prompt("Enter new user name:");
    if (name) {
        $.post('php/add_member.php', {
            parent_id: parentId,
            name: name,
            side: side
        }, function (response) {
            alert(response);
            location.reload(); // Reload tree
        });
    }
}
