(function ($) {
  'use strict';

  function parseNumericId(id) {
    if (typeof id === 'number') {
      return id;
    }

    if (typeof id === 'string') {
      var n = parseInt(id, 10);
      if (!isNaN(n) && n > 0) return n;
      var m = id.match(/(\d+)/);
      return m ? parseInt(m[1], 10) || 0 : 0;
    }

    if (typeof id === 'object' && id) {
      var $o = $(id);
      var attr = ($o.attr('id') || '').toString();
      var mm = attr.match(/(\d+)/);
      return mm ? parseInt(mm[1], 10) || 0 : 0;
    }

    return 0;
  }

  function getRowData(postId) {
    var $tr = $('#post-' + postId);
    if (!$tr.length) return null;
    var $d = $tr.find('.wpsn-qe-data').first();
    if (!$d.length) return null;
    return {
      title: ($d.data('title') || '').toString(),
      description: ($d.data('description') || '').toString(),
      canonical: ($d.data('canonical') || '').toString(),
      robotsIndex: ($d.data('robotsIndex') || '').toString(),
      robotsFollow: ($d.data('robotsFollow') || '').toString(),
      focusKeyword: ($d.data('focusKeyword') || '').toString(),
    };
  }

  function getTermRowData(termId) {
    var $tr = $('#tag-' + termId);
    if (!$tr.length) {
      $tr = $('#term-' + termId);
    }
    if (!$tr.length) return null;
    var $d = $tr.find('.wpsn-qe-data').first();
    if (!$d.length) return null;
    return {
      title: ($d.data('title') || '').toString(),
      description: ($d.data('description') || '').toString(),
      canonical: ($d.data('canonical') || '').toString(),
      robotsIndex: ($d.data('robotsIndex') || '').toString(),
      robotsFollow: ($d.data('robotsFollow') || '').toString(),
      focusKeyword: ($d.data('focusKeyword') || '').toString(),
    };
  }

  function fillQuickEdit(postId) {
    var data = getRowData(postId);
    if (!data) return;

    var $editRow = $('#edit-' + postId);
    if (!$editRow.length) return;

    $editRow.find('input[name="wpsn_seo_title"]').val(data.title);
    $editRow.find('textarea[name="wpsn_seo_description"]').val(data.description);
    $editRow.find('input[name="wpsn_focus_keyword"]').val(data.focusKeyword);
    $editRow.find('input[name="wpsn_canonical"]').val(data.canonical);
    $editRow.find('select[name="wpsn_robots_index"]').val(data.robotsIndex);
    $editRow.find('select[name="wpsn_robots_follow"]').val(data.robotsFollow);
  }

  function fillTermQuickEdit(termId) {
    var data = getTermRowData(termId);
    if (!data) return;

    // WP usually uses #edit-{id} for terms as well, but keep a fallback.
    var $editRow = $('#edit-' + termId);
    if (!$editRow.length) {
      $editRow = $('#inline-edit');
    }
    if (!$editRow.length) return;

    $editRow.find('input[name="wpsn_seo_title"]').val(data.title);
    $editRow.find('textarea[name="wpsn_seo_description"]').val(data.description);
    $editRow.find('input[name="wpsn_focus_keyword"]').val(data.focusKeyword);
    $editRow.find('input[name="wpsn_canonical"]').val(data.canonical);
    $editRow.find('select[name="wpsn_robots_index"]').val(data.robotsIndex);
    $editRow.find('select[name="wpsn_robots_follow"]').val(data.robotsFollow);
  }

  function appendQueuePreserveFields() {
    var cfg = window.WPSN_AdminLists || {};
    var preserve = cfg.queuePreserve || null;
    if (!preserve || typeof preserve !== 'object') return;

    var names = Object.keys(preserve).filter(function (name) {
      return Object.prototype.hasOwnProperty.call(preserve, name) && (preserve[name] || '').toString() !== '';
    });
    if (!names.length) return;

    $('form').each(function () {
      var $form = $(this);

      names.forEach(function (name) {
        if ($form.find('[name="' + name + '"]').length) {
          return;
        }

        $('<input type="hidden" />')
          .attr('name', name)
          .val((preserve[name] || '').toString())
          .appendTo($form);
      });
    });
  }

  $(function () {
    appendQueuePreserveFields();

    // Posts: inlineEditPost
    if (typeof inlineEditPost !== 'undefined' && inlineEditPost.edit) {
      var _edit = inlineEditPost.edit;
      inlineEditPost.edit = function (id) {
        _edit.apply(this, arguments);

        var postId = 0;
        if (typeof id === 'object' && this.getId) {
          postId = parseInt(this.getId(id), 10) || 0;
        } else {
          postId = parseNumericId(id);
        }

        if (!postId) return;
        fillQuickEdit(postId);
      };
    }

    // Terms: inlineEditTax
    if (typeof inlineEditTax !== 'undefined' && inlineEditTax.edit) {
      var _editTax = inlineEditTax.edit;
      inlineEditTax.edit = function (id) {
        _editTax.apply(this, arguments);

        var termId = 0;
        if (typeof id === 'object' && this.getId) {
          termId = parseInt(this.getId(id), 10) || 0;
        } else {
          termId = parseNumericId(id);
        }

        if (!termId) return;
        fillTermQuickEdit(termId);
      };
    }
  });
})(jQuery);
