/* global fixlinksData */
jQuery(document).ready(function ($) {
  'use strict';
  var ajaxUrl = fixlinksData.ajax_url, nonce = fixlinksData.nonce, pollInterval = null;

  function spin($b, t) { $b.prop('disabled', true).html('<span class="fixlinks-spinner"></span>' + (t || '…')); }
  function restore($b, t) { $b.prop('disabled', false).text(t); }

  // Run Crawl
  $('#fixlinks-run-crawl').on('click', function () {
    var $btn = $(this);
    spin($btn, 'Starting…');
    $.post(ajaxUrl, { action: 'fixlinks_run_crawl', nonce: nonce }, function (res) {
      if (res.success) {
        if (res.data.status === 'running') {
          if (!$('#fixlinks-progress-wrap').length) {
            $('<div class="fixlinks-progress-wrap" id="fixlinks-progress-wrap">'
              + '<strong style="font-size:13px">Crawl in progress…</strong>'
              + '<div style="background:#E5E7EB;border-radius:99px;height:8px;margin-top:8px;overflow:hidden">'
              + '<div id="fixlinks-progress-bar" style="background:#4F46E5;height:8px;border-radius:99px;width:0%;transition:width .4s"></div></div>'
              + '<p id="fixlinks-progress-text" style="font-size:12px;color:#888;margin-top:4px">Starting…</p></div>'
            ).insertBefore('.fixlinks-table');
          }
          startPolling();
          restore($btn, 'Run Crawl Now');
        } else {
          alert('Crawl complete! Found ' + (res.data.found || 0) + ' broken links.');
          location.reload();
        }
      } else {
        alert('Error: ' + res.data);
        restore($btn, 'Run Crawl Now');
      }
    }).fail(function () {
      alert('Network error.');
      restore($btn, 'Run Crawl Now');
    });
  });

  if ($('#fixlinks-progress-wrap').length) startPolling();

  function startPolling() {
    if (pollInterval) return;
    pollInterval = setInterval(function () {
      $.post(ajaxUrl, { action: 'fixlinks_crawl_progress', nonce: nonce }, function (res) {
        if (!res.success) return;
        var d = res.data;
        $('#fixlinks-progress-bar').css('width', d.percent + '%');
        $('#fixlinks-progress-text').text(d.done + '/' + d.total + ' URLs checked');
        if (d.status === 'complete' || d.status === 'idle') {
          clearInterval(pollInterval);
          pollInterval = null;
          setTimeout(function () { location.reload(); }, 800);
        }
      });
    }, 3000);
  }

  // Get AI suggestion
  $(document).on('click', '.fixlinks-get-suggestion', function () {
    var $btn = $(this), id = $btn.data('id'), url = $btn.data('url');
    spin($btn, 'Asking AI…');
    $.post(ajaxUrl, { action: 'fixlinks_get_suggestion', nonce: nonce, link_id: id, broken_url: url }, function (res) {
      if (res.success) {
        var d = res.data, cc = d.confidence === 'high' ? 'high' : (d.confidence === 'medium' ? 'medium' : 'low');
        $('.fixlinks-suggestion-cell-' + id).html(
          '<input type="text" class="fixlinks-redirect-input" value="' + (d.suggestion || '') + '" /><br>'
          + '<span class="fixlinks-confidence ' + cc + '">' + d.confidence + '</span>'
          + ' <button class="button button-primary button-small fixlinks-apply" data-id="' + id + '" data-from="' + url + '">Apply 301</button>'
        );
      } else {
        alert('Error: ' + res.data);
        restore($btn, 'Get AI suggestion');
      }
    }).fail(function (xhr) {
      if (xhr.status === 429) {
        var d = JSON.parse(xhr.responseText || '{}');
        alert('Rate limit reached. Resets in ' + Math.ceil((d.retry_after || 3600) / 60) + ' min.');
      } else {
        alert('Network error.');
      }
      restore($btn, 'Get AI suggestion');
    });
  });

  // Apply redirect
  $(document).on('click', '.fixlinks-apply', function () {
    var $btn = $(this), id = $btn.data('id'), fromUrl = $btn.data('from');
    var toUrl = $btn.closest('tr').find('.fixlinks-redirect-input').val().trim();
    if (!toUrl) { alert('Enter a redirect destination first.'); return; }
    spin($btn, 'Saving…');
    $.post(ajaxUrl, { action: 'fixlinks_apply_redirect', nonce: nonce, link_id: id, from_url: fromUrl, to_url: toUrl }, function (res) {
      if (res.success) {
        var fixed = res.data && res.data.fixed_posts ? res.data.fixed_posts : 0;
        var note  = fixed > 0 ? ' <em style="font-size:11px;color:#6B7280">(' + fixed + ' post' + (fixed > 1 ? 's' : '') + ' updated)</em>' : '';
        // Clear suggestion cell (removes spinner if button was inside it)
        $('.fixlinks-suggestion-cell-' + id).html('<span style="color:#6B7280;font-size:12px">→ ' + $('<span>').text(toUrl).html() + '</span>');
        // Update action cell
        $('#fixlinks-row-' + id).find('td:last').html(
          '<span class="fixlinks-applied">✓ Applied</span>' + note + '<br>'
          + '<button class="button button-small fixlinks-rollback" data-from="' + fromUrl + '">Undo</button>'
        );
      } else {
        alert('Could not save redirect. Please try again.');
        restore($btn, 'Apply 301');
      }
    }).fail(function () {
      alert('Something went wrong. Please try again.');
      restore($btn, 'Apply 301');
    });
  });

  // Rollback
  $(document).on('click', '.fixlinks-rollback', function () {
    if (!window.confirm('Remove this redirect?')) return;
    var fromUrl = $(this).data('from');
    $.post(ajaxUrl, { action: 'fixlinks_rollback_redirect', nonce: nonce, from_url: fromUrl }, function (res) {
      if (res.success) {
        var reverted = res.data && res.data.reverted ? res.data.reverted : 0;
        if (reverted > 0) {
          alert('Redirect removed. ' + reverted + ' post' + (reverted > 1 ? 's' : '') + ' reverted to original link.');
        }
        location.reload();
      } else {
        alert('Could not remove redirect. Please try again.');
      }
    }).fail(function () {
      alert('Something went wrong. Please try again.');
    });
  });

  // Bulk get AI suggestions
  $('#fixlinks-bulk-suggest').on('click', function () {
    var $btn = $(this);
    var $pending = $('.fixlinks-get-suggestion');
    if (!$pending.length) { alert('No pending links to get suggestions for.'); return; }
    if (!window.confirm('Get AI suggestions for ' + $pending.length + ' link(s)? This may take a moment.')) return;
    spin($btn, 'Getting suggestions…');
    var buttons = $pending.toArray();
    var index = 0;
    var errors = 0;
    function processNext() {
      if (index >= buttons.length) {
        restore($btn, '✨ Bulk Get Suggestions');
        if (errors > 0) {
          alert('Done! ' + (buttons.length - errors) + ' suggestions fetched. ' + errors + ' failed (rate limit or error).');
        }
        return;
      }
      var $b = $(buttons[index]);
      index++;
      $btn.html('<span class="fixlinks-spinner"></span>Getting ' + index + '/' + buttons.length + '…').prop('disabled', true);
      $b.trigger('click');
      // Wait 2s between calls to avoid rate limits
      setTimeout(processNext, 2000);
    }
    processNext();
  });

  // Bulk apply
  $('#fixlinks-bulk-apply').on('click', function () {
    if (!window.confirm('Apply all AI suggestions?')) return;
    $('.fixlinks-apply').each(function () { $(this).trigger('click'); });
  });

  // Save settings
  $('#fixlinks-save-settings').on('click', function () {
    var $btn = $(this), key = $('#fixlinks_license_key').val().trim();
    spin($btn, 'Activating…');
    $.post(ajaxUrl, { action: 'fixlinks_save_settings', nonce: nonce, license_key: key }, function (res) {
      if (res.success) {
        alert('✓ ' + res.data.message);
        location.reload();
      } else {
        alert('Could not activate license. Please try again.');
        restore($btn, 'Activate License');
      }
    }).fail(function () {
      alert('Something went wrong. Please try again.');
      restore($btn, 'Activate License');
    });
  });
});