// js/components/pages/Relatorio.jsx
// Relatório geral de vendas/financeiro — puro read, sem side-effects
// Extraído de index.html em Fase 6 (2026-04-29): L4868-L5252
// Deps runtime: fmt, fmtDate, saleFinalTotal, itemNet, nid, SmartSelect, RankCard, HistoricoVendedor, RegioesAnalytics
(function() {
  'use strict';
  const {useState, useMemo, useRef} = React;

  // [v224.73 + v224.55] vars+check MOVED to component body (preventivo · regra_validacao_helpers_runtime)

function Relatorio({sales,products,payables,receivables,clients,allUsers,quotes,metas,user,warehouses,gastos}){
  // [v224.73 FIX 2026-05-30] vars+check em render time
  const relatorioCalcs = window.ZNX?.relatorio?.calcs;
  const relatorioAiResumo = window.ZNX?.relatorio?.aiResumo;
  const relatorioExportCsv = window.ZNX?.relatorio?.exportCsv;
  const relatorioExportPdf = window.ZNX?.relatorio?.exportPdf;
  if (!relatorioCalcs || !relatorioAiResumo || !relatorioExportCsv || !relatorioExportPdf) {
    const _msg = `[Relatorio v224.73] bundles faltando: calcs=${!!relatorioCalcs}, aiResumo=${!!relatorioAiResumo}, exportCsv=${!!relatorioExportCsv}, exportPdf=${!!relatorioExportPdf}`;
    console.error(_msg);
    window.Sentry?.captureMessage?.(_msg, 'error');
  }
  // [BUG-FIX 20260518 #619] `gastos` adicionado prop — fonte real de despesas (calcs.js).
  // Antes computePlData lia `payables` Pago que double-contava COGS → lucroLiquido errado.
  // [v214 20260512] user+warehouses props pra aba Produtos (privacy admin vs vendedora + lookup depósito)
  const isAdminPage = !user || user.role==='admin' || user.role==='financeiro';
  const wList = Array.isArray(warehouses) ? warehouses : [];
  const wName = (id)=> wList.find(w=>w.id===id)?.name || '—';
  const[tab,setTab]=useState('geral');
  // [ONDA2-P1 20260511] regra_loading_state_obrigatorio — inflight separado PDF e CSV
  // PDF demora 2-4s; user impaciente clicava 3× e gerava 3 downloads. Ref separado pra
  // CSV permite paralelismo (são exports diferentes).
  const pdfInflightRef=useRef(false);
  const csvInflightRef=useRef(false);
  const[pdfBusy,setPdfBusy]=useState(false);
  const[csvBusy,setCsvBusy]=useState(false);
  const[periodo,setPeriodo]=useState('');
  const[filterVendedor,setFilterVendedor]=useState('');
  const[filterCliente,setFilterCliente]=useState('');
  const[filterMarca,setFilterMarca]=useState('');
  const[filterPagamento,setFilterPagamento]=useState('');
  const[filterStatus,setFilterStatus]=useState('');
  // [REWRITE v115 2026-05-08] Pacote completo Relatório
  const[valorMin,setValorMin]=useState('');
  const[valorMax,setValorMax]=useState('');
  const[sortBy,setSortBy]=useState('profit'); // profit, revenue, date, margin
  const[sortDir,setSortDir]=useState('desc');
  const[viewSale,setViewSale]=useState(null); // venda em drill-down
  const[showResumoIA,setShowResumoIA]=useState(false);

  // [v214 20260512] STATE — aba Produtos (toggle dia/range + filtros + drill-down)
  const _today = () => new Date().toISOString().slice(0,10);
  const _daysAgo = (n) => { const d=new Date(); d.setDate(d.getDate()-n); return d.toISOString().slice(0,10); };
  const[prodMode,setProdMode]=useState(()=>{try{return localStorage.getItem('znx_relprod_mode')||'dia';}catch(_){return'dia';}});
  const[prodDate,setProdDate]=useState(_today);
  const[prodFrom,setProdFrom]=useState(()=>_daysAgo(6));
  const[prodTo,setProdTo]=useState(_today);
  const[prodFilterSeller,setProdFilterSeller]=useState('');
  const[prodFilterMarca,setProdFilterMarca]=useState('');
  const[prodFilterCat,setProdFilterCat]=useState('');
  const[prodFilterDep,setProdFilterDep]=useState('');
  const[prodFilterStatus,setProdFilterStatus]=useState('faturada'); // faturada | todas
  const[prodSortBy,setProdSortBy]=useState('receita');
  const[prodDrillId,setProdDrillId]=useState(null); // ID do produto pro drill-down (regra_state_id_vs_objeto)
  // Persistir modo (regra_workaround_obsoleto_perigoso — preferência do user)
  React.useEffect(()=>{try{localStorage.setItem('znx_relprod_mode',prodMode);}catch(_){}},[prodMode]);

  const meses=useMemo(()=>relatorioCalcs.computeMeses(sales),[sales]);
  // [v224.96 N+1 backlog] clientsById O(1) pra SmartSelect Cliente · evita 1.6M ops em 1538 quotes × 1072 clients
  const clientsById=useMemo(()=>Object.fromEntries((clients||[]).map(c=>[c.id,c])),[clients]);

  function labelMes(m){
    const[y,mo]=m.split('-');
    const n=['Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set','Out','Nov','Dez'];
    return n[parseInt(mo)-1]+'/'+y;
  }

  // BUG-FIX-3: excluir também 'Devolvida (total)' do faturamento (antes só excluía 'Cancelada')
  const fs=useMemo(()=>relatorioCalcs.computeFilteredSales(sales,periodo,filterVendedor,filterCliente,filterMarca,filterPagamento,products,clients),[sales,periodo,filterVendedor,filterCliente,filterMarca,filterPagamento,products,clients]);

  const revenue=fs.reduce((s,v)=>s+saleFinalTotal(v),0);
  const profit=fs.reduce((s,v)=>s+saleProfit(v.items,products),0);
  const margin=revenue?(profit/revenue*100):0;
  function pct(n){return n.toFixed(1)+'%'}

  // ── NOTAS ──────────────────────────────────────────────────
  const notasData=useMemo(()=>relatorioCalcs.computeNotasData(fs,products,clients),[fs,products,clients]);

  // ── CLIENTES ────────────────────────────────────────────────
  const clientData=useMemo(()=>relatorioCalcs.computeClientData(fs,products,clients),[fs,products,clients]);

  // ── MARCAS ──────────────────────────────────────────────────
  const brandData=useMemo(()=>relatorioCalcs.computeBrandData(fs,products),[fs,products]);

  // ── EVOLUÇÃO MENSAL ─────────────────────────────────────────
  const monthlyData=useMemo(()=>relatorioCalcs.computeMonthlyData(sales,products),[sales,products]);

  const maxMrev=Math.max(...monthlyData.map(x=>x.revenue),1);

  const TABS=[
    {id:'geral',label:'📊 Visão Geral'},
    {id:'notas',label:'🧾 Por Nota'},
    {id:'produtos',label:'📦 Produtos'},
    {id:'clientes',label:'👥 Clientes'},
    {id:'periodo',label:'📋 Linha do Tempo'},
    {id:'pl',label:'💰 P&L Executivo'},
  ];

  // ── [v214.1 hotfix 20260512] prodBaseSales = filtros de ESCOPO apenas (período+status+vendedora)
  // Usado pra derivar opts dos dropdowns ANTES dos filtros marca/cat/dep → permite trocar
  // entre marcas sem zerar (fix dropdown circular auditado em v214).
  // [v224.92 PERF 2026-05-31] guards tab=== em 8 useMemos · lazy compute
  // 2 ABORTs (v224.92, v224.92.1) calibraram esta forma: guards + null-safety L124-129
  const prodBaseSales = useMemo(()=>tab==='produtos'?relatorioCalcs.computeProdBaseSales(sales,prodMode,prodDate,prodFrom,prodTo,prodFilterStatus,prodFilterSeller):null,[tab,sales,prodMode,prodDate,prodFrom,prodTo,prodFilterStatus,prodFilterSeller]);

  // ── [v214 20260512] AGREGAÇÃO Produtos Vendidos por dia/range ─────────
  // Privacy: `sales` prop já vem filtrado por role (vendedora só vê dela em App.jsx).
  // Devoluções: subtrai it.returned_qty se houver. Cliente top: produto comprado por quem.
  // Receita líquida: rateia desconto global proporcional à linha (regra_jsonb_item_name_aliases fallback 4-níveis).
  const prodAggrData = useMemo(()=>tab==='produtos' && prodBaseSales?relatorioCalcs.computeProdAggrData(prodBaseSales,products,clients,prodFilterMarca,prodFilterCat,prodFilterDep,prodSortBy):null,[tab,prodBaseSales,products,clients,prodFilterMarca,prodFilterCat,prodFilterDep,prodSortBy]);

  // [v214.1 hotfix 20260512] Removido `vendas:new Set()` + Set.add(...spread).
  // Set.add() aceita só 1 arg, spread quebrava silencioso. Campo não usado no JSX.
  const prodTotaisFooter = useMemo(()=>tab==='produtos' && prodAggrData?relatorioCalcs.computeProdTotaisFooter(prodAggrData):null,[tab,prodAggrData]);

  // [v214.1 hotfix 20260512] Opts derivam de prodBaseSales (ANTES de filtros marca/cat/dep)
  // → trocar marca não esconde outras opções (fix dropdown circular).
  const prodOptsRaw = useMemo(()=>tab==='produtos' && prodBaseSales?relatorioCalcs.computeProdOptsRaw(prodBaseSales,products):null,[tab,prodBaseSales,products]);
  // [v224.92 null-safe] derivados rodam INCONDICIONAL no top · fallback safe quando guard retorna null
  const prodMarcasOpts = prodOptsRaw?.marcas || [];
  const prodCatOpts = prodOptsRaw?.cats || [];
  // prodSellerOpts mantido global (admin escolhe entre todas vendedoras do histórico) — não afeta circular
  const prodSellerOpts = useMemo(()=>tab==='produtos'?relatorioCalcs.computeProdSellerOpts(sales):null,[tab,sales]);
  const prodMaxRev = prodAggrData ? Math.max(...prodAggrData.slice(0,10).map(p=>p.totalRevenue),1) : 1;
  const prodDrill = (prodDrillId && prodAggrData) ? prodAggrData.find(p=>p.id===prodDrillId) : null;


  // ── [v115 D] Linha do Tempo Financeira — eventos cronológicos ──
  const linhaDoTempo = useMemo(()=>tab==='periodo'?relatorioCalcs.computeLinhaDoTempo(fs,payables,receivables,periodo,clients):null,[tab,fs,payables,receivables,periodo,clients]);

  // ── [v115 E] P&L Executivo — DRE simplificado ──
  // [BUG-FIX 20260518 #619] swap `payables` → `gastos` — fonte real de despesas (não double-conta COGS)
  const plData = useMemo(()=>relatorioCalcs.computePlData(fs,products,metas,gastos,periodo),[fs,products,metas,gastos,periodo]);

  // [Bug #615 20260518] Breakdown gastos por categoria — usado em tab='pl' P&L Executivo
  const gastosPorCategoria = useMemo(()=>tab==='pl'?relatorioCalcs.computeGastosPorCategoria(gastos,periodo):null,[tab,gastos,periodo]);

  // ── [v115 C] Sparkline 6m e dados transacionais por cliente ──
  // [v224.92 PERF] clientDataExt detectado como DEAD CODE (zero consumers · CC ABORT 2 grep) · guard mesmo assim · cleanup futuro v224.95+
  const clientDataExt = useMemo(()=>tab==='clientes'?relatorioCalcs.computeClientDataExt(clientData,sales,clients):null,[tab,clientData,sales,clients]);

  // ── [v115 F1] Resumo Executivo Narrativo ──
  function gerarResumoIA(){
    const periodoLabel=periodo?labelMes(periodo):'todo o histórico';
    return relatorioAiResumo.gerarResumoIA({periodoLabel,fs,plData,clientData,brandData});
  }

  // ── [v115 F2] Export pro Contador (CSV padrão BR) ──
  function exportContadorCSV(){
    // [ONDA2-P1 20260511] inflight guard — evita gerar CSV 2× em duplo-click rápido
    if(csvInflightRef.current)return;
    csvInflightRef.current=true;setCsvBusy(true);
    try{
      relatorioExportCsv.exportContadorCSV({fs,clients,periodo});
    }finally{
      csvInflightRef.current=false;setCsvBusy(false);
    }
  }

  // ── [v115 F3] PDF Imprimível Premium do período ──
  async function exportPDFExecutivo(){
    // [ONDA2-P1 20260511] inflight guard — PDF demora 2-4s, user impaciente
    // clicava várias vezes e gerava múltiplos downloads idênticos.
    if(pdfInflightRef.current)return;
    pdfInflightRef.current=true;setPdfBusy(true);
    try{
      const periodoLabel=periodo?labelMes(periodo):'Histórico completo';
      await relatorioExportPdf.exportPDFExecutivo({fs,plData,clientData,brandData,periodo,periodoLabel});
    }finally{
      pdfInflightRef.current=false;setPdfBusy(false);
    }
  }

  return(
    <div>
      {/* Header com botões inteligentes [v115] */}
      <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:20,flexWrap:'wrap',gap:10}}>
        {/* [L2-Relatorio 2026-05-09] Title com contador de vendas filtradas + label do período */}
        <div className="page-title">
          Relatório
          {(() => {
            const hasFilters=!!(periodo||filterVendedor||filterCliente||filterMarca||filterPagamento||filterStatus);
            const totalSales=(sales||[]).filter(s=>s.status!=='Cancelada'&&s.status!=='Cancelado').length;
            return hasFilters
              ? <span style={{fontSize:13,color:'#B89840',fontWeight:600,marginLeft:8}}>({fs.length} de {totalSales} vendas{periodo?` · ${labelMes(periodo)}`:''})</span>
              : <span style={{fontSize:13,color:'#9CA3AF',fontWeight:400,marginLeft:8}}>({totalSales} vendas · todos períodos)</span>;
          })()}
        </div>
        <div style={{display:'flex',gap:8,alignItems:'center',flexWrap:'wrap'}}>
          <button onClick={()=>setShowResumoIA(true)} title="Gera texto narrativo do período (envia pra WhatsApp/copia)"
            style={{padding:'8px 14px',border:'1px solid #B89840',background:'linear-gradient(135deg,#FEF9E7,#FFFBEB)',color:'#92700A',borderRadius:8,fontSize:12,fontWeight:700,cursor:'pointer'}}>
            🤖 Resumo Executivo
          </button>
          <button onClick={exportContadorCSV} disabled={csvBusy} title="Planilha padrão pra contador (CSV BR com BOM UTF-8)"
            style={{padding:'8px 14px',border:'1px solid #16A34A',background:'#F0FDF4',color:'#15803D',borderRadius:8,fontSize:12,fontWeight:700,cursor:csvBusy?'not-allowed':'pointer',opacity:csvBusy?0.6:1}}>
            {csvBusy?'⏳ Gerando…':'📊 Export Contador'}
          </button>
          <button onClick={exportPDFExecutivo} disabled={pdfBusy} title="PDF formatado pra apresentar/imprimir"
            style={{padding:'8px 14px',border:'1px solid #DC2626',background:'#FEF2F2',color:'#B91C1C',borderRadius:8,fontSize:12,fontWeight:700,cursor:pdfBusy?'not-allowed':'pointer',opacity:pdfBusy?0.6:1}}>
            {pdfBusy?'⏳ Gerando PDF…':'📄 PDF Executivo'}
          </button>
          <SmartSelect width={200} value={periodo} onChange={setPeriodo} placeholder="Todos os períodos" options={[{value:'',label:'Todos os períodos'},...meses.map(m=>({value:m,label:labelMes(m)}))]}/>
        </div>
      </div>
      {/* Filtros avancados */}
      <div style={{display:'flex',gap:8,marginBottom:16,flexWrap:'wrap',alignItems:'center'}}>
        <SmartSelect width={160} value={filterVendedor} onChange={setFilterVendedor} placeholder="Vendedor" options={[{value:'',label:'Todos vendedores'},...[...new Set(sales.map(s=>s.sellerName).filter(Boolean))].sort().map(v=>({value:v,label:v}))]}/>
        <SmartSelect width={180} value={filterCliente} onChange={setFilterCliente} placeholder="Cliente" options={[{value:'',label:'Todos clientes'},...[...new Map(sales.map(s=>[s.clientId,s.client||s.clientName||(clientsById[s.clientId]?.name)||'']).filter(([id,n])=>n)).values()].filter(Boolean).sort().slice(0,50).map(v=>({value:v,label:v}))]}/>
        <SmartSelect width={150} value={filterMarca} onChange={setFilterMarca} placeholder="Marca" options={[{value:'',label:'Todas marcas'},...[...new Set(products.map(p=>p.brand||extractBrand(p.name)).filter(Boolean))].sort().map(v=>({value:v,label:v}))]}/>
        <SmartSelect width={140} value={filterPagamento} onChange={setFilterPagamento} placeholder="Pagamento" options={[{value:'',label:'Todas formas'},...['Pix','Dinheiro','Cartao','Boleto','Transferencia'].map(v=>({value:v,label:v}))]}/>
        {(filterVendedor||filterCliente||filterMarca||filterPagamento)&&<button className="btn-outline" onClick={()=>{setFilterVendedor('');setFilterCliente('');setFilterMarca('');setFilterPagamento('');}} style={{fontSize:11,padding:'4px 10px'}}>Limpar filtros</button>}
      </div>

      {/* Tabs */}
      <div style={{display:'flex',gap:6,marginBottom:20,flexWrap:'wrap'}}>
        {TABS.map(t=><button key={t.id} className={tab===t.id?'btn-gold':'btn-outline'} style={{fontSize:13}} onClick={()=>setTab(t.id)}>{t.label}</button>)}
      </div>

      {/* ── VISÃO GERAL ── [v118] CEO mode: features únicas só */}
      {tab==='geral'&&(
        <>
          {/* [NOVO v118] Banner Resumo Executivo INLINE — versão curta sempre visível
              (modal F1 fica disponível pra texto completo + WhatsApp). Aqui é o digest. */}
          {(()=>{
            const periodoLbl=periodo?labelMes(periodo):'todo o histórico';
            const topVend=Object.entries(plData.vendedoresPeriodo||{}).sort((a,b)=>b[1]-a[1])[0];
            const topCli=clientData[0];
            const topMrc=brandData[0];
            const concentRisco = topCli && plData.receitaBruta>0 ? (topCli.total/plData.receitaBruta)*100 : 0;
            return(
              <div style={{background:'linear-gradient(135deg,#0F1B36,#1B2A4A)',borderRadius:14,padding:'20px 24px',marginBottom:18,position:'relative',overflow:'hidden'}}>
                <div style={{position:'absolute',top:0,left:0,bottom:0,width:5,background:'#B89840'}}/>
                <div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-start',flexWrap:'wrap',gap:12}}>
                  <div style={{flex:1,minWidth:280}}>
                    <div style={{fontSize:10,color:'#B89840',fontWeight:700,letterSpacing:2,textTransform:'uppercase',marginBottom:4}}>📊 Resumo Executivo · {periodoLbl}</div>
                    <div style={{fontSize:14,color:'#FEF9E7',lineHeight:1.6}}>
                      Faturamento bruto <strong style={{color:'#B89840'}}>{fmt(plData.receitaBruta)}</strong> com lucro líquido <strong style={{color:plData.lucroLiquido>=0?'#22C55E':'#FCA5A5'}}>{fmt(plData.lucroLiquido)}</strong> ({plData.margemLiquidaPct.toFixed(1)}% margem). {fs.length} notas · ticket médio {fmt(fs.length?plData.receitaBruta/fs.length:0)}.
                      {topVend && <span> Top vendedora: <strong style={{color:'#FEF9E7'}}>{topVend[0]}</strong>.</span>}
                      {topCli && <span> Top cliente: <strong style={{color:'#FEF9E7'}}>{topCli.name}</strong>.</span>}
                    </div>
                    {concentRisco>=30&&(
                      <div style={{marginTop:10,padding:'8px 12px',background:'rgba(220,38,38,0.2)',borderLeft:'3px solid #DC2626',borderRadius:4,fontSize:12,color:'#FCA5A5'}}>
                        ⚠️ Concentração de risco: <strong>{topCli.name}</strong> = {concentRisco.toFixed(0)}% do faturamento — diversificar
                      </div>
                    )}
                  </div>
                  <button onClick={()=>setShowResumoIA(true)} style={{padding:'8px 14px',background:'rgba(184,152,64,0.15)',border:'1px solid #B89840',color:'#B89840',borderRadius:8,fontSize:12,fontWeight:700,cursor:'pointer',whiteSpace:'nowrap'}}>
                    📋 Texto completo →
                  </button>
                </div>
              </div>
            );
          })()}

          {/* KPIs com 5º Saldo Cash — único do Relatório (transacional) */}
          {(()=>{
            const recPend=(receivables||[]).filter(r=>r.status==='Pendente').reduce((a,r)=>a+(Number(r.value)||0),0);
            const pagPend=(payables||[]).filter(p=>p.status==='Pendente').reduce((a,p)=>a+(Number(p.value)||0),0);
            const saldoCash=recPend-pagPend;
            return(
              <div style={{display:'grid',gridTemplateColumns:'repeat(6,1fr)',gap:12,marginBottom:18}}>
                <div className="stat-card" style={{borderLeft:'4px solid #B89840'}}><div className="stat-label">Faturamento</div><div className="stat-value" style={{color:'#92700A'}}>{fmt(revenue)}</div></div>
                {/* [BUG-FIX 20260518 #619] Card "Lucro Bruto" = Receita − COGS (saleProfit). Era "Lucro Líquido" com label errado. */}
                {/* [Hotfix v223.13.2 20260518] Card "Lucro Bruto" usa plData.margemBruta (factory unificada v223.13.1).
                    Antes: `profit` (saleProfit simples = R$ 231k) NÃO deduzia globalDisc/credit → math não fechava com DRE/Líquido.
                    Agora bate byte-by-byte com Margem Bruta DRE Compacto L354 + Tab P&L L739 + Dashboard "bruto". */}
                <div className="stat-card" style={{borderLeft:'4px solid #15803D'}}><div className="stat-label">Lucro Bruto</div><div className="stat-value" style={{color:'#15803D'}}>{fmt(plData.margemBruta)}</div><div style={{fontSize:10,color:'#9CA3AF',marginTop:2}}>Receita − CMV − Desc. Globais − Crédito</div></div>
                {/* [BUG-FIX 20260518 #619] Card "Lucro Líquido" REAL = Margem Bruta − Despesas (gastos). Antes mostrava bruto. */}
                <div className="stat-card" style={{borderLeft:'4px solid '+(plData.lucroLiquido>=0?'#16A34A':'#DC2626')}}><div className="stat-label">Lucro Líquido</div><div className="stat-value" style={{color:plData.lucroLiquido>=0?'#16A34A':'#DC2626'}}>{fmt(plData.lucroLiquido)}</div><div style={{fontSize:10,color:'#9CA3AF',marginTop:2}}>Bruto − Gastos</div></div>
                {/* [BUG-FIX 20260518 #619] Margem agora reflete LÍQUIDA (era BRUTA com label "Geral"). */}
                <div className="stat-card" style={{borderLeft:'4px solid '+(plData.margemLiquidaPct>=15?'#16A34A':plData.margemLiquidaPct>=5?'#2563EB':'#DC2626')}}><div className="stat-label">Margem Líquida</div><div className="stat-value" style={{color:plData.margemLiquidaPct>=15?'#16A34A':plData.margemLiquidaPct>=5?'#2563EB':'#DC2626'}}>{plData.margemLiquidaPct.toFixed(1)}%</div><div style={{fontSize:10,color:'#9CA3AF',marginTop:2}}>Bruta {plData.margemBrutaPct.toFixed(1)}%</div></div>
                <div className="stat-card"><div className="stat-label">Notas Emitidas</div><div className="stat-value">{fs.length}</div><div style={{fontSize:11,color:'#9CA3AF',marginTop:2}}>Ticket {fmt(fs.length?revenue/fs.length:0)}</div></div>
                <div className="stat-card" style={{borderLeft:'4px solid '+(saldoCash>=0?'#16A34A':'#DC2626')}}>
                  <div className="stat-label">💵 Saldo Cash</div>
                  <div className="stat-value" style={{color:saldoCash>=0?'#16A34A':'#DC2626'}}>{saldoCash>=0?'+':''}{fmt(saldoCash)}</div>
                  <div style={{fontSize:11,color:'#9CA3AF',marginTop:2}}>Receber {fmt(recPend)} − Pagar {fmt(pagPend)}</div>
                </div>
              </div>
            );
          })()}

          {!periodo&&monthlyData.length>0&&(
            <div className="card" style={{marginBottom:20}}>
              <div style={{fontWeight:700,fontSize:14,color:'#2563EB',marginBottom:16}}>📈 Evolução Mensal</div>
              <div style={{display:'flex',alignItems:'flex-end',gap:8,height:110}}>
                {monthlyData.map(m=>{
                  const rh=Math.round(m.revenue/maxMrev*80);
                  const ph=Math.round(m.profit/maxMrev*80);
                  return(
                    <div key={m.mes} style={{flex:1,display:'flex',flexDirection:'column',alignItems:'center',gap:3}}>
                      <span style={{fontSize:9,color:'#2563EB',whiteSpace:'nowrap'}}>{fmt(m.revenue)}</span>
                      <div style={{width:'100%',position:'relative',height:80,display:'flex',alignItems:'flex-end'}}>
                        <div style={{position:'absolute',bottom:0,width:'100%',height:rh,background:'#2a2010',borderRadius:'3px 3px 0 0'}}/>
                        <div style={{position:'absolute',bottom:0,width:'100%',height:ph,background:'linear-gradient(180deg,#16A34A99,#16A34A33)',borderRadius:'3px 3px 0 0'}}/>
                        <div style={{position:'absolute',bottom:0,width:'100%',height:rh,background:'linear-gradient(180deg,#2563EB99,#2563EB33)',borderRadius:'3px 3px 0 0'}}/>
                      </div>
                      <span style={{fontSize:9,color:'#9CA3AF',whiteSpace:'nowrap'}}>{labelMes(m.mes)}</span>
                      <span style={{fontSize:9,color:'#16A34A',whiteSpace:'nowrap'}}>{fmt(m.profit)}</span>
                    </div>
                  );
                })}
              </div>
              <div style={{display:'flex',gap:16,marginTop:6,fontSize:11,color:'#9CA3AF'}}>
                <span>🟡 Faturamento &nbsp; 🟢 Lucro</span>
              </div>
            </div>
          )}

          {/* [NOVO v118] Top 5 vendas mais lucrativas + DRE compacto (peeks únicos do Relatório) */}
          <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:20,marginBottom:20}}>
            <div className="card">
              <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:12}}>
                <div style={{fontWeight:700,color:'#2563EB'}}>🏆 Top 5 Vendas Mais Lucrativas</div>
                <button onClick={()=>setTab('notas')} style={{background:'none',border:'none',color:'#9CA3AF',fontSize:11,cursor:'pointer',textDecoration:'underline'}}>Ver todas →</button>
              </div>
              {notasData.slice(0,5).map((s,i)=>(
                <div key={s.id} style={{display:'flex',justifyContent:'space-between',alignItems:'center',padding:'8px 0',borderBottom:'1px solid #F3F4F6',fontSize:12}}>
                  <div style={{flex:1,minWidth:0}}>
                    <div style={{fontWeight:600,color:'#1B2A4A'}}>{s.number||'—'} · {s.clientName}</div>
                    <div style={{fontSize:10,color:'#9CA3AF',marginTop:1}}>{fmtDate(s.date)} · {s.sellerName||'—'}</div>
                  </div>
                  <div style={{textAlign:'right',minWidth:140}}>
                    <div style={{color:'#16A34A',fontWeight:700}}>{fmt(s.profit)}</div>
                    <div style={{fontSize:10,color:'#9CA3AF'}}>{fmt(s.revenue)} · {pct(s.margin)}</div>
                  </div>
                </div>
              ))}
              {/* [L2-Relatorio 2026-05-09] Empty state melhor com CTA */}
              {notasData.length===0&&(
                <div style={{textAlign:'center',padding:'40px 20px'}}>
                  <div style={{fontSize:32,marginBottom:8}}>📊</div>
                  <div style={{fontSize:13,fontWeight:600,color:'#374151',marginBottom:4}}>Nenhuma venda no período/filtros</div>
                  <div style={{fontSize:11,color:'#9CA3AF',marginBottom:10}}>Ajuste o período ou limpe os filtros pra ver dados.</div>
                  {(periodo||filterVendedor||filterCliente||filterMarca||filterPagamento)&&(
                    <button onClick={()=>{setPeriodo('');setFilterVendedor('');setFilterCliente('');setFilterMarca('');setFilterPagamento('');}}
                      style={{padding:'7px 16px',background:'#1B2A4A',color:'#fff',border:'none',borderRadius:6,fontSize:12,fontWeight:600,cursor:'pointer'}}>
                      ↻ Limpar todos os filtros
                    </button>
                  )}
                </div>
              )}
            </div>

            <div className="card">
              <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:12}}>
                <div style={{fontWeight:700,color:'#2563EB'}}>💰 DRE Compacto</div>
                <button onClick={()=>setTab('pl')} style={{background:'none',border:'none',color:'#9CA3AF',fontSize:11,cursor:'pointer',textDecoration:'underline'}}>Ver completo →</button>
              </div>
              <table style={{width:'100%',fontSize:12}}>
                <tbody>
                  <tr><td style={{padding:'5px 0',color:'#374151'}}>Receita Bruta</td><td style={{padding:'5px 0',textAlign:'right',fontWeight:600}}>{fmt(plData.receitaBruta)}</td></tr>
                  <tr><td style={{padding:'5px 0',color:'#DC2626',fontSize:11}}>(-) CMV</td><td style={{padding:'5px 0',textAlign:'right',color:'#DC2626',fontSize:11}}>-{fmt(plData.cmv)}</td></tr>
                  <tr style={{background:'#F0FDF4'}}><td style={{padding:'7px 0',fontWeight:700,color:'#15803D'}}>= Margem Bruta</td><td style={{padding:'7px 0',textAlign:'right',fontWeight:700,color:'#15803D'}}>{fmt(plData.margemBruta)} <span style={{fontSize:10}}>({plData.margemBrutaPct.toFixed(1)}%)</span></td></tr>
                  {/* [BUG-FIX 20260518 #619] Removida linha "(-) Comissões" — agora INFO derivada, já inclusa em Despesas quando admin paga via Folha. Bate com SQL Cowork. */}
                  <tr><td style={{padding:'5px 0',color:'#EA580C',fontSize:11}}>(-) Despesas (Gastos)</td><td style={{padding:'5px 0',textAlign:'right',color:'#EA580C',fontSize:11}}>-{fmt(plData.despesas)}</td></tr>
                  <tr style={{background:plData.lucroLiquido>=0?'#0F1B36':'#7F1D1D',color:'#fff'}}>
                    <td style={{padding:'10px 0 10px 8px',fontWeight:800,color:'#B89840',fontSize:12}}>= LUCRO LÍQUIDO</td>
                    <td style={{padding:'10px 8px 10px 0',textAlign:'right',fontWeight:800,color:'#fff',fontSize:13}}>{fmt(plData.lucroLiquido)} <span style={{color:'#B89840',fontSize:11}}>({plData.margemLiquidaPct.toFixed(1)}%)</span></td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>

          {/* Top Clientes + Top Marcas (já existia, mantido) */}
          <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:20}}>
            <div className="card">
              <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:12}}>
                <div style={{fontWeight:700,color:'#2563EB'}}>👥 Top Clientes</div>
                <button onClick={()=>setTab('clientes')} style={{background:'none',border:'none',color:'#9CA3AF',fontSize:11,cursor:'pointer',textDecoration:'underline'}}>Ver todos →</button>
              </div>
              {clientData.slice(0,8).map((c,i)=>(
                <div key={c.name} style={{display:'flex',justifyContent:'space-between',alignItems:'center',padding:'7px 0',borderBottom:'1px solid #F3F4F6',fontSize:13}}>
                  <span><span style={{color:'#9CA3AF',fontSize:11,marginRight:6}}>#{i+1}</span>{c.name}</span>
                  <div style={{textAlign:'right'}}>
                    <div className="gold">{fmt(c.total)}</div>
                    <div style={{fontSize:11,color:'#9CA3AF'}}>{c.pedidos} pedido{c.pedidos!==1?'s':''}</div>
                  </div>
                </div>
              ))}
            </div>
            <div className="card">
              <div style={{fontWeight:700,color:'#2563EB',marginBottom:12}}>🏷️ Top Marcas</div>
              {brandData.slice(0,8).map((b,i)=>(
                <div key={b.brand} style={{display:'flex',justifyContent:'space-between',alignItems:'center',padding:'7px 0',borderBottom:'1px solid #F3F4F6',fontSize:13}}>
                  <span><span style={{color:'#9CA3AF',fontSize:11,marginRight:6}}>#{i+1}</span>{b.brand}</span>
                  <div style={{textAlign:'right'}}>
                    <div className="gold">{fmt(b.revenue)}</div>
                    <div style={{fontSize:11,color:'#16A34A'}}>L: {fmt(b.profit)}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </>
      )}

      {/* ── POR NOTA ── */}
      {tab==='notas'&&(
        <div className="card" style={{padding:0}}>
          <div style={{padding:'14px 16px',borderBottom:'1px solid #E4E7EC',display:'flex',justifyContent:'space-between',alignItems:'center'}}>
            <span style={{fontWeight:700,color:'#2563EB'}}>🧾 Lucro por Nota</span>
            {/* [Hotfix v223.13.2 20260518] Header Notas usa plData.margemBruta + margemBrutaPct (factory unificada). */}
            <span style={{fontSize:12,color:'#9CA3AF'}}>{notasData.length} notas · Total: {fmt(revenue)} · Lucro: {fmt(plData.margemBruta)} · Margem: {pct(plData.margemBrutaPct)}</span>
          </div>
          <div style={{overflowX:'auto'}}>
            <table>
              <thead><tr><th>#</th><th>Data</th><th>Cliente</th><th>Vendedor</th><th>Faturamento</th><th>Custo</th><th>Lucro</th><th>Margem</th></tr></thead>
              <tbody>
                {notasData.map(s=>(
                  <tr key={s.id}>
                    <td className="gold" style={{fontSize:12}}>{s.number||'—'}</td>
                    <td className="dim" style={{fontSize:12}}>{fmtDate(s.date)}</td>
                    <td style={{maxWidth:160,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap',fontSize:13}}>{s.clientName}</td>
                    <td className="dim" style={{fontSize:11}}>{s.sellerName||'—'}</td>
                    <td>{fmt(s.revenue)}</td>
                    <td className="dim">{fmt(s.revenue-s.profit)}</td>
                    <td style={{color:'#16A34A',fontWeight:600}}>{fmt(s.profit)}</td>
                    <td>
                      <span style={{padding:'2px 8px',borderRadius:10,fontSize:12,fontWeight:700,
                        background:s.margin>=30?'#1a3a1a':s.margin>=15?'#3a2a00':'#3a0000',
                        color:s.margin>=30?'#16A34A':s.margin>=15?'#2563EB':'#DC2626'
                      }}>{pct(s.margin)}</span>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* ── CLIENTES ── */}
      {tab==='clientes'&&(
        <div className="card" style={{padding:0}}>
          <div style={{padding:'14px 16px',borderBottom:'1px solid #E4E7EC',fontWeight:700,color:'#2563EB'}}>👥 Rendimento por Cliente</div>
          <div style={{overflowX:'auto'}}>
            <table>
              <thead><tr><th>#</th><th>Cliente</th><th>Pedidos</th><th>Faturamento</th><th>% do Total</th><th>Lucro</th><th>Margem</th><th>Ticket Médio</th></tr></thead>
              <tbody>
                {clientData.map((c,i)=>{
                  const mg=c.total?(c.profit/c.total*100):0;
                  const share=revenue?(c.total/revenue*100):0;
                  return(
                    <tr key={c.name}>
                      <td className="dim" style={{fontSize:12}}>#{i+1}</td>
                      <td style={{fontWeight:500}}>{c.name}</td>
                      <td>{c.pedidos}</td>
                      <td className="gold">{fmt(c.total)}</td>
                      <td>
                        <div style={{display:'flex',alignItems:'center',gap:6}}>
                          <span style={{fontSize:12,minWidth:38}}>{share.toFixed(1)}%</span>
                          <div style={{background:'#F9FAFB',borderRadius:3,height:6,width:60,overflow:'hidden'}}>
                            <div style={{height:'100%',background:'#2563EB',borderRadius:3,width:`${share}%`}}/>
                          </div>
                        </div>
                      </td>
                      <td style={{color:'#16A34A'}}>{fmt(c.profit)}</td>
                      <td><span style={{padding:'2px 8px',borderRadius:10,fontSize:12,fontWeight:700,
                        background:mg>=30?'#1a3a1a':mg>=15?'#3a2a00':'#3a0000',
                        color:mg>=30?'#16A34A':mg>=15?'#2563EB':'#DC2626'
                      }}>{pct(mg)}</span></td>
                      <td className="dim">{fmt(c.pedidos?c.total/c.pedidos:0)}</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* [v115 D] LINHA DO TEMPO FINANCEIRA — eventos cronológicos */}
      {tab==='periodo'&&(
        <div className="card" style={{padding:0}}>
          <div style={{padding:'14px 16px',borderBottom:'1px solid #E4E7EC',display:'flex',justifyContent:'space-between',alignItems:'center',flexWrap:'wrap',gap:8}}>
            <span style={{fontWeight:700,color:'#2563EB'}}>📋 Linha do Tempo Financeira</span>
            <span style={{fontSize:12,color:'#9CA3AF'}}>{linhaDoTempo.length} eventos · Saldo: <strong style={{color:linhaDoTempo[0]?.saldoAcumulado>=0?'#16A34A':'#DC2626'}}>{fmt(linhaDoTempo[0]?.saldoAcumulado||0)}</strong></span>
          </div>
          {linhaDoTempo.length===0?(
            <div style={{padding:40,textAlign:'center',color:'#9CA3AF'}}>Nenhum evento financeiro no período</div>
          ):(
            <div style={{maxHeight:600,overflowY:'auto'}}>
              <table>
                <thead><tr style={{position:'sticky',top:0,background:'#fff',zIndex:1}}>
                  <th>Data</th>
                  <th>Tipo</th>
                  <th>Descrição</th>
                  <th style={{textAlign:'right'}}>Valor</th>
                  <th style={{textAlign:'right'}}>Saldo</th>
                </tr></thead>
                <tbody>
                  {linhaDoTempo.map((e,i)=>(
                    <tr key={i} style={{background:e.type==='venda'?'#F0FDF4':e.type==='despesa'?'#FEF2F2':'#EFF6FF'}}>
                      <td className="dim" style={{fontSize:12,whiteSpace:'nowrap'}}>{fmtDate(e.date)}</td>
                      <td><span style={{fontSize:14,marginRight:4}}>{e.icon}</span><span style={{fontSize:11,color:'#6B7280'}}>{e.type}</span></td>
                      <td style={{fontSize:13}}>{e.descricao}</td>
                      <td style={{textAlign:'right',fontWeight:700,color:e.sinal==='+'?'#16A34A':'#DC2626'}}>{e.sinal}{fmt(e.valor)}</td>
                      <td style={{textAlign:'right',fontSize:11,color:e.saldoAcumulado>=0?'#374151':'#DC2626',fontWeight:600}}>{fmt(e.saldoAcumulado)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      )}

      {/* [v214 20260512] ABA PRODUTOS — toggle dia/range + filtros + drill-down + devoluções */}
      {tab==='produtos'&&(
        <div>
          {/* Toolbar período + filtros */}
          <div className="card" style={{padding:'14px 16px',marginBottom:14,display:'flex',flexWrap:'wrap',gap:10,alignItems:'center'}}>
            <div style={{display:'inline-flex',background:'#F3F4F6',borderRadius:8,padding:3}}>
              <button onClick={()=>setProdMode('dia')} style={{padding:'6px 14px',border:'none',borderRadius:6,fontSize:12,fontWeight:700,cursor:'pointer',background:prodMode==='dia'?'#B89840':'transparent',color:prodMode==='dia'?'#fff':'#6B7280'}}>📅 Dia único</button>
              <button onClick={()=>setProdMode('range')} style={{padding:'6px 14px',border:'none',borderRadius:6,fontSize:12,fontWeight:700,cursor:'pointer',background:prodMode==='range'?'#B89840':'transparent',color:prodMode==='range'?'#fff':'#6B7280'}}>📊 Período</button>
            </div>
            {prodMode==='dia'?(
              <input type="date" value={prodDate} onChange={e=>setProdDate(e.target.value)} style={{padding:'6px 10px',border:'1px solid #D1D5DB',borderRadius:6,fontSize:13}}/>
            ):(
              <>
                <input type="date" value={prodFrom} onChange={e=>setProdFrom(e.target.value)} style={{padding:'6px 10px',border:'1px solid #D1D5DB',borderRadius:6,fontSize:13}}/>
                <span style={{color:'#9CA3AF',fontSize:13}}>até</span>
                <input type="date" value={prodTo} onChange={e=>setProdTo(e.target.value)} style={{padding:'6px 10px',border:'1px solid #D1D5DB',borderRadius:6,fontSize:13}}/>
                <button onClick={()=>{setProdFrom(_today());setProdTo(_today());}} style={{padding:'5px 10px',background:'#F3F4F6',border:'1px solid #D1D5DB',borderRadius:6,fontSize:11,cursor:'pointer'}}>Hoje</button>
                <button onClick={()=>{setProdFrom(_daysAgo(6));setProdTo(_today());}} style={{padding:'5px 10px',background:'#F3F4F6',border:'1px solid #D1D5DB',borderRadius:6,fontSize:11,cursor:'pointer'}}>7d</button>
                <button onClick={()=>{setProdFrom(_daysAgo(29));setProdTo(_today());}} style={{padding:'5px 10px',background:'#F3F4F6',border:'1px solid #D1D5DB',borderRadius:6,fontSize:11,cursor:'pointer'}}>30d</button>
              </>
            )}
            <div style={{width:1,height:24,background:'#E5E7EB'}}/>
            {/* Vendedora — só admin escolhe; vendedora trava na própria */}
            {isAdminPage&&(
              <select value={prodFilterSeller} onChange={e=>setProdFilterSeller(e.target.value)} style={{padding:'6px 8px',border:'1px solid #D1D5DB',borderRadius:6,fontSize:12,minWidth:120}}>
                <option value="">Toda equipe</option>
                {prodSellerOpts.map(s=><option key={s} value={s}>{s}</option>)}
              </select>
            )}
            <select value={prodFilterMarca} onChange={e=>setProdFilterMarca(e.target.value)} style={{padding:'6px 8px',border:'1px solid #D1D5DB',borderRadius:6,fontSize:12,minWidth:110}}>
              <option value="">Toda marca</option>
              {prodMarcasOpts.map(m=><option key={m} value={m}>{m}</option>)}
            </select>
            <select value={prodFilterCat} onChange={e=>setProdFilterCat(e.target.value)} style={{padding:'6px 8px',border:'1px solid #D1D5DB',borderRadius:6,fontSize:12,minWidth:110}}>
              <option value="">Toda categoria</option>
              {prodCatOpts.map(c=><option key={c} value={c}>{c}</option>)}
            </select>
            {wList.length>0&&(
              <select value={prodFilterDep} onChange={e=>setProdFilterDep(e.target.value)} style={{padding:'6px 8px',border:'1px solid #D1D5DB',borderRadius:6,fontSize:12,minWidth:110}}>
                <option value="">Todo depósito</option>
                {wList.map(w=><option key={w.id} value={w.id}>{w.name}</option>)}
              </select>
            )}
            <select value={prodFilterStatus} onChange={e=>setProdFilterStatus(e.target.value)} style={{padding:'6px 8px',border:'1px solid #D1D5DB',borderRadius:6,fontSize:12}}>
              <option value="faturada">Só faturadas</option>
              <option value="todas">Todas</option>
            </select>
            <select value={prodSortBy} onChange={e=>setProdSortBy(e.target.value)} style={{padding:'6px 8px',border:'1px solid #D1D5DB',borderRadius:6,fontSize:12}}>
              <option value="receita">↓ Receita</option>
              <option value="qtd">↓ Quantidade</option>
              <option value="vendas">↓ # Vendas</option>
            </select>
            <div style={{flex:1}}/>
            <button
              onClick={()=>{
                try{
                  const header=['Produto','Marca','Categoria','Depósito','Qtd Bruta','Qtd Devolvida','Qtd Líquida','# Vendas','Top Cliente','Receita','Ticket Médio'];
                  const lines=[header.join(';')];
                  prodAggrData.forEach(p=>{
                    lines.push([p.name,p.brand,p.category,wName(p.depId),p.totalQty,p.devolvedQty,p.qtyLiquida,p.vendasCount,p.topClient,p.totalRevenue.toFixed(2),p.ticketMedio.toFixed(2)].map(v=>String(v).replace(/;/g,',')).join(';'));
                  });
                  const blob=new Blob(['﻿'+lines.join('\n')],{type:'text/csv;charset=utf-8'});
                  const url=URL.createObjectURL(blob);
                  const a=document.createElement('a');
                  a.href=url;
                  a.download='zaynex_produtos_'+(prodMode==='dia'?prodDate:prodFrom+'_a_'+prodTo)+'.csv';
                  a.click();
                  setTimeout(()=>URL.revokeObjectURL(url),500);
                  if(typeof toast==='function') toast('✅ CSV exportado','success');
                }catch(e){
                  console.error('[ZNX v214] export csv',e);
                  if(typeof Sentry!=='undefined') try{Sentry.captureException(e,{tags:{feature:'relatorio_produtos_csv'}});}catch(_){}
                  if(typeof toast==='function') toast('❌ Falha ao exportar CSV','error');
                }
              }}
              style={{padding:'6px 14px',background:'#10B981',color:'#fff',border:'none',borderRadius:6,fontSize:12,fontWeight:700,cursor:'pointer'}}>📥 Export CSV</button>
          </div>

          {/* Resumo do período */}
          <div className="card" style={{padding:14,marginBottom:14,display:'grid',gridTemplateColumns:'repeat(auto-fit,minmax(160px,1fr))',gap:12}}>
            <div><div style={{fontSize:11,color:'#6B7280',textTransform:'uppercase',letterSpacing:.5}}>SKUs únicos</div><div style={{fontSize:22,fontWeight:800,color:'#1F2937'}}>{prodAggrData.length}</div></div>
            <div><div style={{fontSize:11,color:'#6B7280',textTransform:'uppercase',letterSpacing:.5}}>Qtd bruta</div><div style={{fontSize:22,fontWeight:800,color:'#1F2937'}}>{prodTotaisFooter.qty} un.</div></div>
            <div><div style={{fontSize:11,color:'#6B7280',textTransform:'uppercase',letterSpacing:.5}}>Qtd líquida</div><div style={{fontSize:22,fontWeight:800,color:'#16A34A'}}>{prodTotaisFooter.qtyLiq} un.</div>{prodTotaisFooter.qty!==prodTotaisFooter.qtyLiq&&<div style={{fontSize:10,color:'#DC2626'}}>(−{prodTotaisFooter.qty-prodTotaisFooter.qtyLiq} devolvidas)</div>}</div>
            {isAdminPage&&<div><div style={{fontSize:11,color:'#6B7280',textTransform:'uppercase',letterSpacing:.5}}>Receita</div><div style={{fontSize:22,fontWeight:800,color:'#B89840'}}>{fmt(prodTotaisFooter.revenue)}</div></div>}
            <div><div style={{fontSize:11,color:'#6B7280',textTransform:'uppercase',letterSpacing:.5}}>Período</div><div style={{fontSize:14,fontWeight:600,color:'#1F2937'}}>{prodMode==='dia'?fmtDate(prodDate):fmtDate(prodFrom)+' → '+fmtDate(prodTo)}</div></div>
          </div>

          {/* Gráfico Top 10 */}
          {prodAggrData.length>0&&isAdminPage&&(
            <div className="card" style={{padding:14,marginBottom:14}}>
              <div style={{fontSize:13,fontWeight:700,color:'#2563EB',marginBottom:10}}>🏆 Top 10 por receita</div>
              {prodAggrData.slice(0,10).map((p,i)=>{
                const barW=Math.round((p.totalRevenue/prodMaxRev)*100);
                return(
                  <div key={p.id} style={{marginBottom:10,cursor:'pointer'}} onClick={()=>setProdDrillId(p.id)}>
                    <div style={{display:'flex',justifyContent:'space-between',marginBottom:3,fontSize:12}}>
                      <span><span style={{color:'#9CA3AF',marginRight:6}}>#{i+1}</span><strong>{p.name}</strong> <span style={{color:'#6B7280',fontSize:11}}>· {p.brand}</span></span>
                      <span style={{display:'flex',gap:14}}><span>{p.totalQty} un.</span><span className="gold" style={{fontWeight:700}}>{fmt(p.totalRevenue)}</span></span>
                    </div>
                    <div style={{background:'#F9FAFB',borderRadius:3,height:8,overflow:'hidden'}}>
                      <div style={{height:'100%',background:'linear-gradient(90deg,#B89840,#D4AF37)',borderRadius:3,width:barW+'%',transition:'width .3s'}}/>
                    </div>
                  </div>
                );
              })}
            </div>
          )}

          {/* Tabela completa */}
          <div className="card" style={{padding:0}}>
            <div style={{padding:'14px 16px',borderBottom:'1px solid #E4E7EC',fontWeight:700,color:'#2563EB',display:'flex',justifyContent:'space-between',alignItems:'center'}}>
              <span>📦 Produtos vendidos {prodMode==='dia'?'em '+fmtDate(prodDate):'no período'}</span>
              <span style={{fontSize:12,color:'#9CA3AF',fontWeight:400}}>{prodAggrData.length} SKU(s) · clique numa linha para ver as vendas</span>
            </div>
            {prodAggrData.length===0?(
              <div style={{padding:40,textAlign:'center',color:'#9CA3AF'}}>Nenhum produto vendido nesse período/filtros</div>
            ):(
              <div style={{overflowX:'auto',maxHeight:600}}>
                <table>
                  <thead><tr style={{position:'sticky',top:0,background:'#fff',zIndex:1}}>
                    <th>#</th>
                    <th>Produto</th>
                    <th>Marca</th>
                    <th>Categoria</th>
                    {wList.length>0&&<th>Depósito</th>}
                    <th style={{textAlign:'right'}}>Qtd</th>
                    <th style={{textAlign:'right'}}># Vendas</th>
                    <th>Top cliente</th>
                    {isAdminPage&&<th style={{textAlign:'right'}}>Receita</th>}
                    {isAdminPage&&<th style={{textAlign:'right'}}>Ticket médio</th>}
                  </tr></thead>
                  <tbody>
                    {prodAggrData.map((p,i)=>(
                      <tr key={p.id} style={{cursor:'pointer'}} onClick={()=>setProdDrillId(p.id)} title="Clique pra ver as vendas que tiveram esse produto">
                        <td className="dim" style={{fontSize:12}}>#{i+1}</td>
                        <td style={{fontSize:12,maxWidth:240,fontWeight:600}}>{p.name}</td>
                        <td><span style={{fontSize:11,color:'#2563EB',background:'#FEF3C7',padding:'2px 6px',borderRadius:4}}>{p.brand}</span></td>
                        <td style={{fontSize:11,color:'#6B7280'}}>{p.category}</td>
                        {wList.length>0&&<td style={{fontSize:11}}>{wName(p.depId)}</td>}
                        <td style={{textAlign:'right',fontWeight:700}}>
                          {p.qtyLiquida} un.
                          {p.devolvedQty>0&&<div style={{fontSize:10,color:'#DC2626'}}>(bruta {p.totalQty} − {p.devolvedQty} dev.)</div>}
                        </td>
                        <td style={{textAlign:'right'}}>{p.vendasCount}</td>
                        <td style={{fontSize:11,maxWidth:160}} title={p.topClient+' ('+p.topClientQty+' un.)'}>{p.topClient} <span style={{color:'#9CA3AF'}}>({p.topClientQty}u)</span></td>
                        {isAdminPage&&<td style={{textAlign:'right',color:'#B89840',fontWeight:700}}>{fmt(p.totalRevenue)}</td>}
                        {isAdminPage&&<td style={{textAlign:'right',fontSize:12,color:'#6B7280'}}>{fmt(p.ticketMedio)}</td>}
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>

          {/* Drill-down modal */}
          {prodDrill&&(
            <div onClick={()=>setProdDrillId(null)} style={{position:'fixed',inset:0,background:'rgba(0,0,0,.55)',zIndex:9999,display:'flex',alignItems:'center',justifyContent:'center',padding:20}}>
              <div onClick={e=>e.stopPropagation()} style={{background:'#fff',borderRadius:12,maxWidth:900,width:'100%',maxHeight:'85vh',overflow:'auto',boxShadow:'0 20px 60px rgba(0,0,0,.3)'}}>
                <div style={{padding:'16px 20px',borderBottom:'1px solid #E5E7EB',display:'flex',justifyContent:'space-between',alignItems:'center',position:'sticky',top:0,background:'#fff',zIndex:1}}>
                  <div>
                    <div style={{fontSize:11,color:'#9CA3AF',textTransform:'uppercase',letterSpacing:.5}}>Produto · drill-down</div>
                    <div style={{fontSize:18,fontWeight:800,color:'#1F2937'}}>{prodDrill.name}</div>
                    <div style={{fontSize:12,color:'#6B7280'}}>{prodDrill.brand} · {prodDrill.category} · {prodDrill.qtyLiquida} un. líquidas em {prodDrill.vendasCount} venda(s)</div>
                  </div>
                  <button onClick={()=>setProdDrillId(null)} style={{background:'none',border:'none',fontSize:24,cursor:'pointer',color:'#9CA3AF'}}>×</button>
                </div>
                <div style={{padding:16}}>
                  <table>
                    <thead><tr>
                      <th>Data</th>
                      <th>Venda</th>
                      <th>Cliente</th>
                      <th style={{textAlign:'right'}}>Qtd</th>
                      {isAdminPage&&<th style={{textAlign:'right'}}>Receita</th>}
                      <th>Status</th>
                    </tr></thead>
                    <tbody>
                      {prodDrill.salesList.sort((a,b)=>(b.date||'').localeCompare(a.date||'')).map((sl,i)=>(
                        <tr key={sl.saleId+'-'+i}>
                          <td className="dim" style={{fontSize:12,whiteSpace:'nowrap'}}>{fmtDate(sl.date)}</td>
                          <td style={{fontSize:12,fontWeight:600}}>{sl.saleNumber?'VND-'+String(sl.saleNumber).padStart(4,'0'):'(sem nº)'}</td>
                          <td style={{fontSize:12}}>{sl.client}</td>
                          <td style={{textAlign:'right',fontWeight:700}}>{sl.qty}</td>
                          {isAdminPage&&<td style={{textAlign:'right',color:'#B89840'}}>{fmt(sl.lineRevenue)}</td>}
                          <td style={{fontSize:11}}><span style={{padding:'2px 6px',borderRadius:4,background:(sl.status||'').toLowerCase().includes('cancel')?'#FEE2E2':(sl.status||'').toLowerCase().includes('devol')?'#FEF3C7':'#D1FAE5',color:(sl.status||'').toLowerCase().includes('cancel')?'#991B1B':(sl.status||'').toLowerCase().includes('devol')?'#92400E':'#065F46'}}>{sl.status||'—'}</span></td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          )}
        </div>
      )}

      {/* [Wave W2 PLAN 2026-05-18 v223.20] P&L Executivo extraído pra widget isolado.
          Backlog #645 fechado (Wave 8 deixou aberto desde 15/05).
          Componente: window.ZNX.widgets.relatorio.PLExecutivoView (8 props).
          regra_validacao_helpers_runtime_quando_ordem_scripts_uncertain: check inline + fallback UI. */}
      {(() => {
        const PLExecutivoView = window.ZNX?.widgets?.relatorio?.PLExecutivoView;
        if (!PLExecutivoView) {
          if (typeof window.znxCaptureRpcError === 'function') {
            window.znxCaptureRpcError('Relatorio_widget_missing', {
              missing: 'PLExecutivoView',
              hint: 'Verificar js/components/widgets/relatorio/PLExecutivoView.jsx carregou'
            });
          }
          if (tab === 'pl') {
            return <div style={{padding:20,color:'#DC2626',background:'#FEE2E2',borderRadius:8}}>⚠️ Widget P&L Executivo não carregou. Recarregue a página.</div>;
          }
          return null;
        }
        return (
          <PLExecutivoView
            tab={tab}
            periodo={periodo}
            labelMes={labelMes}
            fs={fs}
            revenue={revenue}
            fmt={fmt}
            plData={plData}
            gastosPorCategoria={gastosPorCategoria}
          />
        );
      })()}
    </div>
  );
}

  window.ZNX = window.ZNX || {};
  window.ZNX.components = window.ZNX.components || {};
  window.ZNX.components.Relatorio = Relatorio;
  window.Relatorio = Relatorio;

  window.ZNX.refactor_phase_6_loaded = window.ZNX.refactor_phase_6_loaded || {};
  window.ZNX.refactor_phase_6_loaded.Relatorio = true;

})();
