// js/components/common/ApprovalBell.jsx
// Sino de notificações pra approval flow.
// Criado em 2026-05-05 (sistema 4 onda 4b).
//
// Comportamento por role:
//   admin/financeiro:
//     - Conta requests pending
//     - Click abre ApprovalQueueModal
//     - Pulsa quando tem novo
//   vendedora:
//     - Conta seus requests com decisão recente (approved/rejected) NÃO vistos
//     - Click abre lista de notificações (modal próprio simples)
//
// Polling: 30s
//
// Deps runtime: sb, ApprovalQueueModal
(function() {
  'use strict';
  const {useState, useEffect, useCallback} = React;

function ApprovalBell({user, clients}){
  const role = user?.role || 'vendedor';
  const isAdminFin = role === 'admin' || role === 'financeiro';
  const[count,setCount]=useState(0);
  const[notifications,setNotifications]=useState([]); // pra vendedora
  const[showQueue,setShowQueue]=useState(false);
  const[showNotifications,setShowNotifications]=useState(false);
  const[acting,setActing]=useState(false);

  const reload = useCallback(async () => {
    try {
      if(isAdminFin){
        // Conta pending não-expirados
        const{count:c,error}=await sb.from('template_approval_requests')
          .select('id',{count:'exact',head:true})
          .eq('status','pending')
          .gte('expires_at',new Date().toISOString());
        if(error)throw error;
        setCount(c||0);
      } else {
        // Vendedora: aprovados/rejeitados não vistos
        const{data,error}=await sb.from('template_approval_requests')
          .select('id,template_id,status,approved_at,reject_reason,client_ids,expires_at')
          .eq('vendedora_name', user?.name || '__none__')
          .in('status',['approved','rejected'])
          .eq('seen_by_vendedora',false)
          .order('approved_at',{ascending:false})
          .limit(20);
        if(error)throw error;
        setNotifications(data||[]);
        setCount((data||[]).length);
      }
    } catch(e){
      znxLogWarn('[ZNX] ApprovalBell reload fail', e);
    }
  },[isAdminFin,user?.name]);

  // [BUG-FIX Onda D 2026-05-07] polling 30s → 60s. Realtime cobre instantâneo, polling é fallback.
  useEffect(()=>{
    reload();
    const t=setInterval(reload,60000);
    return ()=>clearInterval(t);
  },[reload]);

  async function markSeen(id){
    if(acting)return;
    setActing(true);
    try {
      await sb.from('template_approval_requests').update({seen_by_vendedora:true}).eq('id',id);
      reload();
    } catch(e){znxLogWarn('[ZNX] markSeen fail', e);}
    finally{setActing(false);}
  }

  async function dispatchApproved(notif){
    // Re-abre o CampaignModal com clientes prefilled vindos da approval
    // Estratégia: armazena em window e dispara event customizado
    window.__znxApprovedRequest = {
      requestId: notif.id,
      templateId: notif.template_id,
      clientIds: notif.client_ids || []
    };
    window.dispatchEvent(new CustomEvent('znx:openApprovedCampaign',{detail:window.__znxApprovedRequest}));
    await markSeen(notif.id);
    setShowNotifications(false);
  }

  function templateLabel(tid){
    const labels={
      promo_5pct:'🏷️ Promo 5% off',
      frete_gratis_sp:'🚚 Frete grátis SP',
      brinde_especial:'🎁 Brinde especial'
    };
    return labels[tid]||tid;
  }

  // ═════════════ RENDER ═════════════

  if(!user)return null;

  return(
    <>
      <button onClick={()=>{
          if(isAdminFin)setShowQueue(true);
          else setShowNotifications(true);
        }}
        title={isAdminFin?`${count} aprovação(ões) pendente(s)`:`${count} resposta(s) não vista(s)`}
        style={{
          position:'relative',
          background:count>0?'#FFFBEB':'transparent',
          border:count>0?'1.5px solid #C8A951':'1.5px solid #E5E7EB',
          borderRadius:8,
          padding:'6px 10px',
          fontSize:14,
          cursor:'pointer',
          display:'flex',
          alignItems:'center',
          gap:5,
          fontWeight:600,
          color:count>0?'#92700A':'#6B7280'
        }}>
        🔔
        {count>0&&(
          <span style={{
            position:'absolute',
            top:-4,right:-4,
            background:'#DC2626',
            color:'#FFFFFF',
            borderRadius:9,
            minWidth:18,height:18,
            fontSize:10,
            fontWeight:800,
            display:'flex',
            alignItems:'center',
            justifyContent:'center',
            padding:'0 5px',
            boxShadow:'0 1px 3px rgba(0,0,0,0.2)',
            animation:'pulse 1.5s ease-in-out infinite'
          }}>{count>99?'99+':count}</span>
        )}
      </button>

      {/* Admin queue */}
      {showQueue&&isAdminFin&&(
        <ApprovalQueueModal
          user={user}
          clients={clients}
          onClose={()=>setShowQueue(false)}
          onChanged={reload}
        />
      )}

      {/* Vendedora notifications */}
      {showNotifications&&!isAdminFin&&(
        <Modal title={`🔔 Suas notificações (${notifications.length})`} onClose={()=>setShowNotifications(false)}>
          {notifications.length===0?(
            <div style={{padding:30,textAlign:'center',color:'#6B7280'}}>
              <div style={{fontSize:36,marginBottom:10}}>📭</div>
              Nenhuma notificação nova.
            </div>
          ):(
            <div style={{display:'flex',flexDirection:'column',gap:10,maxHeight:480,overflowY:'auto'}}>
              {notifications.map(n=>{
                const approved=n.status==='approved';
                const expiresIn=Math.max(0,Math.floor((new Date(n.expires_at)-Date.now())/3600000));
                return(
                  <div key={n.id} style={{
                    border:`2px solid ${approved?'#16A34A55':'#DC262655'}`,
                    background:approved?'#ECFDF5':'#FEE2E2',
                    borderRadius:10,
                    padding:'12px 14px'
                  }}>
                    <div style={{display:'flex',justifyContent:'space-between',alignItems:'baseline',marginBottom:4}}>
                      <div style={{fontSize:14,fontWeight:700,color:approved?'#16A34A':'#DC2626'}}>
                        {approved?'✅ Aprovado':'❌ Rejeitado'} — {templateLabel(n.template_id)}
                      </div>
                    </div>
                    <div style={{fontSize:12,color:'#374151',marginBottom:6}}>
                      {(n.client_ids||[]).length} cliente{(n.client_ids||[]).length>1?'s':''}
                      {approved&&expiresIn>0&&<span style={{marginLeft:8,color:'#EA580C'}}>· expira em {expiresIn}h</span>}
                    </div>
                    {n.reject_reason&&(
                      <div style={{fontSize:12,color:'#DC2626',background:'#FFFFFF',padding:'6px 10px',borderRadius:6,fontStyle:'italic',marginBottom:8}}>
                        💬 "{n.reject_reason}"
                      </div>
                    )}
                    <div style={{display:'flex',gap:6,justifyContent:'flex-end'}}>
                      <button className="btn-outline btn-sm" onClick={()=>markSeen(n.id)} disabled={acting}>
                        Marcar como visto
                      </button>
                      {approved&&expiresIn>0&&(
                        <button className="btn-gold btn-sm" onClick={()=>dispatchApproved(n)} disabled={acting}>
                          📱 Disparar agora
                        </button>
                      )}
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </Modal>
      )}

      <style>{`
        @keyframes pulse {
          0%,100% { transform: scale(1); }
          50% { transform: scale(1.15); }
        }
      `}</style>
    </>
  );
}

  // Namespace
  window.ZNX = window.ZNX || {};
  window.ZNX.common = window.ZNX.common || {};
  window.ZNX.common.ApprovalBell = ApprovalBell;
  window.ApprovalBell = ApprovalBell;
})();
