// Simple Approval Queue Admin UI (WP Admin Builder page)
(function($){
  function renderItems(items){
    const $list = $('#vmo-approval-list');
    if (!$list.length) return;
    $list.empty();
    if (!items || !items.length) { $list.append('<li>No pending items.</li>'); return; }
    items.forEach(it=>{
      const payload = (typeof it.payload === 'string') ? it.payload : JSON.stringify(it.payload);
      const row = $(`
        <li data-id="${it.id}">
          <strong>[${it.type}]</strong> ${it.title || '(untitled)'}
          <pre style="white-space:pre-wrap;background:#0c1a2b;color:#cde;padding:8px;border-radius:6px;">${$('<div>').text(payload).html()}</pre>
          <div>
            <button class="button button-primary vmo-approve">Approve</button>
            <button class="button vmo-reject">Reject</button>
          </div>
        </li>`);
      $list.append(row);
    });
  }

  function loadQueue(){
    $.get({
      url: vmo_ajax.ajaxurl,
      data: { action:'vmo_queue_list', security: vmo_ajax.nonce, status:'pending' }
    }).done(res=>{ if(res.success) renderItems(res.data.items); });
  }

  $(document).on('click','.vmo-approve',function(){
    const id = $(this).closest('li').data('id');
    $.post(vmo_ajax.ajaxurl,{ action:'vmo_queue_approve', security:vmo_ajax.nonce, id })
      .done(()=> loadQueue());
  });
  $(document).on('click','.vmo-reject',function(){
    const id = $(this).closest('li').data('id');
    $.post(vmo_ajax.ajaxurl,{ action:'vmo_queue_reject', security:vmo_ajax.nonce, id })
      .done(()=> loadQueue());
  });

  // Auto-load on dashboard template
  $(function(){
    if ($('#vmo-approval-list').length) loadQueue();
  });

  // Global readiness check helper used by generation calls
  // 🔧 FIX: Properly block generation when consultation not ready
  window.vmoEnsureConsultationReady = function(onReady){
    // Check if this is a refinement operation (has existing content)
    const hasExistingContent = window.vmoState && window.vmoState.blocks && window.vmoState.blocks.length > 0;
    
    if (hasExistingContent) {
      // For refinements, bypass consultation requirement
      console.log('[VMO] Refinement operation detected - bypassing consultation requirement');
      if (typeof onReady === 'function') onReady();
      return true;
    }
    
    // For new content generation, check consultation status
    $.post(vmo_ajax.ajaxurl, { action:'vmo_get_consultation_status', security:vmo_ajax.nonce })
      .done(res=>{
        if (res.success && res.data.ready) { 
          console.log('[VMO] Consultation ready - proceeding with generation');
          if (typeof onReady==='function') onReady(); 
          return true; 
        }
        
        // Consultation not ready - BLOCK generation completely
        console.log('[VMO] Consultation not ready - blocking generation');
        if (window.showToast) {
          window.showToast('⚠️ Please complete the Business Consultation first to generate new content.', 'warning');
        } else {
          alert('Please complete the Business Consultation first to generate new content.');
        }
        
        // Try to open wizard if available (v9.0 intelligent consultation or v8.x legacy)
        if (window.VMOIntelligentConsultation?.prototype?.openBusinessWizard) {
          try { (new VMOIntelligentConsultation()).openBusinessWizard(); } catch(e){}
        } else if (window.VMOConversationalAI?.prototype?.openBusinessWizard) {
          try { (new VMOConversationalAI()).openBusinessWizard(); } catch(e){}
        }
        
        // Return false and DO NOT call onReady callback
        return false;
      })
      .fail(err => {
        console.error('[VMO] Consultation status check failed:', err);
        if (window.showToast) {
          window.showToast('⚠️ Unable to verify consultation status. Please complete Business Consultation.', 'error');
        }
        // DO NOT call onReady on failure
        return false;
      });
    
    // Return false immediately for new content without consultation
    return false;
  };
})(jQuery);
