jQuery(function ($) {
  /* Abrir edição */
  $(document).on("click", ".o2-svg-field-add", function () {
    const field = $(this).closest(".o2-svg-field");
    $(field).children().addClass("d-none");
    $(".o2-svg-field-edit", field).removeClass("d-none");
  });

  /* Salvar edição */
  $(document).on("click", ".o2-svg-field-salvar", function () {
    const field = $(this).closest(".o2-svg-field");
    const textarea = field.find(".o2-svg-field-textarea");
    $(field).children().addClass("d-none");
    if (textarea.val()) {
      $(".o2-svg-field-render", field).html(textarea.val());
      field.children("input").val(textarea.val());
      $('.o2-svg-field-selected', field).removeClass("d-none");
      textarea.val("");
    } else {
      $(".o2-svg-field-unselected", field).removeClass("d-none");
    }
  });

  /* Cancelar edição */
  $(document).on("click", ".o2-svg-field-cancelar", function () {
    const field = $(this).closest(".o2-svg-field");
    const textarea = $(".o2-svg-field-textarea", field);
    $(field).children().addClass("d-none");
    if (textarea.val())
      $(".o2-svg-field-selected", field).removeClass("d-none");
    else
      $(".o2-svg-field-unselected", field).removeClass("d-none");
    textarea.val("");
  });

  /* Editar svg */
  $(document).on("click", ".o2-svg-field-editar", function () {
    const field = $(this).closest(".o2-svg-field");
    const textarea = $('.o2-svg-field-textarea', field);
    $(field).children().addClass("d-none");
    textarea.val(field.children('input').val());
    $('.o2-svg-field-edit', field).removeClass("d-none");
    textarea.select();
  });

  /* Remover */
  $(document).on('click', '.o2-svg-field-remover', function () {
    const field = $(this).closest(".o2-svg-field");
    if (!confirm('Confirma exclusão do svg?')) return false;
    field.children().addClass("d-none");
    field.children('input').val("");
    $('.o2-svg-field-unselected', field).removeClass("d-none");
  });
});
