// SVG Chart Components — Premium 2026
const { useState: uS, useRef: uR, useEffect: uE } = React;

function LineChart({ data=[], labels=[], color='#F97316', h=160 }) {
  if (!data.length) return null;
  const W=400, pad=14, pb=28, pt=12;
  const min=Math.min(...data)*0.85, max=Math.max(...data)*1.05, rng=max-min||1;
  const xp = i => pad + (i/(data.length-1||1))*(W-pad*2);
  const yp = v => pt + (1-(v-min)/rng)*(h-pt-pb);
  const pts = data.map((v,i)=>[xp(i),yp(v)]);
  const gid = `lc${color.replace(/[^a-zA-Z0-9]/g,'')}`;

  function path() {
    if (pts.length<2) return `M${pts[0][0]},${pts[0][1]}`;
    let d=`M${pts[0][0]},${pts[0][1]}`;
    for (let i=1;i<pts.length;i++) {
      const cp=(pts[i-1][0]+pts[i][0])/2;
      d+=` C${cp},${pts[i-1][1]} ${cp},${pts[i][1]} ${pts[i][0]},${pts[i][1]}`;
    }
    return d;
  }
  const linePath=path();
  const areaPath=`${linePath} L${pts[pts.length-1][0]},${h-pb} L${pts[0][0]},${h-pb} Z`;

  return (
    <svg viewBox={`0 0 ${W} ${h}`} style={{width:'100%',height:h,display:'block'}}>
      <defs>
        <linearGradient id={gid} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={color} stopOpacity=".13"/>
          <stop offset="88%" stopColor={color} stopOpacity="0"/>
        </linearGradient>
      </defs>
      {/* Hairline grid */}
      {[0,.25,.5,.75,1].map(t=>(
        <line key={t} x1={pad} x2={W-pad} y1={pt+(h-pt-pb)*t} y2={pt+(h-pt-pb)*t}
          stroke={t===1?'rgba(0,0,0,.07)':'rgba(0,0,0,.032)'} strokeWidth={.75}/>
      ))}
      <path d={areaPath} fill={`url(#${gid})`}/>
      {/* Animated draw */}
      <path d={linePath} fill="none" stroke={color} strokeWidth="2"
        strokeLinecap="round" strokeLinejoin="round"
        strokeDasharray="1400"
        style={{filter:`drop-shadow(0 0 3px ${color}44)`}}>
        <animate attributeName="stroke-dashoffset" from="1400" to="0"
          dur=".9s" fill="freeze" calcMode="spline" keyTimes="0;1" keySplines="0.16 1 0.3 1"/>
      </path>
      {/* Premium markers */}
      {pts.map(([x,y],i)=>(
        <g key={i}>
          <circle cx={x} cy={y} r="9" fill={color} opacity=".07"/>
          <circle cx={x} cy={y} r="3.5" fill="#fff" stroke={color} strokeWidth="2"
            style={{filter:`drop-shadow(0 0 4px ${color}66)`}}/>
        </g>
      ))}
      {labels.map((l,i)=>(
        <text key={i} x={xp(i)} y={h-6} textAnchor="middle" fontSize="9.5"
          fill="#B0ACA8" fontFamily="-apple-system,'Inter',sans-serif">{l}</text>
      ))}
    </svg>
  );
}

function BarChart({ data=[], labels=[], color='#F97316', h=150 }) {
  const [hov, setHov] = uS(-1);
  const [prog, setProg] = uS(0);
  const rafRef = uR(null);
  const dataKey = data.join(',');

  uE(() => {
    if (!data.length) return;
    setProg(0);
    const t0 = performance.now(), dur = 720;
    const tick = t => {
      const p = Math.min((t - t0) / dur, 1);
      setProg(1 - Math.pow(1 - p, 3));
      if (p < 1) rafRef.current = requestAnimationFrame(tick);
    };
    rafRef.current = requestAnimationFrame(tick);
    return () => { if (rafRef.current) cancelAnimationFrame(rafRef.current); };
  }, [dataKey]);

  if (!data.length) return null;
  const W=400, pad=10, pb=28, pt=8;
  const max=Math.max(...data)*1.1||1;
  const gap=Math.floor((W-pad*2)/data.length);
  const bw=Math.max(8, Math.floor(gap*0.52));
  const gid=`bc${color.replace(/[^a-zA-Z0-9]/g,'')}`;

  const animP = i => {
    const delay = i * (0.5 / Math.max(data.length, 1));
    return Math.max(0, Math.min(1, (prog - delay) / (1 - delay + 0.001)));
  };
  const bh = (v, i) => {
    const eased = 1 - Math.pow(1 - animP(i), 2.5);
    return Math.max(0, Math.floor((v/max)*(h-pt-pb)*eased));
  };
  const xp = i => pad + i*gap + Math.floor((gap-bw)/2);

  return (
    <svg viewBox={`0 0 ${W} ${h}`} style={{width:'100%',height:h,display:'block'}}
      onMouseLeave={()=>setHov(-1)}>
      <defs>
        <linearGradient id={gid} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={color} stopOpacity=".92"/>
          <stop offset="100%" stopColor={color} stopOpacity=".5"/>
        </linearGradient>
        <linearGradient id={`${gid}h`} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#FDB97D"/>
          <stop offset="100%" stopColor={color}/>
        </linearGradient>
      </defs>
      {/* Hairline grid */}
      {[0,.33,.67,1].map(t=>(
        <line key={t} x1={pad} x2={W-pad} y1={pt+(h-pt-pb)*t} y2={pt+(h-pt-pb)*t}
          stroke={t===1?'rgba(0,0,0,.07)':'rgba(0,0,0,.03)'} strokeWidth={.75}/>
      ))}
      {data.map((v,i)=>{
        const isH=hov===i;
        const bhi=bh(v,i);
        const rx=Math.min(7, bw/2, bhi>2?bhi:99);
        const alpha=hov>=0&&!isH?0.32:1;
        const xi=xp(i);
        const yi=h-pb-bhi;
        return (
          <g key={i} onMouseEnter={()=>setHov(i)} onMouseLeave={()=>setHov(-1)}>
            {/* Soft glow on hover */}
            {isH && bhi>0 && (
              <rect x={xi-4} y={yi} width={bw+8} height={bhi} rx={rx}
                fill={color} opacity=".13" style={{filter:'blur(10px)'}}/>
            )}
            {bhi>0 && (
              <rect x={xi} y={yi} width={bw} height={bhi} rx={rx}
                fill={`url(#${isH?gid+'h':gid})`} opacity={alpha}
                style={{
                  transform: isH ? 'translateY(-2px)' : 'none',
                  transformOrigin: `${xi+bw/2}px ${h-pb}px`,
                  transition: 'transform .18s ease, opacity .18s ease',
                  filter: isH ? `drop-shadow(0 4px 10px ${color}44)` : 'none',
                }}/>
            )}
            {labels && (
              <text x={xi+bw/2} y={h-7} textAnchor="middle" fontSize="9.5"
                fill={hov>=0&&!isH?'rgba(168,164,160,.35)':isH?color:'#B0ACA8'}
                fontWeight={isH?700:400}
                fontFamily="-apple-system,'Inter',sans-serif">
                {labels[i]}
              </text>
            )}
          </g>
        );
      })}
    </svg>
  );
}

function MiniBar({ data=[], color='#F97316' }) {
  if (!data.length) return null;
  const W=80, h=32, max=Math.max(...data)||1;
  const bw=Math.floor((W/data.length)*0.52);
  const gap=W/data.length;
  const gid=`mb${color.replace(/[^a-zA-Z0-9]/g,'')}`;
  return (
    <svg viewBox={`0 0 ${W} ${h}`} style={{width:W,height:h}}>
      <defs>
        <linearGradient id={gid} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={color} stopOpacity=".88"/>
          <stop offset="100%" stopColor={color} stopOpacity=".48"/>
        </linearGradient>
      </defs>
      {data.map((v,i)=>{
        const bhi=Math.max(2,Math.floor((v/max)*h));
        return <rect key={i} x={i*gap+gap*0.225} y={h-bhi} width={bw} height={bhi}
          rx="2.5" fill={`url(#${gid})`}/>;
      })}
    </svg>
  );
}

window.LineChart=LineChart;
window.BarChart=BarChart;
window.MiniBar=MiniBar;
