"use strict"; 
jQuery(function ($) {
  $(document).on(
      'change blur',
      'textarea[name="aimogen_allowed_domains"]',
      function () {

          const textarea = $(this);

          $.post(AimogenRemote.ajax_url, {
              action: 'aimogen_save_allowed_domains',
              nonce: AimogenRemote.nonce,
              post_id: textarea.data('id'),
              domains: textarea.val()
          });
      }
  );
  $(document).on('click', '.aimogen-create-remote', function (e) {
    e.preventDefault();
    var $panel = $(this).closest('.aimogen-user-remote-panel');

    $.ajax({
      type: 'POST',
      url: AimogenRemote.ajax_url,
      dataType: 'json',
      data: {
        action: 'aimogen_user_create_remote',
        nonce: AimogenRemote.nonce,
        max: AimogenRemote.max
      }
    }).done(function (res) {
      if (res && res.success) {
        location.reload();
      } else {
        alert((res && res.data) ? res.data : 'Failed to create chatbot.');
      }
    }).fail(function (_, __, error) {
      alert('Error creating chatbot: ' + error);
    });
  });

  $(document).on('click', '.aimogen-delete-remote', function (e) {
    e.preventDefault();
    if (!confirm('Delete this chatbot?')) return;

    var $btn = $(this);
    var postId = $btn.data('id');
    var $panel = $btn.closest('.aimogen-user-remote-panel');

    $.ajax({
      type: 'POST',
      url: AimogenRemote.ajax_url,
      dataType: 'json',
      data: {
        action: 'aimogen_user_delete_remote',
        nonce: AimogenRemote.nonce,
        post_id: postId
      }
    }).done(function (res) {
      if (res && res.success) {
        location.reload();
      } else {
        alert((res && res.data) ? res.data : 'Failed to delete chatbot.');
      }
    }).fail(function (_, __, error) {
      alert('Error deleting chatbot: ' + error);
    });
  });

  $(document).on('click', '.aimogen-regen-remote', function (e) {
    e.preventDefault();
    if (!confirm('Regenerate embed key? Old embeds will stop working.')) return;

    var $btn = $(this);
    var postId = $btn.data('id');
    var $panel = $btn.closest('.aimogen-user-remote-panel');

    $.ajax({
      type: 'POST',
      url: AimogenRemote.ajax_url,
      dataType: 'json',
      data: {
        action: 'aimogen_user_regen_remote',
        nonce: AimogenRemote.nonce,
        post_id: postId
      }
    }).done(function (res) {
      if (res && res.success) {
        location.reload();
      } else {
        alert((res && res.data) ? res.data : 'Failed to regenerate key.');
      }
    }).fail(function (_, __, error) {
      alert('Error regenerating key: ' + error);
    });
  });
});