// js/components/widgets/Pagamentos.jsx
// Registro de pagamentos recebidos — associados a vendas ou avulsos.
// Movido de index.html em Fase 5 do refactor (2026-04-29): L6682-L6853
// [Wave 34 v224.15 NUCLEAR EXTRACT 2026-05-24] 287L -> ~180L (-37%) · 9ª replicação NUCLEAR
// Extract: 1 lib + 4 widgets · padrão Wave 32 Compras (RPC-heavy híbrido) + JSX extractable
// Handlers save/remove/togglePago PRESERVADOS LITERAL byte-a-byte (audit log + idempotency per-row)
//
// Deps runtime: Modal, Icon, StatusBadge, SmartSelect, showConfirm, fmt, fmtDate, dualWrite, genIdUUID,
//               today, toast, znxGuard, sb (globals) + PAGAMENTO_TYPES + PAGAMENTO_COLORS (index.html L571-572)
// Deps Wave 34: ZNX.lib.pagamentos.calcs + ZNX.widgets.pagamentos.{PagamentosHeader, PagamentosStatsCards,
//               PagamentosTable, PagamentoFormModal}
(function() {
  'use strict';
  const {useState, useEffect, useRef, useMemo} = React;

let _inFlightDeletePagamento=false;

// [Wave 34 v224.15 + v224.54 2026-05-28] vars+check MOVED to component body
// regra_validacao_helpers_runtime_quando_ordem_scripts_uncertain (ERP-5G false positive · Babel transpile race)

function Pagamentos({pagamentos,setPagamentos}){
  // [v224.54 FIX-5G 2026-05-28] vars+check em render time · garante registry completo
  const pgmW = (window.ZNX && window.ZNX.widgets && window.ZNX.widgets.pagamentos) || {};
  const pgmCalcs = window.ZNX && window.ZNX.lib && window.ZNX.lib.pagamentos && window.ZNX.lib.pagamentos.calcs;
  if(!pgmCalcs || !pgmW.PagamentosHeader || !pgmW.PagamentosStatsCards || !pgmW.PagamentosTable || !pgmW.PagamentoFormModal){
    const _msg = '[Pagamentos v224.15 wave34] deps faltando: calcs='+!!pgmCalcs+', PagamentosHeader='+!!pgmW.PagamentosHeader+', PagamentosStatsCards='+!!pgmW.PagamentosStatsCards+', PagamentosTable='+!!pgmW.PagamentosTable+', PagamentoFormModal='+!!pgmW.PagamentoFormModal;
    console.error(_msg);
    if(window.Sentry && typeof window.Sentry.captureMessage === 'function') window.Sentry.captureMessage(_msg, 'error');
  }
  const[modal,setModal]=useState(null);
  const[form,setForm]=useState({recipient:'',type:'Fornecedor',value:'',date:today(),reference:'',status:'Pendente',notes:''});
  const[filter,setFilter]=useState({month:today().slice(0,7),type:'',status:''});
  const[editId,setEditId]=useState(null);
  // [v128 LOADING-STATE 2026-05-11] regra_loading_state_obrigatorio — combate duplo-click no save() e togglePago()
  const savingRef = useRef(false);
  useEffect(() => { savingRef.current = false; }, [modal]);
  const togglePagoInflightRef = useRef(new Set());
  const [togglePagoVer, setTogglePagoVer] = useState(0);

  // [Wave 34 v224.15] 3 useMemo via lib (filtered + porTipo + totals)
  const filtered = useMemo(()=>pgmCalcs.filterPagamentos(pagamentos, filter), [pagamentos, filter]);
  const porTipo = useMemo(()=>pgmCalcs.aggregateByType(filtered), [filtered]);
  const totals = useMemo(()=>pgmCalcs.calcTotals(filtered), [filtered]);

  function openNew(){setForm({recipient:'',type:'Fornecedor',value:'',date:today(),reference:'',status:'Pendente',notes:''});setEditId(null);setModal('form');}
  function openEdit(p){setForm({...p,value:String(p.value)});setEditId(p.id);setModal('form');}
  async function save(){
    // [v128 LOADING-STATE 2026-05-11] regra_loading_state_obrigatorio — anti duplo-click
    if(savingRef.current)return;
    if(!form.value){toast('Informe o valor');return;}
    savingRef.current=true;
    try {
      const isNew=!editId;
      const id=isNew?genIdUUID():editId;
      const entry={...form,value:Number(form.value)};
      const ok=await dualWrite('pagamentos',id,
        {recipient:entry.recipient||null,type:entry.type,value:entry.value,
         date:entry.date,reference:entry.reference||null,status:entry.status,
         notes:entry.notes||null},
        isNew,()=>{
          if(!isNew){setPagamentos(prev=>prev.map(p=>p.id===id?{...entry,id}:p));}
          else{setPagamentos(prev=>[...prev,{...entry,id}]);}
        });
      if(!ok){savingRef.current=false;return;}
      setModal(null);
    } catch(e) {
      savingRef.current=false;
      const msg=e.message||'Erro inesperado. Tente novamente.';
      toast('❌ '+msg);
      if(typeof Sentry!=='undefined')Sentry.captureException(e,{extra:{context:'save_pagamentos',errorMessage:e.message}});
    }
  }
  async function remove(id){
    if(!await znxGuard(['admin','financeiro']))return;
    if(_inFlightDeletePagamento){toast('⏳ Processando...');return;}
    // [v127 CRIT-4 2026-05-09] regra_soft_delete_financeiro — pagamento é histórico fiscal.
    // ANTES: hard DELETE (bloqueado por trigger tg_block_hard_delete_financial silenciosamente).
    // AGORA: UPDATE status='Cancelado'. Mantém rastro no DRE/SPED.
    if(!await showConfirm({title:'Cancelar Pagamento',message:'Cancelar este pagamento?\n(O registro fica no histórico marcado como Cancelado pra compliance fiscal — não é apagado de verdade)',confirmText:'Cancelar',confirmColor:'#DC2626'}))return;
    _inFlightDeletePagamento=true;
    try{
      // [ONDA-D D4 2026-05-11] regra_admin_audit_log — pegar before state pra forense
      const beforeRow=pagamentos.find(p=>p.id===id)||null;
      const{error}=await sb.from('pagamentos').update({status:'Cancelado',updated_at:new Date().toISOString()}).eq('id',id);
      if(error){toast('❌ Erro ao cancelar pagamento: '+error.message);if(typeof Sentry!=='undefined')Sentry.captureException(new Error(error.message),{extra:{context:'cancelPagamento',id}});return;}
      setPagamentos(prev=>prev.map(p=>p.id===id?{...p,status:'Cancelado'}:p));
      // [ONDA-D D4 2026-05-11] audit log explícito — soft-delete financeiro é ação sensível
      try{
        await sb.rpc('log_admin_action',{
          p_action:'cancel_pagamento',
          p_target_type:'pagamento',
          p_target_id:String(id),
          p_before:beforeRow?{status:beforeRow.status,value:beforeRow.value}:null,
          p_after:{status:'Cancelado'},
          p_reason:null,
          p_metadata:{recipient:beforeRow?.recipient,value:beforeRow?.value,context:'soft_delete_pagamento'}
        });
      }catch(auditErr){
        console.warn('[ZNX] log_admin_action falhou (não-fatal):',auditErr);
      }
      toast('✅ Pagamento cancelado (mantido no histórico).');
    }catch(e){
      console.error('[ZNX] cancelPagamento error:',e);
      if(typeof Sentry!=='undefined')Sentry.captureException(e,{extra:{context:'cancelPagamento',id}});
      toast('❌ Erro inesperado ao cancelar pagamento.');
    }finally{_inFlightDeletePagamento=false;}
  }
  async function togglePago(p){
    // [v128 LOADING-STATE 2026-05-11] regra_loading_state_obrigatorio — anti duplo-click por linha
    if(togglePagoInflightRef.current.has(p.id))return;
    if(!await znxGuard(['admin','financeiro']))return;
    const newStatus=p.status==='Pago'?'Pendente':'Pago';
    // [ONDA3 P2 2026-05-11] showConfirm + audit log — admin/financeiro mudando status financeiro
    const confirmMsg = newStatus==='Pago'
      ? `Marcar este pagamento como PAGO?\n(R$ ${(p.value||0).toFixed(2)} — ${p.recipient||''})`
      : `Reverter este pagamento pra PENDENTE?\n(R$ ${(p.value||0).toFixed(2)} — ${p.recipient||''})\nSerá registrado no audit log.`;
    if(!await showConfirm({
      title: newStatus==='Pago'?'Confirmar pagamento':'Reverter pagamento',
      message: confirmMsg,
      confirmText: newStatus==='Pago'?'Marcar Pago':'Reverter',
      confirmColor: newStatus==='Pago'?'#15803D':'#EA580C'
    }))return;
    togglePagoInflightRef.current.add(p.id);
    setTogglePagoVer(v=>v+1);
    try {
      // [BUG-FIX 20260504] dualWrite + async + znxGuard — antes só setPagamentos local
      const ok=await dualWrite('pagamentos',p.id,{status:newStatus,updated_at:new Date().toISOString()},false,()=>{
        setPagamentos(prev=>prev.map(x=>x.id===p.id?{...x,status:newStatus}:x));
      });
      if(!ok&&typeof Sentry!=='undefined'){
        Sentry.captureException(new Error('togglePago_pagamentos failed'),{extra:{pagamentoId:p.id,newStatus}});
      }
      // [ONDA3 P2 2026-05-11] audit log explícito — mudança de status financeiro é ação sensível
      if(ok){
        try{
          await sb.rpc('log_admin_action',{
            p_action:'toggle_status',
            p_target_type:'pagamento',
            p_target_id:String(p.id),
            p_before:{status:p.status},
            p_after:{status:newStatus},
            p_reason:null,
            p_metadata:{value:p.value,recipient:p.recipient,context:'togglePago_pagamentos'}
          });
        }catch(_){/* audit best-effort, não bloqueia operação */}
      }
    } catch(e) {
      const msg=e?.message||'Erro ao alterar status.';
      toast('❌ '+msg);
      if(typeof Sentry!=='undefined')Sentry.captureException(e,{extra:{context:'togglePago_pagamentos',pagamentoId:p.id}});
    } finally {
      togglePagoInflightRef.current.delete(p.id);
      setTogglePagoVer(v=>v+1);
    }
  }

  // === Render (4 widgets extraídos · togglePagoVer força re-render pra refletir inflight Set) ===
  return(
    <div>
      {pgmW.PagamentosHeader && <pgmW.PagamentosHeader filter={filter} setFilter={setFilter} onNewClick={openNew}/>}
      {pgmW.PagamentosStatsCards && <pgmW.PagamentosStatsCards totalGeral={totals.totalGeral} totalPago={totals.totalPago} totalPendente={totals.totalPendente} itemCount={filtered.length} porTipo={porTipo}/>}
      {pgmW.PagamentosTable && <pgmW.PagamentosTable pagamentos={filtered} onToggle={togglePago} onEdit={openEdit} onRemove={remove} togglePagoInflightSet={togglePagoInflightRef.current}/>}
      {pgmW.PagamentoFormModal && <pgmW.PagamentoFormModal open={modal==='form'} form={form} setForm={setForm} editId={editId} onSave={save} onClose={()=>setModal(null)} isSaving={savingRef.current}/>}
    </div>
  );
}

// ══════════════════════════════════════════════════════════════
// CONTAS A PAGAR
// ══════════════════════════════════════════════════════════════

  window.ZNX = window.ZNX || {};
  window.ZNX.components = window.ZNX.components || {};
  window.ZNX.components.Pagamentos = Pagamentos;
  window.Pagamentos = Pagamentos;

  window.ZNX.refactor_phase_5_loaded = window.ZNX.refactor_phase_5_loaded || {};
  window.ZNX.refactor_phase_5_loaded.Pagamentos = true;
  // [Wave 34 marker v224.15] confirma extract executado
  window.Pagamentos_v224_15_wave34 = true;

})();
