(function($){
  // Simple modal helpers
  function ensureModal(){
    if($('#trendly-modal-overlay').length){ return; }
    var overlay = $('<div id="trendly-modal-overlay" class="trendly-modal-overlay"/>').hide();
    var modal = $(
      '<div id="trendly-modal" class="trendly-modal" role="dialog" aria-modal="true">' +
        '<div class="trendly-modal-header">' +
          '<span class="trendly-modal-title">Trendly AI</span>' +
          '<button type="button" class="trendly-modal-close" aria-label="Close">×</button>' +
        '</div>' +
        '<div class="trendly-modal-body"><div class="trendly-spinner"></div><p>Processing...</p></div>' +
        '<div class="trendly-modal-footer"><button type="button" class="button trendly-modal-ok">Close</button></div>' +
      '</div>'
    ).hide();
    $('body').append(overlay, modal);
    overlay.on('click', closeModal);
    modal.find('.trendly-modal-close, .trendly-modal-ok').on('click', closeModal);
  }
  function openModal(contentHtml){
    ensureModal();
    if(contentHtml){ $('#trendly-modal .trendly-modal-body').html(contentHtml); }
    $('#trendly-modal-overlay').fadeIn(120);
    $('#trendly-modal').fadeIn(120);
  }
  function updateModal(contentHtml){
    ensureModal();
    $('#trendly-modal .trendly-modal-body').html(contentHtml);
  }
  function closeModal(){
    $('#trendly-modal, #trendly-modal-overlay').fadeOut(120);
  }

  $(document).on('click', '#trendly-test-keys', function(e){
    e.preventDefault();
    openModal('<div class="trendly-spinner"></div><p>Testing API keys...</p>');
    $.post(TrendlyAI.ajaxUrl, { action: 'trendly_test_api_keys', nonce: TrendlyAI.nonce })
      .done(function(resp){
        if(resp && resp.success){
          updateModal('<p>' + (resp.data.configured ? 'API keys are configured.' : 'API keys missing.') + '</p>');
        } else {
          updateModal('<p>Failed to test.</p>');
        }
      }).fail(function(){
        updateModal('<p>Request failed.</p>');
      });
  });

  $(document).on('click', '#trendly-generate-draft', function(e){
    e.preventDefault();
    openModal('<div class="trendly-spinner"></div><p>Generating draft from trends...</p>');
    $.post(TrendlyAI.ajaxUrl, { action: 'trendly_generate_draft', nonce: TrendlyAI.nonce })
      .done(function(resp){
        if(resp && resp.success && resp.data && resp.data.post_id){
          var html = '<p>Draft created.</p>' +
                     '<p><a class="button button-primary" href="' + resp.data.edit_link + '">Edit: ' + $('<div>').text(resp.data.title).html() + '</a></p>';
          updateModal(html);
        } else {
          var msg = (resp && resp.data && resp.data.message) ? resp.data.message : 'Failed to generate draft.';
          updateModal('<p>' + $('<div>').text(msg).html() + '</p>');
        }
      }).fail(function(){
        updateModal('<p>Request failed.</p>');
      });
  });

  // Generate Content page
  $(document).on('click', '#trendly-fetch-trends', function(e){
    e.preventDefault();
    var region = $('#trendly-region').val();
    var $wrap = $('#trendly-topics');
    var $table = $wrap.find('table.trendly-table');
    $table.hide();
    $wrap.find('p.trendly-loading').remove();
    $wrap.append($('<p class="trendly-loading">Loading trending topics...</p>'));
    $.post(TrendlyAI.ajaxUrl, { action: 'trendly_fetch_trends', nonce: TrendlyAI.nonce, region: region }, function(resp){
      if(resp && resp.success && resp.data && resp.data.topics){
        var $tbody = $table.find('tbody');
        $tbody.empty();
        resp.data.topics.forEach(function(topic){
          var $tr = $('<tr/>' );
          var $topic = $('<td/>' ).text(topic);
          var $action = $('<td/>' );
          var $status = $('<td class="trendly-status"/>' );
          var $view = $('<td class="trendly-view"/>' );
          var $btn = $('<button class="button button-primary"/>' ).text('Generate Draft');
          $btn.on('click', function(){
            $btn.prop('disabled', true);
            $status.html('<span class="trendly-spinner"></span> Generating...');
            generateFromTopic(topic, function(success, data){
              if(success){
                $status.html('<span style="color:#2c7;">Success</span>');
                // Also show modal with edit link
                var html = '<p>Draft created for:</p>' +
                           '<p><strong>' + $('<div>').text(topic).html() + '</strong></p>' +
                           '<p><a class="button button-primary" href="' + data.edit_link + '">Edit: ' + $('<div>').text(data.title).html() + '</a></p>';
                updateModal(html);
                if(data && data.post_id){
                  // Prefer preview for drafts, permalink for published
                  var currentStatus = $('#trendly-status').val() || 'draft';
                  var viewLink = (currentStatus === 'publish') ? (data.permalink || data.preview_link || null)
                                                               : (data.preview_link || data.permalink || null);
                  if(!viewLink){
                    // Best-effort: admin-ajax doesn’t know permalink; create an edit link-based preview param if available
                    viewLink = data.edit_link ? data.edit_link.replace('post.php?post=', 'post.php?preview=true&preview_id=') : '';
                  }
                  if(viewLink){
                    $view.html('<a href="' + viewLink + '" target="_blank">View</a>');
                  } else {
                    $view.text('—');
                  }
                }
              } else {
                $status.html('<span style="color:#d63638;">Failed</span>');
                updateModal('<p>Failed to generate draft.</p>');
              }
            });
          });
          $action.append($btn);
          $tr.append($topic, $action, $status, $view);
          $tbody.append($tr);
        });
        $table.show();
      } else {
        $wrap.find('p.trendly-loading').text('Failed to load topics. Please try again.');
      }
    }).fail(function(){
      $wrap.find('p.trendly-loading').text('Request failed. Please try again.');
    });
  });
  // Helper to generate from a selected topic
  function generateFromTopic(topic, cb){
    if(!topic){ if(typeof cb === 'function'){ cb(false); } return; }
    openModal('<div class="trendly-spinner"></div><p>Generating draft...</p>');
    var length = $('#trendly-length').val();
    var images = $('#trendly-images').val();
    var status = $('#trendly-status').val() || 'draft';
    $.post(TrendlyAI.ajaxUrl, { action: 'trendly_generate_from_topic', nonce: TrendlyAI.nonce, topic: topic, length: length, images: images, status: status }, function(resp){
      if(resp && resp.success && resp.data && resp.data.post_id){
        var createdLabel = (status === 'publish') ? 'Post published for:' : 'Draft created for:';
        var html = '<p>' + createdLabel + '</p>' +
                   '<p><strong>' + $('<div>').text(topic).html() + '</strong></p>' +
                   '<p><a class="button button-primary" href="' + resp.data.edit_link + '">Edit: ' + $('<div>').text(resp.data.title).html() + '</a></p>';
        updateModal(html);
        if(typeof cb === 'function'){ cb(true, resp.data); }
      } else {
        var msg = (resp && resp.data && resp.data.message) ? resp.data.message : 'Failed to generate draft.';
        updateModal('<p>' + $('<div>').text(msg).html() + '</p>');
        if(typeof cb === 'function'){ cb(false); }
      }
    }).fail(function(){
      updateModal('<p>Request failed.</p>');
      if(typeof cb === 'function'){ cb(false); }
    });
  }
})(jQuery);
