// js/components/widgets/clientes/CreditPanel.jsx
// [Wave 9 KIMI 2026-05-17] Extraído de Clientes.jsx L430-462 — bloco crédito dentro de ClientModal.
// Padrão: IIFE + window.ZNX.widgets.clientes.CreditPanel namespace + props injection.
//
// Bloco "Crédito disponível" do ClientModal (Ficha View):
// - Saldo atual (verde se > 0, cinza se 0)
// - Botões + Adicionar / − Remover (admin/financeiro only)
// - Histórico de movimentações (details collapsible)
//
// Props (validados FASE 1.5 = 6 props):
//   client: object — cliente atual da Ficha
//   creditBalance: number — derived no pai (client.creditBalance || client.credit_balance || 0)
//   canEditCredit: bool — admin/financeiro check (gate buttons)
//   creditHistory: array — movimentações
//   onAddCredit: fn — closure setCreditModal add do pai
//   onRemoveCredit: fn — closure setCreditModal remove do pai
//
// Deps runtime globals: fmt (window.fmt — formato BRL).
(function() {
  'use strict';

  function CreditPanel({client, creditBalance, canEditCredit, isAdmin, creditHistory, onAddCredit, onRemoveCredit, onRefundCredit}){
    return (
      <>
        {/* [FEATURE crédito] Bloco crédito disponível + botão admin/financeiro */}
        <div style={{background:creditBalance>0?'#ECFDF5':'#F9FAFB',border:'1px solid '+(creditBalance>0?'#10B98144':'#E5E7EB'),borderRadius:8,padding:'12px 16px',marginBottom:14,display:'flex',justifyContent:'space-between',alignItems:'center'}}>
          <div>
            <div style={{fontSize:11,color:'#6B7280',textTransform:'uppercase',letterSpacing:1,marginBottom:2}}>💰 Crédito disponível</div>
            <div style={{fontSize:22,fontWeight:800,color:creditBalance>0?'#059669':'#9CA3AF'}}>{fmt(creditBalance)}</div>
          </div>
          {canEditCredit&&(
            <div style={{display:'flex',gap:8}}>
              <button className="btn-gold btn-sm" onClick={onAddCredit}>+ Adicionar</button>
              {creditBalance>0&&isAdmin&&onRefundCredit&&<button className="btn-sm" style={{background:'#92400E',color:'#fff',border:'none',padding:'6px 12px',borderRadius:4,cursor:'pointer',fontWeight:600}} onClick={onRefundCredit}>💸 Estornar</button>}
              {creditBalance>0&&<button className="btn-outline btn-sm" style={{borderColor:'#DC2626',color:'#DC2626'}} onClick={onRemoveCredit}>− Remover</button>}
            </div>
          )}
        </div>
        {/* Histórico de movimentações de crédito (admin/financeiro) */}
        {canEditCredit&&creditHistory.length>0&&(
          <details style={{marginBottom:14,background:'#FAFBFC',border:'1px solid #E5E7EB',borderRadius:8,padding:'8px 12px'}}>
            <summary style={{cursor:'pointer',fontWeight:600,color:'#374151',fontSize:13}}>📜 Histórico de crédito ({creditHistory.length})</summary>
            <table style={{marginTop:10,fontSize:12}}>
              <thead><tr><th>Data</th><th>Tipo</th><th>Valor</th><th>Motivo</th><th>Quem</th></tr></thead>
              <tbody>
                {creditHistory.map(h=>(
                  <tr key={h.id}>
                    <td>{new Date(h.created_at).toLocaleString('pt-BR',{day:'2-digit',month:'2-digit',hour:'2-digit',minute:'2-digit'})}</td>
                    <td><span className={`badge ${h.movement_type==='add'?'badge-blue':h.movement_type==='use'?'badge-gray':h.movement_type==='refund'?'badge-blue':'badge-red'}`}>{h.movement_type==='add'?'+ ADIÇÃO':h.movement_type==='remove'?'− REMOÇÃO':h.movement_type==='use'?'USO EM VENDA':h.movement_type==='refund'?'DEVOLUÇÃO':h.movement_type}</span></td>
                    <td style={{fontWeight:700,color:(h.movement_type==='add'||h.movement_type==='refund')?'#059669':'#DC2626'}}>{(h.movement_type==='add'||h.movement_type==='refund')?'+':'−'} {fmt(h.value)}</td>
                    <td>{h.reason||'—'}</td>
                    <td>{h.created_by_name||'—'}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </details>
        )}
      </>
    );
  }

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