// js/components/widgets/clientes/ListaTabView.jsx
// [Wave 17 v223.43 20260521] Aba Lista clientes — extraído de Clientes.jsx L460-634
// MAIS USADA pela equipe — ZERO regressão tolerada
// Props: filtered, visibleClients, receivables, search, setSearch, filterState, setFilterState,
//        filterSegment, setFilterSegment, filterIncompletos, setFilterIncompletos,
//        selectedIds, MAX_BULK, todaySentByMe, todayOutreachMap, clientHealthMap, user,
//        clientesCalcs, onOpen360, onSetView, onSetForm, onSetModal, onDel,
//        onToggleSelect, onSelectAllVisible, onClearSelection, onOpenCampaign,
//        selectedClientsList
// Deps runtime: window.SmartSelect, window.Icon, window.exportCSV, window.BR_STATES,
//               window.CLIENT_SEGMENTS, window.toast
(function(){
  'use strict';

  function ListaTabView(props){
    // Defensive coalesce (regra_destructure_data_props_com_default v223.42.2)
    const filtered = props.filtered || [];
    const visibleClients = props.visibleClients || [];
    const receivables = props.receivables || [];
    const search = props.search || '';
    const setSearch = props.setSearch || function(){};
    const filterState = props.filterState || '';
    const setFilterState = props.setFilterState || function(){};
    const filterSegment = props.filterSegment || '';
    const setFilterSegment = props.setFilterSegment || function(){};
    const filterIncompletos = !!props.filterIncompletos;
    const setFilterIncompletos = props.setFilterIncompletos || function(){};
    const selectedIds = props.selectedIds || new Set();
    const MAX_BULK = Number(props.MAX_BULK || 25);
    const todaySentByMe = Number(props.todaySentByMe || 0);
    const todayOutreachMap = props.todayOutreachMap || new Map();
    const clientHealthMap = props.clientHealthMap || new Map();
    const user = props.user || {};
    const clientesCalcs = props.clientesCalcs || (window.ZNX && window.ZNX.clientes && window.ZNX.clientes.calcs) || {};
    const onOpen360 = props.onOpen360 || function(){};
    const onSetView = props.onSetView || function(){};
    const onSetForm = props.onSetForm || function(){};
    const onSetModal = props.onSetModal || function(){};
    const onDel = props.onDel || function(){};
    const onToggleSelect = props.onToggleSelect || function(){};
    const onSelectAllVisible = props.onSelectAllVisible || function(){};
    const onClearSelection = props.onClearSelection || function(){};
    const onOpenCampaign = props.onOpenCampaign || function(){};
    const selectedClientsList = props.selectedClientsList || [];
    const EMPTY = props.EMPTY || {};

    const SmartSelect = window.SmartSelect;
    const Icon = window.Icon;
    const exportCSV = (typeof window.exportCSV === 'function') ? window.exportCSV : function(){ alert('exportCSV não disponível'); };
    const BR_STATES = window.BR_STATES || [];
    const CLIENT_SEGMENTS = window.CLIENT_SEGMENTS || [];

    if (!SmartSelect || !Icon) {
      if (window.Sentry && typeof window.Sentry.captureMessage === 'function') {
        try { window.Sentry.captureMessage('[Wave 17 v223.43] ListaTabView missing deps: SmartSelect='+(!!SmartSelect)+' Icon='+(!!Icon), 'error'); } catch(e){}
      }
      console.error('[ListaTabView] Deps faltando: SmartSelect=', !!SmartSelect, 'Icon=', !!Icon);
      return (<div style={{padding:20,color:'#B91C1C',background:'#FEE2E2',borderRadius:8}}>Erro: widgets faltando. Recarregue (Ctrl+Shift+R).</div>);
    }

    return (
      <>
        <div className="page-header">
          {/* [L2-Clientes] Title com contador adaptativo */}
          <div className="page-title">
            Clientes
            {(function(){
              const hasFilters = !!(search || filterState || filterSegment);
              return hasFilters
                ? <span style={{fontSize:13,color:'#B89840',fontWeight:600,marginLeft:8}}>({filtered.length} de {visibleClients.length}{user && user.role==='vendedor'?' seus':''})</span>
                : <span style={{fontSize:13,color:'#9CA3AF',fontWeight:400,marginLeft:8}}>({visibleClients.length}{user && user.role==='vendedor'?' seus':''})</span>;
            })()}
          </div>
          <div style={{display:'flex',gap:8,flexWrap:'wrap'}}>
            <input style={{width:240}} value={search} onChange={function(e){ setSearch(e.target.value); }} placeholder="🔍 Nome, CPF/CNPJ, cidade, telefone..."/>
            <SmartSelect width={90} value={filterState} onChange={setFilterState} placeholder="Estado" options={[{value:'',label:'Estado'}].concat(BR_STATES.map(function(s){ return {value:s,label:s}; }))}/>
            <SmartSelect width={170} value={filterSegment} onChange={setFilterSegment} placeholder="Segmento" options={[{value:'',label:'Segmento'}].concat(CLIENT_SEGMENTS.map(function(s){ return {value:s,label:s}; }))}/>
            {(function(){
              const incQty = visibleClients.filter(clientesCalcs.isClienteIncompleto || function(){return false;}).length;
              if (incQty === 0) return null;
              return (
                <button onClick={function(){ setFilterIncompletos(!filterIncompletos); }}
                  style={{padding:'7px 12px',borderRadius:8,border:'1.5px solid '+(filterIncompletos?'#92700A':'#FCA5A5'),background:filterIncompletos?'#FEF3C7':'#FFFFFF',color:filterIncompletos?'#92700A':'#DC2626',fontWeight:700,fontSize:12,cursor:'pointer',display:'flex',alignItems:'center',gap:5}}>
                  ⚠ {filterIncompletos?'Mostrar todos':'Só incompletos ('+incQty+')'}
                </button>
              );
            })()}
            <button className="btn-outline" onClick={function(){ exportCSV(filtered.map(function(c){ return {Nome:c.name,Tipo:c.type,Documento:c.document||'',Segmento:c.segment||'',Telefone:c.phone||'',WhatsApp:c.whatsapp||'',Email:c.email||'',Cidade:c.city||'',Estado:c.state||'',CanalPref:c.canalPref||'',PrazoPgto:c.paymentTerm||'',LimiteCredito:c.creditLimit||0}; }), 'clientes_zaynex'); }} style={{display:'flex',alignItems:'center',gap:5,fontSize:12}}>⬇ CSV</button>
            <button className="btn-gold" onClick={function(){ onSetForm(EMPTY); onSetModal('new'); }} style={{display:'flex',alignItems:'center',gap:6}}><Icon n="plus" size={14}/>Novo Cliente</button>
          </div>
        </div>

        {/* Contador diário 25/25 */}
        {(function(){
          const remaining = Math.max(0, MAX_BULK - todaySentByMe);
          const pct = Math.min(100, (todaySentByMe/MAX_BULK)*100);
          const color = todaySentByMe >= MAX_BULK ? '#DC2626' : todaySentByMe >= 20 ? '#EA580C' : '#16A34A';
          return (
            <div style={{background:'#FFFFFF',border:'1px solid #E5E7EB',borderRadius:10,padding:'10px 14px',marginBottom:12,display:'flex',alignItems:'center',gap:14}}>
              <div style={{fontSize:18}}>📊</div>
              <div style={{flex:1}}>
                <div style={{display:'flex',justifyContent:'space-between',alignItems:'baseline',marginBottom:5}}>
                  <div style={{fontSize:12,color:'#6B7280',fontWeight:600}}>Mensagens disparadas hoje</div>
                  <div style={{fontSize:13,fontWeight:700,color:color}}>
                    {todaySentByMe} / {MAX_BULK}
                    {remaining>0
                      ? <span style={{color:'#9CA3AF',fontWeight:500,fontSize:11,marginLeft:6}}>· sobram {remaining}</span>
                      : <span style={{color:'#DC2626',fontWeight:700,fontSize:11,marginLeft:6}}>· LIMITE DO DIA ATINGIDO</span>}
                  </div>
                </div>
                <div style={{height:5,background:'#F3F4F6',borderRadius:3,overflow:'hidden'}}>
                  <div style={{width:pct+'%',height:'100%',background:color,transition:'width .3s'}}/>
                </div>
              </div>
            </div>
          );
        })()}

        {/* Barra de bulk action */}
        {selectedIds.size > 0 && (function(){
          const remaining = Math.max(0, MAX_BULK - todaySentByMe);
          const blocked = remaining === 0;
          const newOnes = selectedClientsList.filter(function(c){ return !todayOutreachMap.has(c.id); }).length;
          const dupes = selectedIds.size - newOnes;
          return (
            <div style={{position:'sticky',top:0,zIndex:5,background:'#FFFBEB',border:'2px solid #C8A951',borderRadius:10,padding:'10px 14px',marginBottom:12,display:'flex',justifyContent:'space-between',alignItems:'center',boxShadow:'0 2px 8px rgba(200,169,81,.2)'}}>
              <div>
                <div style={{fontSize:14,fontWeight:700,color:'#92700A'}}>🎯 {selectedIds.size} cliente{selectedIds.size>1?'s':''} selecionado{selectedIds.size>1?'s':''}</div>
                {dupes>0 && <div style={{fontSize:11,color:'#EA580C',marginTop:2}}>⚠ {dupes} já contactado{dupes>1?'s':''} hoje — pulará automaticamente</div>}
                {blocked && <div style={{fontSize:11,color:'#DC2626',marginTop:2,fontWeight:700}}>🚫 Limite diário {MAX_BULK} atingido</div>}
                {!blocked && newOnes>remaining && <div style={{fontSize:11,color:'#EA580C',marginTop:2}}>⚠ Sobram {remaining} disparos — só os {remaining} primeiros serão enviados</div>}
              </div>
              <div style={{display:'flex',gap:8}}>
                <button className="btn-outline btn-sm" onClick={onClearSelection}>Limpar</button>
                <button className="btn-gold" onClick={onOpenCampaign} disabled={blocked||newOnes===0} style={{display:'flex',alignItems:'center',gap:6,opacity:blocked||newOnes===0?0.5:1}}>📱 Disparar campanha</button>
              </div>
            </div>
          );
        })()}

        <div className="card" style={{padding:0}}>
          <table>
            <thead><tr>
              <th style={{width:32,padding:'6px 6px 6px 14px'}}>
                <input type="checkbox" title={'Selecionar até '+MAX_BULK+' visíveis'}
                  checked={selectedIds.size>0 && filtered.every(function(c){ return selectedIds.has(c.id); })}
                  onChange={function(e){ if(e.target.checked) onSelectAllVisible(filtered); else onClearSelection(); }}/>
              </th>
              <th>Nome</th><th>Tipo</th><th>Segmento</th><th>Cidade</th><th>UF</th><th>Telefone</th><th>Canal</th><th>Ações</th>
            </tr></thead>
            <tbody>
              {filtered.map(function(c){
                const saldoAberto = (receivables||[]).filter(function(r){ return r.clientId === c.id && r.status === 'Pendente'; }).reduce(function(s,r){ return s+r.value; }, 0);
                const overLimit = c.creditLimit > 0 && saldoAberto > c.creditLimit;
                const h = clientHealthMap.get(c.id);
                const isSelected = selectedIds.has(c.id);
                const contactedToday = todayOutreachMap.get(c.id);
                const incompleto = (typeof clientesCalcs.isClienteIncompleto === 'function') && clientesCalcs.isClienteIncompleto(c);
                return (
                  <tr key={c.id} style={{background:isSelected?'#FFFBEB':(overLimit?'#FEE2E2':(incompleto?'#FEF9C3':'transparent'))}}>
                    <td style={{padding:'6px 6px 6px 14px'}}>
                      <input type="checkbox" checked={isSelected} onChange={function(){ onToggleSelect(c.id); }} title={contactedToday?'⚠ Já contactado hoje — selecionar mesmo assim?':'Selecionar pra campanha'}/>
                    </td>
                    <td style={{fontWeight:500}}>
                      {h && <span title={'Health Score '+h.score+'/100 — Recência:'+h.recencyPts+' Freq:'+h.frequencyPts+' Valor:'+h.valuePts} style={{display:'inline-block',padding:'2px 7px',borderRadius:10,fontSize:10,fontWeight:700,background:h.color+'20',color:h.color,marginRight:6,verticalAlign:'middle'}}>{h.emoji} {h.score}</span>}
                      {contactedToday && <span title={'✅ Contactado hoje por '+(contactedToday.vendedora_name||'—')} style={{display:'inline-block',padding:'2px 7px',borderRadius:10,fontSize:10,fontWeight:700,background:'#16A34A20',color:'#16A34A',marginRight:6,verticalAlign:'middle'}}>✓ HOJE</span>}
                      {c.name}
                      {overLimit && <span style={{marginLeft:6,fontSize:10,color:'#DC2626',fontWeight:700}}>⚠ LIMITE</span>}
                      {incompleto && <span title="Cliente sem CPF e WhatsApp — completar dados" style={{marginLeft:6,fontSize:10,color:'#92700A',fontWeight:700,background:'#FEF3C7',padding:'2px 6px',borderRadius:4}}>⚠ DADOS INCOMPLETOS</span>}
                    </td>
                    <td><span className={'badge '+(c.type==='PJ'?'badge-blue':'badge-gray')}>{c.type}</span></td>
                    <td><span style={{fontSize:11,color:'#2563EB'}}>{c.segment||'—'}</span></td>
                    <td className="dim">{c.city||'—'}</td>
                    <td><strong style={{fontSize:12}}>{c.state||'—'}</strong></td>
                    <td className="dim">{c.phone||c.whatsapp||'—'}{c.phone&&c.whatsapp&&c.phone!==c.whatsapp&&<span title="Tambem tem WhatsApp diferente" style={{marginLeft:4,fontSize:9,color:'#16A34A'}}>·WA</span>}{!c.phone&&c.whatsapp&&<span title="Telefone vazio — mostrando WhatsApp" style={{marginLeft:4,fontSize:9,color:'#16A34A'}}>WA</span>}</td>
                    <td><span style={{fontSize:11,color:'#9CA3AF'}}>{c.channel||'—'}</span></td>
                    <td>
                      <div style={{display:'flex',gap:6}}>
                        <button className="btn-outline btn-sm" title="Cliente 360º" onClick={function(){ onOpen360(c); }} style={{borderColor:'#C8A951',color:'#92700A'}}>🎯</button>
                        <button className="btn-outline btn-sm" title="Ficha rápida" onClick={function(){ onSetView(c); }}><Icon n="eye" size={12}/></button>
                        <button className="btn-outline btn-sm" title="Editar" onClick={function(){ onSetForm(c); onSetModal('edit'); }}><Icon n="edit" size={12}/></button>
                        <button className="btn-danger btn-sm" title="Excluir" onClick={function(){ onDel(c.id); }}><Icon n="trash" size={12}/></button>
                      </div>
                    </td>
                  </tr>
                );
              })}
              {/* Empty state inteligente */}
              {filtered.length === 0 && (function(){
                const hasFilters = !!(search || filterState || filterSegment);
                return (
                  <tr><td colSpan={9} style={{textAlign:'center',padding:50}}>
                    {hasFilters ? (
                      <>
                        <div style={{fontSize:38,marginBottom:10}}>🔍</div>
                        <div style={{fontSize:15,fontWeight:600,color:'#374151',marginBottom:6}}>Nenhum cliente bate com os filtros</div>
                        <div style={{fontSize:12,color:'#6B7280',marginBottom:14}}>
                          {search && <>Busca: <strong>"{search}"</strong></>}
                          {(search && (filterState||filterSegment)) && ' · '}
                          {filterState && <>Estado: <strong>{filterState}</strong></>}
                          {(filterState && filterSegment) && ' · '}
                          {filterSegment && <>Segmento: <strong>{filterSegment}</strong></>}
                        </div>
                        <button onClick={function(){ setSearch(''); setFilterState(''); setFilterSegment(''); }}
                          style={{padding:'9px 22px',background:'#1B2A4A',color:'#fff',border:'none',borderRadius:6,fontSize:12,fontWeight:600,cursor:'pointer'}}>
                          ↻ Limpar todos os filtros
                        </button>
                      </>
                    ) : visibleClients.length === 0 ? (
                      <>
                        <div style={{fontSize:38,marginBottom:10}}>👥</div>
                        <div style={{fontSize:15,fontWeight:600,color:'#374151',marginBottom:6}}>{user && user.role==='vendedor'?'Você ainda não tem clientes':'Nenhum cliente cadastrado'}</div>
                        <div style={{fontSize:12,color:'#6B7280',marginBottom:14}}>{user && user.role==='vendedor'?'Cadastre seu primeiro cliente pra começar a vender.':'Comece cadastrando o primeiro cliente.'}</div>
                        <button onClick={function(){ onSetForm(EMPTY); onSetModal('new'); }}
                          style={{padding:'9px 22px',background:'#B89840',color:'#fff',border:'none',borderRadius:6,fontSize:12,fontWeight:600,cursor:'pointer'}}>
                          ➕ Cadastrar primeiro cliente
                        </button>
                      </>
                    ) : 'Nenhum cliente encontrado'}
                  </td></tr>
                );
              })()}
            </tbody>
          </table>
        </div>
      </>
    );
  }

  window.ZNX = window.ZNX || {};
  window.ZNX.widgets = window.ZNX.widgets || {};
  window.ZNX.widgets.clientes = window.ZNX.widgets.clientes || {};
  window.ZNX.widgets.clientes.ListaTabView = ListaTabView;
  window.ListaTabViewClientes = ListaTabView; // alias
})();
