jQuery(function ($) {

  const backdrop = $('#wp-link-backdrop').clone();
  const modal = $('#o2-link-modal');
  const buttonAdd = modal.find('#o2-link-modal-add');
  const results = modal.find('.o2-link-modal-results');

  const urlInput = $('#o2-link-modal-url', modal);
  const textInput = $('#o2-link-modal-text', modal);
  const targetInput = $('#o2-link-modal-target', modal);


  const cleanModal = () => {
    urlInput.val('');
    textInput.val('');
    $('#o2-link-modal-search', modal).val('');
    targetInput.prop('checked', false);
  }

  const closeModal = () => {
    buttonAdd.off('click');
    backdrop.remove();
    modal.hide();
    cleanModal();
  }

  const openModal = () => {
    updateResults();
    $('body').append(backdrop);
    backdrop.on('click', () => closeModal());
    backdrop.show();
    modal.show();
  }

  const updateField = (el, text, url, target) => {
    $(el).find('.o2-link-field-input-text').val(text).trigger('change');
    $(el).find('.o2-link-field-input-url').val(url);
    $(el).find('.o2-link-field-input-target').val(target);
  }

  const updateResults = (search) => {
    var postData = {
      action: 'o2_get_query_link', // Ação do AJAX para buscar
      s: search,
      query: {
        post_mime_type: 'page', // Filtrar apenas páginas
        posts_per_page: -1 // Retornar todas as páginas (-1 para todas)
      }
    }

    modal.find('.spinner').css('visibility', 'visible');
    wp.ajax.post('o2_get_query_link', postData)
      .done(resp => {
        results.children('ul').html('');
        modal.find('.spinner').css('visibility', 'hidden');

        Array.from(Object.entries(resp)).forEach(([key, link]) => {
          results.children('ul').append(`
            <li>
              <span>${link.title}</span>
              <b>${link.type}</b>
              <input type="hidden" class="url" value="${link.url}">
              <input type="hidden" class="title" value="${link.title}">
            </li>
          `);
        });
      })
      .fail(error => {
        modal.find('.spinner').css('visibility', 'hidden');
      })
  }

  /* buttons que fecham o modal */
  $('.o2-link-modal-close').on('click', () => closeModal());

  /* button que abre o modal */
  $(document).on('click', '.o2-link-field-add', function () {
    buttonAdd.on('click', () => {
      if (urlInput.val() || textInput.val()) {
        const linkField = $(this).closest('.o2-link-field');
        linkField.children('.o2-link-field-unselected').addClass('d-none');
        linkField.children('.o2-link-field-selected').removeClass('d-none');

        linkField.find('.o2-link-field-title').text(textInput.val() || "Sem título");
        linkField.find('.o2-link-field-url').text(urlInput.val());
        linkField.find('.o2-link-field-access').attr('href', urlInput.val());
        updateField(linkField, textInput.val(), urlInput.val(), targetInput.prop('checked') ? '_blank' : '_self');
      }
      closeModal();
    });

    openModal();
  });

  /* editar link */
  $(document).on('click', '.o2-link-field-edit', function () {
    const field = $(this).closest('.o2-link-field');
    textInput.val(field.find('.o2-link-field-title').text());
    urlInput.val(field.find('.o2-link-field-url').text());
    targetInput.prop('checked', field.find('.o2-link-field-input-target').val() === '_blank' ? true : false);
    field.find('.o2-link-field-add').trigger('click');
  });

  /* remove links */
  $(document).on('click', '.o2-link-field-remove', function () {
    const linkField = $(this).closest('.o2-link-field');
    linkField.children('.o2-link-field-unselected').removeClass('d-none');
    linkField.children('.o2-link-field-selected').addClass('d-none');
    updateField(linkField, '', '', '_self');
  });

  /* selected link */
  $(document).on('click', '.o2-link-modal-results ul li', function () {
    const url = $(this).find('.url').val();
    const text = $(this).find('.title').val();

    $(this).siblings('li').removeClass('selected');
    $(this).addClass('selected');
    urlInput.val(url);
    textInput.val(text);
  });

  /* pesquisa modal */
  let timeout;
  $('#o2-link-modal-search').on('keyup', function () {
    clearTimeout(timeout);
    timeout = setTimeout(() => {
      updateResults($(this).val());
    }, 1000);
  });
});