// js/components/widgets/GraficoMesView.jsx
// [Wave 12B v223.35 20260520] Extraído de DashboardV2.jsx L473-594 (SVG 121L denso)
// SEÇÃO 4 — Gráfico mês inteiro D1-D31 + overlay mês anterior + ghost futuros + pulse hoje + pico
// [v223.18 UX] Substitui chart14 (rolling 14d). Opção B Jamal: ghost futuro.
// [v223.17 UX FIX] padT 16→32: label R$ pico não corta no topo
// [v223.19 UX] Header dinâmico: quando pico=hoje, evita repetir mesmo valor 2x
//
// Props:
//   chartMes (array de {date, total, totalPrev, label, isFuture, dia})
//   chartMax (number), chartHoje (obj), chartPico (obj), chartMesLabel (string),
//   chartHojeDia (number), chartUltimoDia (number)
// Deps runtime: window.fmt
(function(){
  'use strict';

  function GraficoMesView(props){
    const {
      chartMes=[], chartMax=1, chartHoje={total:0}, chartPico={total:0,dia:0,label:'1'},
      chartMesLabel='', chartHojeDia=1, chartUltimoDia=31
    } = props;
    const fmt = typeof window.fmt === 'function' ? window.fmt : (v)=>String(v);

    // [UX FIX v223.17] padT 16→32: dá folga pra label R$ pico não cortar no topo
    const W = 980, H = 220, padL = 56, padR = 16, padT = 32, padB = 32;
    const chartW = W - padL - padR;
    const chartH = H - padT - padB;
    const n = chartMes.length;
    if (n < 2) return <div className="card" style={{padding:18,textAlign:'center',color:'#9CA3AF'}}>Sem dados pro gráfico do mês.</div>;
    const stepX = chartW / (n - 1);
    const yTicks = [0, 0.25, 0.5, 0.75, 1].map(p => Math.round(chartMax * p));
    function xAt(i){ return padL + i * stepX; }
    function yAt(v){ return padT + chartH - (v / chartMax) * chartH; }
    const realizados = chartMes.filter(b => !b.isFuture);
    const lastRealIdx = realizados.length - 1;
    const linePath = realizados.map((b,i)=>{
      const realIdx = chartMes.indexOf(b);
      return (i===0?'M':'L')+xAt(realIdx)+' '+yAt(b.total);
    }).join(' ');
    const areaPath = realizados.length > 0
      ? linePath + ' L'+xAt(lastRealIdx)+' '+(padT+chartH)+' L'+xAt(0)+' '+(padT+chartH)+' Z'
      : '';
    const prevPath = chartMes.map((b,i)=>(i===0?'M':'L')+xAt(i)+' '+yAt(b.totalPrev||0)).join(' ');

    return (
      <div className="card" style={{padding:'18px 20px 12px'}}>
        <div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-start',flexWrap:'wrap',gap:8,marginBottom:14}}>
          <div>
            <div style={{fontSize:11,color:'#9CA3AF',fontWeight:700,textTransform:'uppercase',letterSpacing:1.5}}>📈 Vendas — {chartMesLabel} · dia {chartHojeDia}/{chartUltimoDia}</div>
            <div style={{fontSize:13,color:'#6B7280',marginTop:4}}>
              {chartPico.dia === chartHojeDia && chartPico.total > 0 ? (
                <>🏆 <strong style={{color:'#7C3AED'}}>HOJE é o pico do mês</strong>: <strong style={{color:'#2563EB'}}>{fmt(chartHoje.total)}</strong></>
              ) : (
                <>Pico: <strong style={{color:'#1B2A4A'}}>{fmt(chartPico.total)}</strong> em D{chartPico.label} · Hoje: <strong style={{color:'#2563EB'}}>{fmt(chartHoje.total)}</strong></>
              )}
            </div>
          </div>
          <div style={{display:'flex',gap:14,fontSize:11,color:'#6B7280'}}>
            <span style={{display:'flex',alignItems:'center',gap:5}}><span style={{width:18,height:3,background:'linear-gradient(90deg,#3B82F6,#2563EB)',display:'inline-block',borderRadius:2}}/> mês atual</span>
            <span style={{display:'flex',alignItems:'center',gap:5}}><span style={{width:18,height:0,borderTop:'2px dashed #94A3B8',display:'inline-block'}}/> mês anterior</span>
          </div>
        </div>

        <svg width="100%" viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="xMidYMid meet" style={{display:'block',maxHeight:260}}>
          <defs>
            <linearGradient id="areaGrad" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stopColor="#3B82F6" stopOpacity="0.35"/>
              <stop offset="60%" stopColor="#3B82F6" stopOpacity="0.08"/>
              <stop offset="100%" stopColor="#3B82F6" stopOpacity="0"/>
            </linearGradient>
            <linearGradient id="lineGrad" x1="0" y1="0" x2="1" y2="0">
              <stop offset="0%" stopColor="#3B82F6"/>
              <stop offset="100%" stopColor="#2563EB"/>
            </linearGradient>
          </defs>

          {yTicks.map((tick,i)=>(
            <g key={i}>
              <line x1={padL} y1={yAt(tick)} x2={W-padR} y2={yAt(tick)} stroke={i===0?'#CBD5E1':'#E5E7EB'} strokeWidth="1" strokeDasharray={i===0?'':'3 3'}/>
              <text x={padL-8} y={yAt(tick)+4} fontSize="10" fill="#94A3B8" textAnchor="end">{tick>=1000?(tick/1000).toFixed(0)+'k':tick}</text>
            </g>
          ))}

          <path d={prevPath} stroke="#94A3B8" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round" strokeDasharray="5 4" opacity="0.55"/>
          <path d={areaPath} fill="url(#areaGrad)" stroke="none"/>
          <path d={linePath} stroke="url(#lineGrad)" strokeWidth="3" fill="none" strokeLinecap="round" strokeLinejoin="round"/>

          {chartMes.map((b,i)=>{
            if (b.isFuture) {
              const x = xAt(i);
              return (
                <g key={i}>
                  <line x1={x} y1={padT} x2={x} y2={padT+chartH} stroke="#E5E7EB" strokeWidth="0.5" strokeDasharray="2 3" opacity="0.5"/>
                  {(b.dia % 5 === 0 || b.dia === chartUltimoDia) && (
                    <text x={x} y={H-12} fontSize="10" fill="#CBD5E1" textAnchor="middle">{b.label}</text>
                  )}
                </g>
              );
            }
            const isToday = b.dia === chartHojeDia;
            const isPico = b.total === chartPico.total && b.total > 0;
            const x = xAt(i), y = yAt(b.total);
            return(
              <g key={i}>
                <rect x={x-stepX/2} y={padT} width={stepX} height={chartH} fill="transparent">
                  <title>D{b.label}: {fmt(b.total)}{b.totalPrev>0?` (mês anterior: ${fmt(b.totalPrev)})`:''}</title>
                </rect>
                {isToday && <circle cx={x} cy={y} r="14" fill="#2563EB" opacity="0.15"><animate attributeName="r" values="10;18;10" dur="2s" repeatCount="indefinite"/></circle>}
                <circle cx={x} cy={y} r={isToday?6:isPico?5:4} fill={isToday?'#2563EB':'#FFFFFF'} stroke={isPico?'#7C3AED':'#2563EB'} strokeWidth={isPico?2.5:2}/>
                {isPico && b.total>0 && (
                  <g>
                    <rect x={x-22} y={y - 22 < padT ? y + 6 : y - 22} width="44" height="14" rx="3" fill="#7C3AED"/>
                    <text x={x} y={y - 12 < padT ? y + 16 : y - 12} fontSize="9" fill="#FFFFFF" textAnchor="middle" fontWeight="700">{(b.total/1000).toFixed(0)}k</text>
                  </g>
                )}
                {(b.dia % 5 === 0 || isToday || b.dia === 1) && (
                  <text x={x} y={H-12} fontSize="10" fill={isToday?'#2563EB':'#94A3B8'} textAnchor="middle" fontWeight={isToday?700:400}>{b.label}</text>
                )}
              </g>
            );
          })}
        </svg>
      </div>
    );
  }

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