// js/components/widgets/marcas/ficha-tabs/VendasClientesSection.jsx
// [Wave 30 v224.11 NUCLEAR EXTRACT 2026-05-24] Tabs vendas + clientes (FichaMarca L343-426)
// Props: tab, m, topClientes, recurringClients, repurchaseRate, concentTop1, filteredSales, brand, products
// Deps lazy: window.fmt, window.isFaturada, window.saleFinalTotal, window.ZNX.marcasHelpers.{brandOf,fmtDateSafe}
(function(){
  'use strict';
  function VendasClientesSection(props){
    var fmt = window.fmt;
    var isFaturada = window.isFaturada;
    var saleFinalTotal = window.saleFinalTotal;
    var MH = window.ZNX && window.ZNX.marcasHelpers;
    var brandOf = MH && MH.brandOf;
    var fmtDateSafe = MH && MH.fmtDateSafe;
    var tab = props.tab;
    var m = props.m;
    var topClientes = props.topClientes;
    var recurringClients = props.recurringClients;
    var repurchaseRate = props.repurchaseRate;
    var concentTop1 = props.concentTop1;
    var filteredSales = props.filteredSales;
    var brand = props.brand;
    var products = props.products;

    if(tab==='vendas'){
      return (
        <div>
          <div style={{display:'grid',gridTemplateColumns:'repeat(3,1fr)',gap:12,marginBottom:14}}>
            <div className="stat-card"><div className="stat-label">Vendas no período</div><div className="stat-value">{m.qtdVendas}</div></div>
            <div className="stat-card"><div className="stat-label">Receita</div><div className="stat-value gold">{fmt(m.receita)}</div></div>
            <div className="stat-card"><div className="stat-label">Lucro</div><div className="stat-value" style={{color:m.lucro>=0?'#15803D':'#B91C1C'}}>{fmt(m.lucro)}</div></div>
          </div>

          {Object.keys(m.formaPagto).length>0&&(
            <div className="card" style={{marginBottom:14}}>
              <div style={{fontWeight:700,color:'#2563EB',marginBottom:10}}>💳 Distribuição por forma de pagamento</div>
              <div style={{display:'flex',flexDirection:'column',gap:6}}>
                {Object.entries(m.formaPagto).sort(function(a,b){return b[1]-a[1];}).map(function(arr){
                  var fp=arr[0], v=arr[1];
                  var pct = m.receita>0?(v/m.receita*100):0;
                  return (
                    <div key={fp} style={{display:'flex',alignItems:'center',gap:10}}>
                      <div style={{width:120,fontSize:12,color:'#374151'}}>{fp}</div>
                      <div style={{flex:1,background:'#F3F4F6',borderRadius:4,height:18,position:'relative',overflow:'hidden'}}>
                        <div style={{position:'absolute',inset:0,background:'#B89840',width:pct+'%'}}/>
                      </div>
                      <div style={{width:90,textAlign:'right',fontSize:12,fontWeight:700,color:'#1B2A4A'}}>{fmt(v)}</div>
                      <div style={{width:50,textAlign:'right',fontSize:12,color:'#9CA3AF'}}>{pct.toFixed(0)}%</div>
                    </div>
                  );
                })}
              </div>
            </div>
          )}

          <div className="card" style={{padding:0}}>
            <div style={{padding:'14px 16px',borderBottom:'1px solid #E4E7EC',fontWeight:700,color:'#2563EB'}}>📜 Histórico de vendas (últimas 50)</div>
            {filteredSales.filter(function(s){return isFaturada(s)&&(s.items||[]).some(function(it){return brandOf(it,products)===brand.name.toUpperCase();});}).slice(0,50).length===0?
              <div style={{padding:20,color:'#9CA3AF',textAlign:'center'}}>Nenhuma venda no período</div>:(
              <table>
                <thead><tr><th>#</th><th>Data</th><th>Cliente</th><th>Vendedora</th><th style={{textAlign:'right'}}>Total venda</th></tr></thead>
                <tbody>
                  {filteredSales.filter(function(s){return isFaturada(s)&&(s.items||[]).some(function(it){return brandOf(it,products)===brand.name.toUpperCase();});}).slice(0,50).map(function(s){
                    return (
                      <tr key={s.id}>
                        <td className="gold" style={{fontSize:12}}>{s.number||'—'}</td>
                        <td className="dim" style={{fontSize:11}}>{fmtDateSafe(s.date)}</td>
                        <td>{s.client||'—'}</td>
                        <td className="dim" style={{fontSize:12}}>{s.sellerName||'—'}</td>
                        <td style={{textAlign:'right',fontWeight:700,color:'#1B2A4A'}}>{fmt(saleFinalTotal(s))}</td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            )}
          </div>
        </div>
      );
    }

    if(tab==='clientes'){
      return (
        <div>
          <div style={{display:'grid',gridTemplateColumns:'repeat(4,1fr)',gap:12,marginBottom:14}}>
            <div className="stat-card"><div className="stat-label">Clientes únicos</div><div className="stat-value">{m.clientesUnicos}</div></div>
            <div className="stat-card"><div className="stat-label">Recorrentes (2+)</div><div className="stat-value" style={{color:'#15803D'}}>{recurringClients}</div></div>
            <div className="stat-card"><div className="stat-label">Repurchase rate</div><div className="stat-value">{repurchaseRate.toFixed(0)}%</div></div>
            <div className="stat-card"><div className="stat-label">Concentração Top 1</div><div className="stat-value" style={{color:concentTop1>=30?'#B91C1C':'#1B2A4A'}}>{concentTop1.toFixed(0)}%</div></div>
          </div>

          <div className="card" style={{padding:0}}>
            <div style={{padding:'14px 16px',borderBottom:'1px solid #E4E7EC',fontWeight:700,color:'#2563EB'}}>👑 Top clientes desta marca</div>
            {topClientes.length===0?<div style={{padding:20,color:'#9CA3AF',textAlign:'center'}}>Sem clientes no período</div>:(
              <table>
                <thead><tr><th>#</th><th>Cliente</th><th style={{textAlign:'right'}}>Pedidos</th><th style={{textAlign:'right'}}>Receita</th><th style={{textAlign:'right'}}>% receita marca</th></tr></thead>
                <tbody>
                  {topClientes.slice(0,30).map(function(c,i){
                    return (
                      <tr key={c.id}>
                        <td className="dim">{i+1}</td>
                        <td style={{fontWeight:600,color:'#1B2A4A'}}>{c.name}</td>
                        <td style={{textAlign:'right'}}>{c.pedidos}</td>
                        <td style={{textAlign:'right'}} className="gold">{fmt(c.receita)}</td>
                        <td style={{textAlign:'right'}}>{m.receita>0?(c.receita/m.receita*100).toFixed(1)+'%':'—'}</td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            )}
          </div>
        </div>
      );
    }

    return null;
  }
  window.ZNX = window.ZNX || {};
  window.ZNX.widgets = window.ZNX.widgets || {};
  window.ZNX.widgets.fichaMarca = window.ZNX.widgets.fichaMarca || {};
  window.ZNX.widgets.fichaMarca.VendasClientesSection = VendasClientesSection;
})();
