// js/components/widgets/campaign-modal/CampaignStepQueue.jsx
// [Wave 40 v224.21 NUCLEAR EXTRACT 2026-05-24] Step 2: queue (cliente atual + textarea + actions)
// Extract LITERAL CampaignModal L277-340
//
// Props:
//   - currentIdx, filteredClients, currentClient (state machine cursor)
//   - messageOverride, setMessageOverride — textarea state controlado pelo main
//   - health (Map|null), phone (string|null), loading (bool)
//   - onBack — back handler
//   - onSkip — registerSkipped handler com reason interna do main
//   - onMarkSent — markSentAndNext RPC handler (preserved LITERAL no main · BUG-FIX 20260506)
//   - onClose — close modal
//   - onForceDone — confirma close mid-queue → step done
//   - results (array), sentToday, MAX
//
// Deps lazy: window.Modal, window.toast
(function(){
  'use strict';
  function CampaignStepQueue(props){
    const Modal = window.Modal;
    const toast = window.toast;
    if(!Modal){
      console.error('[CampaignStepQueue] window.Modal ausente');
      return null;
    }
    const {
      currentIdx, filteredClients, currentClient,
      messageOverride, setMessageOverride,
      health, phone, loading,
      onBack, onSkip, onMarkSent, onClose, onForceDone,
      results, sentToday, MAX
    } = props;
    const progress = Math.round((currentIdx / filteredClients.length) * 100);
    return (
      <Modal title={'📱 Campanha — '+(currentIdx+1)+' de '+filteredClients.length} onClose={function(){
        if(window.confirm('Tem certeza? Você já enviou pra '+results.length+' cliente(s). Os restantes serão descartados.')){
          onForceDone();
        }
      }} large>
        {/* Progress bar */}
        <div style={{height:6,background:'#F3F4F6',borderRadius:3,overflow:'hidden',marginBottom:14}}>
          <div style={{width:progress+'%',height:'100%',background:'#C8A951',transition:'width .3s'}}/>
        </div>

        {/* Cliente atual */}
        <div style={{background:'#F8FAFB',border:'1px solid #E5E7EB',borderRadius:10,padding:'14px 16px',marginBottom:14}}>
          <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:6}}>
            <div>
              <div style={{fontSize:11,color:'#9CA3AF',textTransform:'uppercase',letterSpacing:1,fontWeight:700}}>Cliente atual</div>
              <div style={{fontSize:18,fontWeight:700,color:'#1B2A4A'}}>{currentClient.name}</div>
              <div style={{fontSize:12,color:'#6B7280',marginTop:2}}>
                {currentClient.type||'PF'} · {currentClient.city||'—'}/{currentClient.state||'—'} · 📱 {currentClient.whatsapp||currentClient.phone||'sem telefone'}
                {!phone && <span style={{color:'#DC2626',fontWeight:700,marginLeft:6}}>⚠ telefone inválido</span>}
              </div>
            </div>
            {health && health.get && health.get(currentClient.id) && (function(){
              const h = health.get(currentClient.id);
              return <div style={{padding:'4px 10px',borderRadius:8,background:h.color+'20',color:h.color,fontWeight:700,fontSize:12}}>{h.emoji} {h.score}</div>;
            })()}
          </div>
        </div>

        {/* Mensagem editável */}
        <div style={{marginBottom:14}}>
          <label style={{fontSize:11,color:'#9CA3AF',textTransform:'uppercase',letterSpacing:1,fontWeight:700,marginBottom:6,display:'block'}}>
            Mensagem (você pode ajustar antes de enviar)
          </label>
          <textarea value={messageOverride} onChange={function(e){setMessageOverride(e.target.value);}}
            style={{width:'100%',minHeight:120,padding:'12px 14px',border:'1px solid #E4E7EC',borderRadius:8,fontSize:13,resize:'vertical',boxSizing:'border-box',lineHeight:1.5}}/>
          <div style={{fontSize:11,color:'#6B7280',marginTop:4}}>{messageOverride.length} caracteres</div>
        </div>

        {/* Ações */}
        <div style={{display:'flex',gap:10,justifyContent:'space-between',alignItems:'center'}}>
          <button className="btn-outline btn-sm" onClick={onBack} disabled={currentIdx===0}>← Anterior</button>
          <div style={{display:'flex',gap:8}}>
            <button className="btn-outline" onClick={onSkip} disabled={loading}>⏭ Pular</button>
            <a className="btn-outline" href={phone ? 'https://wa.me/'+phone+'?text='+encodeURIComponent(messageOverride) : '#'}
              target="_blank" rel="noopener"
              onClick={function(e){ if(!phone){ e.preventDefault(); toast && toast('⚠ Cliente sem telefone'); } }}
              style={{borderColor:'#25D366',color:'#25D366',textDecoration:'none',padding:'7px 14px',fontWeight:700}}>
              📱 Abrir WhatsApp
            </a>
            <button className="btn-gold" onClick={onMarkSent} disabled={loading||!phone}>
              {loading ? '...' : '✓ Marcar enviado + próximo'}
            </button>
          </div>
        </div>

        <div style={{fontSize:11,color:'#9CA3AF',textAlign:'center',marginTop:12}}>
          Já processados: {results.length} · Restantes: {filteredClients.length-currentIdx-1} · Limite hoje: {sentToday+results.length}/{MAX}
        </div>
      </Modal>
    );
  }
  window.ZNX = window.ZNX || {};
  window.ZNX.widgets = window.ZNX.widgets || {};
  window.ZNX.widgets['campaign-modal'] = window.ZNX.widgets['campaign-modal'] || {};
  window.ZNX.widgets['campaign-modal'].CampaignStepQueue = CampaignStepQueue;
  // [Wave 40 marker v224.21] confirma CampaignStepQueue executado
  window.CampaignStepQueue_v224_21_wave40 = true;
})();
