// js/components/widgets/gastos/FolhaTab.jsx
// [Wave Gastos FULL 2026-05-18 v223.22] Extraído de Gastos.jsx L722-818 (tab Folha de Pagamento auto).
// Props (6 objetos agregados): period, stats, payroll, data, actions, helpers.
// Padrão: IIFE + window.ZNX.widgets.gastos.FolhaTab.
(function() {
  'use strict';

  function FolhaTab({period, stats, payroll, data, actions, helpers}) {
    const {payrollMonth, setPayrollMonth} = period;
    const {folhaTotal, folhaPagoMes, employeesWithSalary} = stats;
    const {gerarFolhaMes, payrollInflight, bulkPayFolhaMes, bulkPayInflight} = payroll;
    const {allUsers, folhaStats, paymentsByGasto, isAdmin} = data;
    const {onSalaryEdit, onPay, onReceipt} = actions;
    const {fmt} = helpers;

    return (
      <div>
        {/* Toolbar */}
        <div className="card" style={{padding:14,marginBottom:14,display:'flex',gap:14,alignItems:'center',flexWrap:'wrap'}}>
          <div>
            <label style={{fontSize:11,color:'#9CA3AF',display:'block',marginBottom:2}}>Mês de referência</label>
            <input type="month" value={payrollMonth} onChange={e=>setPayrollMonth(e.target.value)} style={{padding:'6px 10px',border:'1px solid #D1D5DB',borderRadius:6}}/>
          </div>
          <div style={{width:1,height:30,background:'#E5E7EB'}}/>
          <div>
            <div style={{fontSize:10,color:'#9CA3AF',textTransform:'uppercase',letterSpacing:.5}}>Folha esperada</div>
            <div style={{fontSize:20,fontWeight:800,color:'#7C3AED'}}>{fmt(folhaTotal)}</div>
            <div style={{fontSize:11,color:'#6B7280'}}>{employeesWithSalary.length} funcionário(s)</div>
          </div>
          <div>
            <div style={{fontSize:10,color:'#9CA3AF',textTransform:'uppercase',letterSpacing:.5}}>Pago no mês</div>
            <div style={{fontSize:20,fontWeight:800,color:'#16A34A'}}>{fmt(folhaPagoMes)}</div>
            <div style={{fontSize:11,color:'#6B7280'}}>{folhaTotal>0?Math.round(folhaPagoMes/folhaTotal*100):0}% concluído</div>
          </div>
          <div style={{flex:1}}/>
          {isAdmin && (
            <>
              <button onClick={gerarFolhaMes} disabled={payrollInflight} style={{padding:'10px 18px',background:payrollInflight?'#9CA3AF':'#7C3AED',color:'#fff',border:'none',borderRadius:6,fontSize:13,fontWeight:700,cursor:payrollInflight?'wait':'pointer'}}>
                {payrollInflight?'⏳ Gerando...':`🗓️ Gerar Folha de ${payrollMonth}`}
              </button>
              {/* [v217] Pagar Folha Toda em lote */}
              <button onClick={bulkPayFolhaMes} disabled={bulkPayInflight} style={{padding:'10px 18px',background:bulkPayInflight?'#9CA3AF':'#16A34A',color:'#fff',border:'none',borderRadius:6,fontSize:13,fontWeight:700,cursor:bulkPayInflight?'wait':'pointer'}} title="Registra pagamento total pra todos os pendentes/parciais da folha do mês">
                {bulkPayInflight?'⏳ Pagando...':`💰 Pagar Folha Toda`}
              </button>
            </>
          )}
        </div>

        {/* Lista funcionários */}
        <div className="card" style={{padding:0,overflowX:'auto'}}>
          <div style={{padding:'12px 16px',borderBottom:'1px solid #E4E7EC',fontWeight:700,color:'#7C3AED'}}>👥 Funcionários e salários</div>
          {(!allUsers||allUsers.length===0) ? (
            <div style={{padding:30,textAlign:'center',color:'#9CA3AF'}}>Carregando funcionários...</div>
          ) : (
            <table>
              <thead><tr>
                <th>Funcionário</th>
                <th>Função</th>
                <th style={{textAlign:'right'}}>Salário Base</th>
                <th>Status no mês</th>
                <th>Recibo</th>
                <th>Ações</th>
              </tr></thead>
              <tbody>
                {(allUsers||[]).filter(u=>u.active!==false).sort((a,b)=>(b.monthly_salary||0)-(a.monthly_salary||0)).map(u=>{
                  const folha = folhaStats[u.id];
                  const sal = Number(u.monthly_salary||0);
                  return(
                    <tr key={u.id}>
                      <td style={{fontWeight:600}}>{u.name}</td>
                      <td><span style={{fontSize:11,color:'#6B7280',background:'#F3F4F6',padding:'2px 8px',borderRadius:12}}>{u.role}</span></td>
                      <td style={{textAlign:'right',fontWeight:700,color:sal>0?'#7C3AED':'#9CA3AF'}}>
                        {sal>0 ? fmt(sal) : <span style={{fontStyle:'italic'}}>não definido</span>}
                      </td>
                      <td>
                        {!folha && <span className="badge badge-gray">Não lançado</span>}
                        {folha?.status==='Pendente' && <span className="badge badge-yellow">Pendente</span>}
                        {folha?.status==='Parcial' && (()=>{
                          const pct = folha.value>0 ? Math.round((Number(folha.paid_value||0)/Number(folha.value||1))*100) : 0;
                          return <span style={{padding:'2px 8px',borderRadius:10,fontSize:11,fontWeight:700,background:'#DBEAFE',color:'#1E40AF'}}>Parcial {pct}% · falta {fmt(Number(folha.value||0)-Number(folha.paid_value||0))}</span>;
                        })()}
                        {folha?.status==='Pago' && <span className="badge badge-green">✓ Pago</span>}
                        {folha?.status==='Cancelado' && <span className="badge badge-gray">Cancelado</span>}
                      </td>
                      <td>{(()=>{
                        const fp = (paymentsByGasto[folha?.id]||[]).filter(p=>!p.deleted_at);
                        if(fp.length===0) return <span style={{color:'#9CA3AF'}}>—</span>;
                        if(fp.length===1) return <span style={{fontSize:11,color:'#16A34A',fontWeight:700}}>{fp[0].receipt_number}</span>;
                        return <span style={{fontSize:11,color:'#16A34A',fontWeight:700}}>{fp.length} recibos · último {fp[0].receipt_number}</span>;
                      })()}</td>
                      <td>
                        <div style={{display:'flex',gap:4,flexWrap:'wrap'}}>
                          {isAdmin && (
                            <button className="btn-outline btn-sm" onClick={()=>onSalaryEdit(u)} title="Editar salário base">💰</button>
                          )}
                          {(folha?.status==='Pendente'||folha?.status==='Parcial') && isAdmin && (
                            <button className="btn-gold btn-sm" onClick={()=>onPay(folha)} title="Pagar (total ou parcial)">💰 Pagar</button>
                          )}
                          {folha && (folha.status==='Pago'||folha.status==='Parcial') && (
                            <button className="btn-outline btn-sm" onClick={()=>onReceipt(folha)} title="Recibos do pagamento" style={{background:'#EFF6FF',color:'#2563EB'}}>🧾 Recibo</button>
                          )}
                        </div>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          )}
        </div>
      </div>
    );
  }

  window.ZNX = window.ZNX || {};
  window.ZNX.widgets = window.ZNX.widgets || {};
  window.ZNX.widgets.gastos = window.ZNX.widgets.gastos || {};
  window.ZNX.widgets.gastos.FolhaTab = FolhaTab;
})();
