/* Gráficos SVG leves — Maximiano */
const { useState, useEffect, useRef, useMemo } = React;

function useMounted(){ return true; } /* charts render at visible end-state immediately — bulletproof against throttled timers; motion comes from interactions (hover tooltips, hover states, progress widths) */

/* ---- Sparkline ---- */
function Sparkline({data,w=120,h=40,color='#b68b4c',fill=true}){
  const min=Math.min(...data),max=Math.max(...data),rng=(max-min)||1;
  const pts=data.map((v,i)=>[ (i/(data.length-1))*w, h-4-((v-min)/rng)*(h-8) ]);
  const d=pts.map((p,i)=>(i?'L':'M')+p[0].toFixed(1)+' '+p[1].toFixed(1)).join(' ');
  const area=d+` L ${w} ${h} L 0 ${h} Z`;
  const id='sp'+Math.random().toString(36).slice(2,7);
  return (
    <svg width={w} height={h} style={{display:'block'}}>
      <defs><linearGradient id={id} x1="0" y1="0" x2="0" y2="1">
        <stop offset="0" stopColor={color} stopOpacity="0.22"/><stop offset="1" stopColor={color} stopOpacity="0"/>
      </linearGradient></defs>
      {fill && <path d={area} fill={`url(#${id})`}/>}
      <path d={d} fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
}

/* ---- Line chart com comparativo ---- */
function LineChart({series, labels, height=240, fmt}){
  const mounted=useMounted();
  const ref=useRef(null);
  const [w,setW]=useState(640);
  useEffect(()=>{
    if(!ref.current) return;
    const ro=new ResizeObserver(es=>setW(es[0].contentRect.width));
    ro.observe(ref.current); return ()=>ro.disconnect();
  },[]);
  const padL=58, padR=14, padT=14, padB=28;
  const all=series.flatMap(s=>s.data);
  let max=Math.max(...all), min=Math.min(...all);
  const span=max-min; max+=span*0.12; min-=span*0.12; min=Math.max(0,min);
  const rng=(max-min)||1;
  const innerW=w-padL-padR, innerH=height-padT-padB;
  const X=i=>padL+(i/(labels.length-1))*innerW;
  const Y=v=>padT+innerH-((v-min)/rng)*innerH;
  const ticks=4;
  const [hover,setHover]=useState(null);
  return (
    <div ref={ref} style={{position:'relative'}}>
      <svg width={w} height={height} style={{display:'block',overflow:'visible'}}
        onMouseLeave={()=>setHover(null)}
        onMouseMove={e=>{const r=e.currentTarget.getBoundingClientRect();const x=e.clientX-r.left;
          let i=Math.round((x-padL)/innerW*(labels.length-1)); i=Math.max(0,Math.min(labels.length-1,i)); setHover(i);}}>
        {Array.from({length:ticks+1}).map((_,i)=>{
          const v=min+(rng*i/ticks); const y=Y(v);
          return <g key={i}>
            <line x1={padL} y1={y} x2={w-padR} y2={y} stroke="#eceadf" strokeWidth="1"/>
            <text x={padL-10} y={y+4} textAnchor="end" fontSize="10.5" fill="#9a9caa" fontFamily="Public Sans">{fmt?fmt(v):Math.round(v)}</text>
          </g>;
        })}
        {labels.map((l,i)=><text key={i} x={X(i)} y={height-8} textAnchor="middle" fontSize="11" fill="#8c8f9c" fontFamily="Public Sans">{l}</text>)}
        {series.map((s,si)=>{
          const d=s.data.map((v,i)=>(i?'L':'M')+X(i).toFixed(1)+' '+Y(v).toFixed(1)).join(' ');
          const len= si===0? 1400:1400;
          if(s.dashed){
            return <path key={si} d={d} fill="none" stroke={s.color} strokeWidth="1.8" strokeDasharray="5 5" opacity={mounted?0.9:0}
              style={{transition:'opacity .6s'}}/>;
          }
          const area=d+` L ${X(labels.length-1)} ${padT+innerH} L ${X(0)} ${padT+innerH} Z`;
          const gid='lg'+si;
          return <g key={si}>
            {s.fill && <defs><linearGradient id={gid} x1="0" y1="0" x2="0" y2="1">
              <stop offset="0" stopColor={s.color} stopOpacity="0.18"/><stop offset="1" stopColor={s.color} stopOpacity="0"/>
            </linearGradient></defs>}
            {s.fill && <path d={area} fill={`url(#${gid})`} opacity={mounted?1:0} style={{transition:'opacity .8s .2s'}}/>}
            <path d={d} fill="none" stroke={s.color} strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round"
              strokeDasharray={len} strokeDashoffset={mounted?0:len} style={{transition:'stroke-dashoffset 1.1s cubic-bezier(.3,.8,.3,1)'}}/>
          </g>;
        })}
        {hover!=null && <line x1={X(hover)} y1={padT} x2={X(hover)} y2={padT+innerH} stroke="#c9b78f" strokeWidth="1" strokeDasharray="3 3"/>}
        {hover!=null && series.filter(s=>!s.dashed).map((s,si)=>(
          <circle key={si} cx={X(hover)} cy={Y(s.data[hover])} r="4.5" fill="#fff" stroke={s.color} strokeWidth="2.5"/>
        ))}
      </svg>
      {hover!=null && (
        <div style={{position:'absolute',left:Math.min(X(hover)+10,w-160),top:padT,background:'#fff',border:'1px solid #e7e1d4',
          borderRadius:10,boxShadow:'0 8px 24px rgba(28,32,52,.12)',padding:'9px 12px',pointerEvents:'none',minWidth:140}}>
          <div style={{fontSize:11,color:'#8c8f9c',fontWeight:600,marginBottom:5}}>{labels[hover]} / 2026</div>
          {series.map((s,i)=>(
            <div key={i} style={{display:'flex',alignItems:'center',gap:7,fontSize:12.5,marginTop:3}}>
              <span style={{width:9,height:9,borderRadius:3,background:s.color,display:'inline-block'}}></span>
              <span style={{color:'#5a5f70'}}>{s.name}</span>
              <b style={{marginLeft:'auto',fontVariantNumeric:'tabular-nums',color:'#272c3d'}}>{fmt?fmt(s.data[hover]):s.data[hover]}</b>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

/* ---- Bar chart vertical ---- */
function BarChart({data, height=220, fmt, accent='#2d3245'}){
  const mounted=useMounted();
  const max=Math.max(...data.map(d=>d.value))*1.1;
  return (
    <div style={{display:'flex',alignItems:'flex-end',gap:18,height,padding:'8px 4px 0'}}>
      {data.map((d,i)=>{
        const h=(d.value/max)*100;
        return (
          <div key={i} style={{flex:1,display:'flex',flexDirection:'column',alignItems:'center',height:'100%',justifyContent:'flex-end',gap:8}}>
            <div style={{fontSize:12.5,fontWeight:700,color:'#272c3d',fontVariantNumeric:'tabular-nums',opacity:mounted?1:0,transition:'opacity .5s .5s'}}>
              {fmt?fmt(d.value):d.value}
            </div>
            <div style={{width:'100%',maxWidth:54,borderRadius:'8px 8px 0 0',height:mounted?`${h}%`:'0%',
              background:d.color||accent, transition:`height .9s cubic-bezier(.2,.8,.2,1) ${i*0.07}s`, minHeight:4}}></div>
            <div style={{fontSize:12,color:'#5a5f70',fontWeight:600,textAlign:'center'}}>{d.label}</div>
          </div>
        );
      })}
    </div>
  );
}

/* ---- Donut ---- */
function Donut({data, size=180, thickness=26, total, fmt, centerLabel}){
  const mounted=useMounted();
  const sum=data.reduce((a,d)=>a+d.value,0);
  const r=(size-thickness)/2, c=size/2, circ=2*Math.PI*r;
  let acc=0;
  return (
    <div style={{display:'flex',alignItems:'center',gap:24,flexWrap:'wrap'}}>
      <div style={{position:'relative',width:size,height:size,flexShrink:0}}>
        <svg width={size} height={size} style={{transform:'rotate(-90deg)'}}>
          <circle cx={c} cy={c} r={r} fill="none" stroke="#eceadf" strokeWidth={thickness}/>
          {data.map((d,i)=>{
            const frac=d.value/sum; const len=frac*circ; const off=acc*circ; acc+=frac;
            return <circle key={i} cx={c} cy={c} r={r} fill="none" stroke={d.color} strokeWidth={thickness}
              strokeDasharray={`${mounted?len:0} ${circ}`} strokeDashoffset={-off}
              style={{transition:`stroke-dasharray 1s cubic-bezier(.2,.8,.2,1) ${i*0.1}s`}} strokeLinecap="butt"/>;
          })}
        </svg>
        <div style={{position:'absolute',inset:0,display:'grid',placeItems:'center',textAlign:'center'}}>
          <div>
            <div style={{fontFamily:'Spectral,serif',fontSize:23,fontWeight:600,color:'#272c3d',lineHeight:1}}>{total}</div>
            <div style={{fontSize:11,color:'#8c8f9c',marginTop:3}}>{centerLabel}</div>
          </div>
        </div>
      </div>
      <div className="legend" style={{flex:1,minWidth:160}}>
        {data.map((d,i)=>(
          <div className="lg" key={i}>
            <span className="sw" style={{background:d.color}}></span>
            <span className="ln">{d.label}</span>
            <span className="lv">{fmt?fmt(d.value):d.value}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ---- Gauge (meta x realizado) ---- */
function Gauge({value, max, size=180, fmt}){
  const mounted=useMounted();
  const pct=Math.min(value/max,1.15);
  const r=size/2-16, c=size/2, circ=Math.PI*r; // semicircle
  const filled=Math.min(pct,1)*circ;
  const over=pct>1;
  return (
    <div style={{position:'relative',width:size,height:size/2+30,margin:'0 auto'}}>
      <svg width={size} height={size/2+16} style={{overflow:'visible'}}>
        <path d={`M16 ${size/2} A ${r} ${r} 0 0 1 ${size-16} ${size/2}`} fill="none" stroke="#eceadf" strokeWidth="16" strokeLinecap="round"/>
        <path d={`M16 ${size/2} A ${r} ${r} 0 0 1 ${size-16} ${size/2}`} fill="none"
          stroke={over?'#3f7a57':'#b68b4c'} strokeWidth="16" strokeLinecap="round"
          strokeDasharray={circ} strokeDashoffset={mounted?circ-filled:circ}
          style={{transition:'stroke-dashoffset 1.1s cubic-bezier(.2,.8,.2,1)'}}/>
      </svg>
      <div style={{position:'absolute',bottom:0,left:0,right:0,textAlign:'center'}}>
        <div style={{fontFamily:'Spectral,serif',fontSize:28,fontWeight:600,color:'#272c3d',lineHeight:1}}>
          {Math.round(pct*100)}%
        </div>
        <div style={{fontSize:11.5,color:'#8c8f9c',marginTop:3}}>da meta {fmt?`· ${fmt(max)}`:''}</div>
      </div>
    </div>
  );
}

Object.assign(window,{ Sparkline, LineChart, BarChart, Donut, Gauge, useMounted });
