// js/components/widgets/clientes/BlockClientModal.jsx
// [v224.123 NUCLEAR] Admin bloqueia/desbloqueia cliente. Chama RPC toggle_client_blocked_v1
// (SECDEF, gate znx_role='admin'). Padrão window.Modal + title/onClose. Idempotency via
// crypto.randomUUID (p_idem_key direto na RPC). Optimistic setClients (realtime do store
// também atualiza, mas instantâneo aqui). Guard double-click (inFlight ref).
(function(){
  'use strict';
  var useState = React.useState, useRef = React.useRef;

  function BlockClientModal(props){
    var client = props.client;
    var onClose = props.onClose || function(){};
    var setClients = props.setClients || function(){};

    var Modal = window.Modal;
    if (!Modal) {
      if (window.Sentry && typeof window.Sentry.captureMessage === 'function') {
        try { window.Sentry.captureMessage('[v224.123] BlockClientModal missing Modal', 'error'); } catch(e){}
      }
      console.error('[BlockClientModal] Modal faltando');
      return null;
    }
    if (!client) return null;

    var toast = (typeof window.toast === 'function') ? window.toast : function(m){ console.log('[toast]', m); };
    var isBlocked = (typeof window.znxIsClientBlocked === 'function')
      ? window.znxIsClientBlocked(client)
      : (client.blocked_at != null);
    var willBlock = !isBlocked;
    var curReason = (typeof window.znxClientBlockedReason === 'function') ? window.znxClientBlockedReason(client) : '';

    var _r = useState('');
    var reason = _r[0], setReason = _r[1];
    var _s = useState(false);
    var saving = _s[0], setSaving = _s[1];
    var inFlight = useRef(false);

    function handleConfirm(){
      if (inFlight.current) return;
      if (willBlock && reason.trim().length < 5) { toast('⚠ Motivo obrigatório (mín 5 caracteres) ao bloquear'); return; }
      if (!window.sb || typeof window.sb.rpc !== 'function') { toast('❌ Conexão indisponível'); return; }
      inFlight.current = true; setSaving(true);
      var idemKey = (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') ? crypto.randomUUID() : null;
      window.sb.rpc('toggle_client_blocked_v1', {
        p_client_id: client.id,
        p_block: willBlock,
        p_reason: willBlock ? reason.trim() : null,
        p_idem_key: idemKey
      }).then(function(res){
        var error = res && res.error;
        if (error) {
          toast('❌ ' + (error.message || 'Erro ao bloquear'));
          if (window.Sentry) { try { window.Sentry.captureException(new Error(error.message), { tags:{ wave:'v224.123', op:'toggle_client_blocked' }, extra:{ clientId: client.id, willBlock: willBlock } }); } catch(_){} }
          return;
        }
        var nowIso = willBlock ? new Date().toISOString() : null;
        var newReason = willBlock ? reason.trim() : null;
        setClients(function(prev){
          return (prev || []).map(function(c){
            return c.id === client.id
              ? Object.assign({}, c, { blocked_at: nowIso, blocked_reason: newReason, blockedAt: nowIso, blockedReason: newReason })
              : c;
          });
        });
        toast(willBlock ? '🚫 Cliente bloqueado' : '✅ Cliente desbloqueado');
        onClose();
      }).catch(function(e){
        toast('❌ ' + ((e && e.message) || 'Erro'));
        if (window.Sentry) { try { window.Sentry.captureException(e, { tags:{ wave:'v224.123' }, extra:{ clientId: client.id } }); } catch(_){} }
      }).then(function(){
        inFlight.current = false; setSaving(false);
      });
    }

    return (
      <Modal title={(willBlock ? '🚫 Bloquear' : '✅ Desbloquear') + ' — ' + client.name} onClose={onClose}>
        <div style={{display:'flex',flexDirection:'column',gap:14}}>
          <div style={{fontSize:13,color:'#374151',lineHeight:1.5}}>
            {willBlock
              ? 'Bloquear impede criar vendas, orçamentos e contas a receber para este cliente. Apenas administradores podem editar o histórico dele.'
              : 'Desbloquear volta a permitir operações normais com este cliente.'}
          </div>
          {willBlock && (
            <div className="form-group">
              <label>Motivo do bloqueio (obrigatório, mín 5 caracteres)</label>
              <input type="text" value={reason} onChange={function(e){ setReason(e.target.value); }} autoFocus
                placeholder="Ex: inadimplência reincidente, golpe, pedido de exclusão"/>
            </div>
          )}
          {!willBlock && curReason && (
            <div style={{fontSize:12,color:'#6B7280',background:'#F9FAFB',borderRadius:8,padding:'10px 12px'}}>
              Motivo atual do bloqueio: {curReason}
            </div>
          )}
          <div style={{display:'flex',gap:10,justifyContent:'flex-end'}}>
            <button className="btn-outline" onClick={onClose} disabled={saving}>Cancelar</button>
            <button className={willBlock ? 'btn-danger' : 'btn-gold'} onClick={handleConfirm} disabled={saving}>
              {saving ? '⏳ Processando...' : (willBlock ? '🚫 Bloquear cliente' : '✅ Desbloquear')}
            </button>
          </div>
        </div>
      </Modal>
    );
  }

  window.ZNX = window.ZNX || {};
  window.ZNX.widgets = window.ZNX.widgets || {};
  window.ZNX.widgets.clientes = window.ZNX.widgets.clientes || {};
  window.ZNX.widgets.clientes.BlockClientModal = BlockClientModal;
})();
