jQuery(function($){
  function showStatusMessage(message,type){
    $('#wpaicg-status-message').text(message).removeClass('error success').addClass(type);
  }
  function toggleSpinner(sel,show){
    const $btn=$(sel);
    show?$btn.prop('disabled',true).append(' <span class="spinner is-active"></span>'):$btn.prop('disabled',false).find('.spinner').remove();
  }
  $('#wpaicg-title-generator-form').on('submit',function(e){
    e.preventDefault(); const kws=$('#wpaicg-keywords').val().trim(); if(!kws)return alert('Please enter some keywords.');
    toggleSpinner('#wpaicg-generate-titles-btn',true);
    $.post(wpaicg_ajax_obj.ajax_url,{action:'wpaicg_generate_titles',nonce:wpaicg_ajax_obj.nonce,keywords:kws})
    .done(function(r){if(r.success){let html='<ul>';r.data.titles.forEach(t=>html+=`<li><label><input type="checkbox" value="${t}"> ${t}</label></li>`);html+='</ul>';$('#wpaicg-title-results').html(html);$('#wpaicg-post-generator-section').show();}else showStatusMessage('Error: '+r.data.message,'error');})
    .fail((xhr,s)=>showStatusMessage('AJAX error — '+s+' / '+xhr.responseText,'error'))
    .always(()=>toggleSpinner('#wpaicg-generate-titles-btn',false));
  });
  $('#wpaicg-generate-posts-btn').on('click',function(e){
    e.preventDefault();const sel=$('#wpaicg-title-results input:checked').map(function(){return this.value;}).get();if(!sel.length)return alert('Select at least one title.');
    toggleSpinner('#wpaicg-generate-posts-btn',true);
    $.post(wpaicg_ajax_obj.ajax_url,{action:'wpaicg_generate_posts',nonce:wpaicg_ajax_obj.nonce,titles:JSON.stringify(sel)})
    .done(r=>r.success?showStatusMessage(r.data.message,'success'):showStatusMessage('Error: '+r.data.message,'error'))
    .fail((xhr,s)=>showStatusMessage('AJAX error — '+s+' / '+xhr.responseText,'error'))
    .always(()=>toggleSpinner('#wpaicg-generate-posts-btn',false));
  });
});