// js/components/widgets/VendedorAbaDiario.jsx
// [Wave 16 v223.42 20260520] Aba "Diário" do HistoricoVendedor
// Props: vendedoraAlvo (string), sales (array), periodDays (number, default 30)
// Deps runtime: window.ZNX.lib.vendedorAnalise, window.ZNX.widgets.KpiCard, window.fmt
(function(){
  'use strict';

  function VendedorAbaDiario(props){
    const vendedoraAlvo = props.vendedoraAlvo;
    const sales = props.sales || [];
    const periodDays = Number(props.periodDays || 30);

    // Fail-loud guards (regra_estender_bloco_refs_fail_loud)
    const lib = window.ZNX && window.ZNX.lib && window.ZNX.lib.vendedorAnalise;
    const KpiCard = window.ZNX && window.ZNX.widgets && window.ZNX.widgets.KpiCard;
    if (!lib || typeof lib.calcDiario !== 'function' || !KpiCard) {
      if (window.Sentry && typeof window.Sentry.captureMessage === 'function') {
        try { window.Sentry.captureMessage('[Wave 16 v223.42] VendedorAbaDiario missing deps: lib='+(!!lib)+' KpiCard='+(!!KpiCard), 'error'); } catch(e){}
      }
      console.error('[VendedorAbaDiario] Dependências faltando: lib=', !!lib, 'KpiCard=', !!KpiCard);
      return (<div style={{padding:20,color:'#B91C1C',background:'#FEE2E2',borderRadius:8}}>Erro: módulo de análise diário não carregou. Recarregue a página (Ctrl+Shift+R).</div>);
    }
    if (!vendedoraAlvo) return (<div style={{padding:20,color:'#6B7280'}}>Selecione uma vendedora pra ver análise diária.</div>);

    const fmt = (typeof window.fmt === 'function') ? window.fmt : function(v){ return 'R$ '+Number(v||0).toFixed(2); };

    const rows = lib.calcDiario(sales, vendedoraAlvo, periodDays);
    const kpis = lib.calcDiarioKPIs(rows);

    // Visual heatmap: cor de fundo proporcional ao notasCount
    const maxNotas = Math.max(1, ...rows.map(function(r){ return r.notasCount; }));
    function bgFor(count){
      if (count === 0) return '#F3F4F6';
      const intensity = Math.min(1, count/maxNotas);
      const r = Math.round(255 - intensity*100);
      const g = Math.round(251 - intensity*80);
      const b = Math.round(235 - intensity*100);
      return 'rgb('+r+','+g+','+b+')';
    }

    return (
      <div>
        {/* KPIs Diário */}
        <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fit,minmax(180px,1fr))',gap:12,marginBottom:20}}>
          <KpiCard label="Total de Notas" value={String(kpis.totalNotas)} subtitle={'em '+periodDays+'d'} />
          <KpiCard label="Média/Dia Útil" value={kpis.mediaNotasDia.toFixed(1)} subtitle="notas/dia" />
          <KpiCard label="Melhor Dia" value={String(kpis.melhorDia.count)} subtitle={kpis.melhorDia.date} />
          <KpiCard label="Dias Zerados" value={String(kpis.diasZerados)} subtitle="sem notas" />
          <KpiCard label="Taxa Faturamento" value={kpis.taxaFaturamento.toFixed(1)+'%'} subtitle={kpis.totalFaturadas+'/'+kpis.totalNotas} />
        </div>

        {/* Heatmap calendário */}
        <div style={{background:'#fff',border:'1px solid #E5E7EB',borderRadius:12,padding:16,marginBottom:16}}>
          <div style={{fontSize:14,fontWeight:700,color:'#1F2937',marginBottom:12}}>Calendário diário (últimos {periodDays} dias)</div>
          <div style={{display:'grid',gridTemplateColumns:'repeat(7,1fr)',gap:6}}>
            {['Dom','Seg','Ter','Qua','Qui','Sex','Sáb'].map(function(d){
              return <div key={'wh-'+d} style={{fontSize:11,fontWeight:600,color:'#6B7280',textAlign:'center',padding:4}}>{d}</div>;
            })}
            {(function(){
              const firstWd = rows.length ? new Date(rows[0].dateKey).getDay() : 0;
              const padBefore = [];
              for (let i=0;i<firstWd;i++) padBefore.push(<div key={'pad-'+i} />);
              return padBefore.concat(rows.map(function(r){
                return (
                  <div key={r.dateKey} title={r.dateLabel+' ('+r.weekday+') — '+r.notasCount+' notas, '+fmt(r.valorTotal)} style={{
                    background: r.isToday ? '#FEF3C7' : bgFor(r.notasCount),
                    border: r.isToday ? '2px solid #C8A951' : '1px solid #E5E7EB',
                    borderRadius:8, padding:'8px 4px', minHeight:60, display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'space-between'
                  }}>
                    <div style={{fontSize:10,color:'#6B7280',fontWeight:500}}>{r.dateLabel}</div>
                    <div style={{fontSize:18,fontWeight:800,color:r.notasCount>0?'#1F2937':'#D1D5DB'}}>{r.notasCount}</div>
                    <div style={{fontSize:9,color:'#9CA3AF'}}>{r.valorTotal>0?fmt(r.valorTotal).replace('R$','').trim():'—'}</div>
                  </div>
                );
              }));
            })()}
          </div>
        </div>

        {/* Tabela detalhada */}
        <div style={{background:'#fff',border:'1px solid #E5E7EB',borderRadius:12,padding:16}}>
          <div style={{fontSize:14,fontWeight:700,color:'#1F2937',marginBottom:12}}>Detalhamento dia-a-dia</div>
          <div style={{maxHeight:400,overflowY:'auto'}}>
            <table style={{width:'100%',fontSize:13,borderCollapse:'collapse'}}>
              <thead>
                <tr style={{borderBottom:'2px solid #E5E7EB',background:'#F9FAFB'}}>
                  <th style={{textAlign:'left',padding:'8px',fontWeight:600,color:'#374151'}}>Data</th>
                  <th style={{textAlign:'left',padding:'8px',fontWeight:600,color:'#374151'}}>Dia</th>
                  <th style={{textAlign:'right',padding:'8px',fontWeight:600,color:'#374151'}}>Notas</th>
                  <th style={{textAlign:'right',padding:'8px',fontWeight:600,color:'#374151'}}>Faturadas</th>
                  <th style={{textAlign:'right',padding:'8px',fontWeight:600,color:'#374151'}}>Valor Total</th>
                  <th style={{textAlign:'right',padding:'8px',fontWeight:600,color:'#374151'}}>Faturado</th>
                </tr>
              </thead>
              <tbody>
                {rows.slice().reverse().map(function(r){
                  return (
                    <tr key={'row-'+r.dateKey} style={{borderBottom:'1px solid #F3F4F6',background:r.isToday?'#FEF3C7':'transparent'}}>
                      <td style={{padding:'8px',fontWeight:r.isToday?700:500}}>{r.dateLabel}</td>
                      <td style={{padding:'8px',color:'#6B7280'}}>{r.weekday}</td>
                      <td style={{padding:'8px',textAlign:'right',fontWeight:600,color:r.notasCount===0?'#D1D5DB':'#1F2937'}}>{r.notasCount}</td>
                      <td style={{padding:'8px',textAlign:'right',color:'#059669'}}>{r.notasFaturadasCount}</td>
                      <td style={{padding:'8px',textAlign:'right',color:r.valorTotal===0?'#D1D5DB':'#1F2937'}}>{r.valorTotal>0?fmt(r.valorTotal):'—'}</td>
                      <td style={{padding:'8px',textAlign:'right',color:'#059669',fontWeight:600}}>{r.valorFaturado>0?fmt(r.valorFaturado):'—'}</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    );
  }

  window.ZNX = window.ZNX || {};
  window.ZNX.components = window.ZNX.components || {};
  window.ZNX.components.VendedorAbaDiario = VendedorAbaDiario;
  window.VendedorAbaDiario = VendedorAbaDiario;
})();
