// js/components/widgets/ApprovalHub.jsx
// Approval Hub Centralizado — V6 (sistema 4).
// Dashboard único pra admin/financeiro ver TODOS os pedidos pendentes:
// 1. Descontos (discount_requests) — vendedora pediu desconto, espera aprovação
// 2. Cancelamentos (cancel_requests) — vendedora pediu cancelar venda
// 3. Templates restritos (template_approval_requests) — vendedora pediu campanha
//
// Click numa linha abre modal específico (reaproveita modais existentes).
// Criado em 2026-05-06.
//
// Props:
//   user: admin/financeiro
//   discountRequests: array do JSONB
//   cancelRequests: array do JSONB
//   sales, products, clients: pra lookup
//   onOpenDiscount: (req) => void — abre DiscountApprovalModal
//   onOpenCancel: () => void — abre CancelApprovalModal
//   onOpenTemplates: () => void — abre ApprovalQueueModal
//
// Deps runtime: fmt, sb
(function() {
  'use strict';
  const {useState, useEffect, useMemo} = React;

  function ApprovalHub({user, discountRequests, cancelRequests, sales, products, clients, onOpenDiscount, onOpenCancel, onOpenTemplates}) {
    const isAdmin = user?.role === 'admin' || user?.role === 'financeiro';
    if (!isAdmin) return null;

    // Templates pendentes (query async porque não vem no JSONB)
    const [templatesPending, setTemplatesPending] = useState(0);
    useEffect(() => {
      sb.from('template_approval_requests')
        .select('id', {count:'exact', head:true})
        .eq('status', 'pending')
        .gte('expires_at', new Date().toISOString())
        .then(({count}) => setTemplatesPending(count || 0))
        .catch(() => setTemplatesPending(0));
    }, []);

    // Descontos pendentes
    const drPending = useMemo(() => {
      return (discountRequests || [])
        .filter(d => d.status === 'pending')
        .sort((a, b) => new Date(a.requestedAt || a.requested_at || 0) - new Date(b.requestedAt || b.requested_at || 0));
    }, [discountRequests]);

    // Cancelamentos pendentes
    const crPending = useMemo(() => {
      return (cancelRequests || [])
        .filter(c => c.status === 'pending')
        .sort((a, b) => new Date(a.requestedAt || a.requested_at || a.created_at || 0) - new Date(b.requestedAt || b.requested_at || b.created_at || 0));
    }, [cancelRequests]);

    const totalPending = drPending.length + crPending.length + templatesPending;

    // [v224.114 UX desconto 2026-06-02] Feed histórico recente — admin vê quem resolveu hoje
    // (evita Jamal competir com Mohamed pra aprovar o mesmo request · transparência).
    const drResolvedToday = useMemo(function(){
      var ts = new Date(); ts.setHours(0,0,0,0); var tsMs = ts.getTime();
      return (discountRequests || [])
        .filter(function(d){
          if(d.status !== 'approved' && d.status !== 'denied') return false;
          var at = new Date(d.resolvedAt || d.resolved_at || d.requestedAt || d.requested_at || 0).getTime();
          return at >= tsMs;
        })
        .sort(function(a,b){ return new Date(b.resolvedAt||b.resolved_at||0) - new Date(a.resolvedAt||a.resolved_at||0); })
        .slice(0, 5);
    }, [discountRequests]);

    function _renderResolvedFeed(){
      if(drResolvedToday.length === 0) return null;
      return (
        <details style={{marginTop:14, background:'#F9FAFB', border:'1px solid #E5E7EB', borderRadius:8, padding:'10px 14px'}}>
          <summary style={{cursor:'pointer', fontWeight:600, color:'#6B7280', fontSize:12, textTransform:'uppercase', letterSpacing:1}}>
            📜 Últimas {drResolvedToday.length} resolvidas hoje
          </summary>
          <div style={{display:'flex', flexDirection:'column', gap:6, marginTop:10}}>
            {drResolvedToday.map(function(d){
              var isApproved = d.status === 'approved';
              var bg = isApproved ? '#F0FDF4' : '#FEF2F2';
              var bd = isApproved ? '#16A34A33' : '#DC262633';
              var icon = isApproved ? '✅' : '❌';
              var color = isApproved ? '#15803D' : '#B91C1C';
              var resolver = d.resolvedByName || d.resolved_by_name || '—';
              var reqBy = d.requestedBy || d.requested_by || '—';
              var client = d.clientName || d.client_name || '—';
              var valor = fmtMoney(d.totalDesconto || d.total_desconto || 0);
              var at = d.resolvedAt || d.resolved_at;
              var tStr = at ? new Date(at).toLocaleTimeString('pt-BR',{hour:'2-digit',minute:'2-digit'}) : '';
              var reason = d.deniedReason || d.denied_reason;
              return (
                <div key={d.id} style={{padding:'8px 12px', background:bg, border:'1px solid '+bd, borderRadius:6, display:'flex', justifyContent:'space-between', alignItems:'center', gap:10, fontSize:12}}>
                  <div style={{flex:1, minWidth:0}}>
                    <div style={{fontWeight:600, color:color}}>{icon} {reqBy} → {client}</div>
                    <div style={{color:'#6B7280', fontSize:11}}>
                      por <strong>{resolver}</strong>{tStr ? ' às '+tStr : ''}
                      {!isApproved && reason && <span style={{fontStyle:'italic'}}> · motivo: "{reason}"</span>}
                    </div>
                  </div>
                  <div style={{fontWeight:700, color: isApproved?'#15803D':'#B91C1C'}}>−{valor}</div>
                </div>
              );
            })}
          </div>
        </details>
      );
    }

    function timeAgo(iso) {
      if (!iso) return '—';
      const d = Date.now() - new Date(iso).getTime();
      const h = Math.floor(d / 3600000);
      const m = Math.floor(d / 60000) % 60;
      if (h > 24) return Math.floor(h/24) + 'd atrás';
      if (h > 0) return `${h}h ${m}m`;
      if (m > 0) return `${m}min`;
      return 'agora';
    }

    function urgencyColor(iso) {
      if (!iso) return '#9CA3AF';
      const h = (Date.now() - new Date(iso).getTime()) / 3600000;
      if (h > 24) return '#DC2626';   // mais de 1 dia → vermelho
      if (h > 4) return '#EA580C';    // mais de 4h → laranja
      if (h > 1) return '#C8A951';    // mais de 1h → amarelo
      return '#9CA3AF';                // recente → cinza
    }

    if (totalPending === 0) {
      return (
        <>
          <div className="card" style={{padding:30,textAlign:'center'}}>
            <div style={{fontSize:48,marginBottom:10}}>✅</div>
            <div style={{fontSize:16,fontWeight:700,color:'#16A34A',marginBottom:4}}>Nenhuma aprovação pendente</div>
            <div style={{fontSize:12,color:'#6B7280'}}>Tudo limpo. Vendedoras estão usando dentro das regras.</div>
          </div>
          {_renderResolvedFeed()}
        </>
      );
    }

    return (
      <div style={{display:'flex',flexDirection:'column',gap:14}}>
        {/* Header */}
        <div>
          <div style={{fontSize:18,fontWeight:800,color:'#1B2A4A',letterSpacing:'-0.02em'}}>
            🔔 Centro de Aprovações <span style={{color:'#DC2626',fontSize:14,fontWeight:600,marginLeft:6}}>({totalPending} pendente{totalPending===1?'':'s'})</span>
          </div>
          <div style={{fontSize:12,color:'#6B7280',marginTop:2}}>
            Pedidos das vendedoras esperando sua decisão. Ordenado por mais antigo (urgência).
          </div>
        </div>

        {/* KPIs por tipo */}
        <div style={{display:'grid',gridTemplateColumns:'repeat(3, 1fr)',gap:10}}>
          <div className="stat-card" style={{borderLeft:'4px solid #EA580C',cursor:drPending.length?'pointer':'default'}} onClick={()=>drPending.length && onOpenDiscount && onOpenDiscount()}>
            <div className="stat-label">💰 Descontos</div>
            <div className="stat-value" style={{color:'#EA580C',fontSize:24}}>{drPending.length}</div>
            <div style={{fontSize:11,color:'#9CA3AF'}}>{drPending.length>0 ? `Total: ${fmtMoney(drPending.reduce((s,d)=>s+(Number(d.totalDesconto||d.total_desconto||0)),0))}` : 'Tudo aprovado'}</div>
          </div>
          <div className="stat-card" style={{borderLeft:'4px solid #DC2626',cursor:crPending.length?'pointer':'default'}} onClick={()=>crPending.length && onOpenCancel && onOpenCancel()}>
            <div className="stat-label">🚫 Cancelamentos</div>
            <div className="stat-value" style={{color:'#DC2626',fontSize:24}}>{crPending.length}</div>
            <div style={{fontSize:11,color:'#9CA3AF'}}>{crPending.length>0 ? 'Click pra revisar' : 'Tudo limpo'}</div>
          </div>
          <div className="stat-card" style={{borderLeft:'4px solid #2563EB',cursor:templatesPending?'pointer':'default'}} onClick={()=>templatesPending && onOpenTemplates && onOpenTemplates()}>
            <div className="stat-label">📨 Templates restritos</div>
            <div className="stat-value" style={{color:'#2563EB',fontSize:24}}>{templatesPending}</div>
            <div style={{fontSize:11,color:'#9CA3AF'}}>{templatesPending>0 ? 'Campanhas aguardando' : 'Sem pedidos'}</div>
          </div>
        </div>

        {/* Lista descontos */}
        {drPending.length > 0 && (
          <div className="card">
            <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:10}}>
              <div style={{fontSize:13,fontWeight:700,color:'#9CA3AF',textTransform:'uppercase',letterSpacing:1}}>
                💰 Descontos pendentes ({drPending.length})
              </div>
              <button className="btn-outline btn-sm" onClick={()=>onOpenDiscount && onOpenDiscount()}>Abrir modal completo →</button>
            </div>
            <div style={{display:'flex',flexDirection:'column',gap:6}}>
              {drPending.slice(0, 5).map(d => {
                const reason = d.requestReason || d.request_reason || '(sem motivo)';
                const at = d.requestedAt || d.requested_at;
                return (
                  <div key={d.id} onClick={()=>onOpenDiscount && onOpenDiscount(d)} style={{
                    padding:'10px 14px',
                    background:'#FFFBEB',
                    border:'1px solid #FCD34D55',
                    borderRadius:8,
                    cursor:'pointer',
                    display:'flex',
                    justifyContent:'space-between',
                    alignItems:'center',
                    gap:12,
                    transition:'all .15s',
                  }}
                  onMouseEnter={e=>e.currentTarget.style.borderColor='#EA580C'}
                  onMouseLeave={e=>e.currentTarget.style.borderColor='#FCD34D55'}>
                    <div style={{flex:1,minWidth:0}}>
                      <div style={{fontSize:13,fontWeight:600,color:'#1B2A4A'}}>
                        <strong>{d.requestedBy||d.requested_by||'—'}</strong> → {d.clientName||d.client_name||'—'}
                      </div>
                      <div style={{fontSize:12,color:'#6B7280',fontStyle:'italic',marginTop:2,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>
                        💬 "{reason}"
                      </div>
                    </div>
                    <div style={{textAlign:'right',whiteSpace:'nowrap'}}>
                      <div style={{fontSize:14,fontWeight:700,color:'#DC2626'}}>−{fmtMoney(d.totalDesconto||d.total_desconto)}</div>
                      <div style={{fontSize:10,color:urgencyColor(at),fontWeight:600}}>{timeAgo(at)}</div>
                    </div>
                  </div>
                );
              })}
              {drPending.length > 5 && (
                <div style={{textAlign:'center',padding:'8px',fontSize:12,color:'#6B7280'}}>
                  + {drPending.length - 5} mais — abre o modal pra ver todos
                </div>
              )}
            </div>
          </div>
        )}

        {/* Lista cancelamentos */}
        {crPending.length > 0 && (
          <div className="card">
            <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:10}}>
              <div style={{fontSize:13,fontWeight:700,color:'#9CA3AF',textTransform:'uppercase',letterSpacing:1}}>
                🚫 Cancelamentos pendentes ({crPending.length})
              </div>
              <button className="btn-outline btn-sm" onClick={()=>onOpenCancel && onOpenCancel()}>Abrir modal completo →</button>
            </div>
            <div style={{display:'flex',flexDirection:'column',gap:6}}>
              {crPending.slice(0, 5).map(c => {
                const sale = (sales||[]).find(s=>s.id===c.saleId||s.id===c.sale_id);
                const at = c.requestedAt || c.requested_at || c.created_at;
                return (
                  <div key={c.id} onClick={()=>onOpenCancel && onOpenCancel()} style={{
                    padding:'10px 14px',
                    background:'#FEF2F2',
                    border:'1px solid #FCA5A555',
                    borderRadius:8,
                    cursor:'pointer',
                    display:'flex',
                    justifyContent:'space-between',
                    alignItems:'center',
                    gap:12,
                  }}>
                    <div style={{flex:1,minWidth:0}}>
                      <div style={{fontSize:13,fontWeight:600,color:'#1B2A4A'}}>
                        <strong>{c.sellerName||c.seller_name||'—'}</strong> · {sale?.number||'venda'}
                      </div>
                      {c.reason && (
                        <div style={{fontSize:12,color:'#6B7280',fontStyle:'italic',marginTop:2}}>
                          💬 "{c.reason}"
                        </div>
                      )}
                    </div>
                    <div style={{textAlign:'right',whiteSpace:'nowrap'}}>
                      {sale && <div style={{fontSize:14,fontWeight:700,color:'#1B2A4A'}}>{fmtMoney((typeof saleFinalTotal==='function'?saleFinalTotal(sale):0)+(Number(sale.nfTaxValue||sale.nf_tax_value||0))||sale.total||0)}</div>}
                      <div style={{fontSize:10,color:urgencyColor(at),fontWeight:600}}>{timeAgo(at)}</div>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        )}

        {/* Atalho templates */}
        {templatesPending > 0 && (
          <div className="card">
            <div style={{display:'flex',justifyContent:'space-between',alignItems:'center'}}>
              <div>
                <div style={{fontSize:13,fontWeight:700,color:'#2563EB'}}>📨 {templatesPending} pedido{templatesPending===1?'':'s'} de template restrito</div>
                <div style={{fontSize:12,color:'#6B7280',marginTop:2}}>Vendedoras pediram pra disparar campanhas com templates restritos.</div>
              </div>
              <button className="btn-gold btn-sm" onClick={()=>onOpenTemplates && onOpenTemplates()}>Revisar →</button>
            </div>
          </div>
        )}

        {_renderResolvedFeed()}

        {/* Footer */}
        <div style={{padding:'10px 14px',background:'#F8FAFB',borderRadius:8,fontSize:11,color:'#6B7280',textAlign:'center'}}>
          💡 Cards ordenados por mais antigo. Cor da urgência: cinza (recente) · amarelo (1h+) · laranja (4h+) · vermelho (1 dia+).
        </div>
      </div>
    );
  }

  window.ZNX = window.ZNX || {};
  window.ZNX.components = window.ZNX.components || {};
  window.ZNX.components.ApprovalHub = ApprovalHub;
  window.ApprovalHub = ApprovalHub;
  window.ZNX.refactor_phase_5_loaded = window.ZNX.refactor_phase_5_loaded || {};
  window.ZNX.refactor_phase_5_loaded.ApprovalHub = true;
})();
