// js/components/widgets/ApprovalRequestModal.jsx
// Modal pra vendedora PEDIR aprovação de template restrito.
// Criado em 2026-05-05 (sistema 4 onda 4b).
//
// Props:
//   template: objeto do template restrito (com requires_approval=true)
//   selectedClients: array de clientes selecionados (max 25)
//   user: usuário logado
//   onClose: callback fechar
//   onSubmitted: callback após criar pedido (recebe id)
//
// Deps runtime: Modal, sb, toast.
(function() {
  'use strict';
  const {useState} = React;

function ApprovalRequestModal({template, selectedClients, user, onClose, onSubmitted}){
  const[justification,setJustification]=useState('');
  const[loading,setLoading]=useState(false);

  async function submitRequest(){
    if(loading)return;
    if(!template||!selectedClients||selectedClients.length===0){
      toast('⚠ Sem template ou clientes');
      return;
    }
    // [v224.123 NUCLEAR] remove clientes bloqueados do disparo (backend trigger também rejeita)
    const _allowedClients=selectedClients.filter(function(c){return !(window.znxIsClientBlocked&&window.znxIsClientBlocked(c));});
    const _blockedCount=selectedClients.length-_allowedClients.length;
    if(_blockedCount>0)toast('🚫 '+_blockedCount+' cliente(s) bloqueado(s) removido(s) do disparo');
    if(_allowedClients.length===0){toast('⚠ Todos os clientes selecionados estão bloqueados');return;}
    setLoading(true);
    try {
      const{data,error}=await sb.from('template_approval_requests').insert({
        vendedora_name: user?.name || 'sistema',
        vendedora_id: user?.id || null,
        template_id: template.id,
        client_ids: _allowedClients.map(c=>c.id),
        justification: justification.trim() || null
      }).select('id').single();
      if(error)throw error;
      toast('📨 Pedido enviado — aguarde aprovação do admin/financeiro');
      if(onSubmitted)onSubmitted(data?.id);
      onClose();
    } catch(e){
      const msg=e.message||'Erro ao enviar pedido';
      toast('❌ '+msg);
      if(typeof Sentry!=='undefined')Sentry.captureException(e,{extra:{context:'approval_request_submit',templateId:template?.id}});
    } finally {
      setLoading(false);
    }
  }

  return(
    <Modal title="🔒 Pedir aprovação — template restrito" onClose={onClose}>
      <div style={{padding:'4px 0 14px'}}>
        <div style={{background:'#FFFBEB',border:'2px solid #C8A95155',borderRadius:10,padding:'14px 16px',marginBottom:14}}>
          <div style={{display:'flex',gap:14,alignItems:'flex-start'}}>
            <div style={{fontSize:32}}>{template.icon}</div>
            <div style={{flex:1}}>
              <div style={{fontSize:11,color:'#92700A',textTransform:'uppercase',letterSpacing:1,fontWeight:700,marginBottom:3}}>Template selecionado</div>
              <div style={{fontSize:15,fontWeight:700,color:'#1B2A4A',marginBottom:3}}>{template.label}</div>
              <div style={{fontSize:12,color:'#6B7280',marginBottom:8}}>{template.description}</div>
              <div style={{fontSize:12,color:'#374151',background:'#FFFFFF',padding:'8px 12px',borderRadius:6,fontStyle:'italic',lineHeight:1.5,border:'1px solid #C8A95133'}}>"{template.text}"</div>
            </div>
          </div>
        </div>

        <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:10,marginBottom:14}}>
          <div style={{padding:'10px 14px',background:'#F8FAFB',borderRadius:8,border:'1px solid #E5E7EB'}}>
            <div style={{fontSize:11,color:'#6B7280',textTransform:'uppercase',letterSpacing:1,fontWeight:600}}>Clientes alvo</div>
            <div style={{fontSize:20,fontWeight:800,color:'#1B2A4A'}}>{selectedClients.length}</div>
          </div>
          <div style={{padding:'10px 14px',background:'#F8FAFB',borderRadius:8,border:'1px solid #E5E7EB'}}>
            <div style={{fontSize:11,color:'#6B7280',textTransform:'uppercase',letterSpacing:1,fontWeight:600}}>TTL aprovação</div>
            <div style={{fontSize:20,fontWeight:800,color:'#EA580C'}}>48h</div>
          </div>
        </div>

        <div style={{marginBottom:14}}>
          <label style={{fontSize:11,color:'#9CA3AF',textTransform:'uppercase',letterSpacing:1,fontWeight:700,marginBottom:6,display:'block'}}>
            Por que precisa desse template? <span style={{color:'#9CA3AF',fontWeight:500}}>(opcional, mas ajuda na aprovação)</span>
          </label>
          <textarea value={justification} onChange={e=>setJustification(e.target.value)}
            placeholder="Ex: cliente sumiu há 60d, top LTV — vale recuperar com 5% off / frete grátis pq pedido vai compensar / etc"
            style={{width:'100%',minHeight:80,padding:'10px 12px',border:'1px solid #E4E7EC',borderRadius:8,fontSize:13,resize:'vertical',boxSizing:'border-box',lineHeight:1.5}}/>
          <div style={{fontSize:11,color:'#6B7280',marginTop:4}}>{justification.length} caracteres</div>
        </div>

        <div style={{padding:'10px 14px',background:'#FEF3C7',borderRadius:8,fontSize:12,color:'#92700A',lineHeight:1.5,marginBottom:14}}>
          ⚠️ <strong>Importante:</strong> esse template oferece concessão (desconto/frete/brinde) que sai do bolso da empresa. O admin/financeiro precisa aprovar antes de você disparar. Você será notificado pelo sino 🔔 quando receber resposta.
        </div>

        <div style={{display:'flex',gap:10,justifyContent:'flex-end'}}>
          <button className="btn-outline" onClick={onClose} disabled={loading}>Cancelar</button>
          <button className="btn-gold" onClick={submitRequest} disabled={loading}>
            {loading?'Enviando...':'📨 Enviar pedido de aprovação'}
          </button>
        </div>
      </div>
    </Modal>
  );
}

  // Namespace
  window.ZNX = window.ZNX || {};
  window.ZNX.widgets = window.ZNX.widgets || {};
  window.ZNX.widgets.ApprovalRequestModal = ApprovalRequestModal;
  window.ApprovalRequestModal = ApprovalRequestModal;
})();
