// Hand-built SVG charts — line, area, donut, bar.

function Sparkline({ data=[], stroke="#5FD6D0", w=84, h=26 }) {
  if (!data.length) return null;
  const max = Math.max(...data), min = Math.min(...data);
  const range = max-min || 1;
  const step = w/(data.length-1);
  const pts = data.map((v,i) => [i*step, h - ((v-min)/range)*(h-4) - 2]);
  const path = "M " + pts.map(p=>p.join(",")).join(" L ");
  const area = path + ` L ${w},${h} L 0,${h} Z`;
  const id = "sg-" + Math.random().toString(36).slice(2,7);
  return (
    <svg width={w} height={h} viewBox={`0 0 ${w} ${h}`}>
      <defs>
        <linearGradient id={id} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={stroke} stopOpacity="0.25"/>
          <stop offset="100%" stopColor={stroke} stopOpacity="0"/>
        </linearGradient>
      </defs>
      <path d={area} fill={`url(#${id})`}/>
      <path d={path} fill="none" stroke={stroke} strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
}

function LineChart({ data, height=240, color="#5FD6D0", secondColor=null, valKey="v", val2Key=null, fmt=v=>"$"+v+"M" }) {
  const W = 700, H = height, padL=46, padR=14, padT=14, padB=28;
  const innerW = W - padL - padR, innerH = H - padT - padB;
  const maxV = Math.max(...data.map(d => Math.max(d[valKey], val2Key ? d[val2Key]||0 : 0))) * 1.1;
  const step = innerW / (data.length-1);
  const yTicks = 5;
  const xy = (i, v) => [padL + i*step, padT + innerH - (v/maxV)*innerH];

  const buildPath = key => "M " + data.map((d,i) => xy(i, d[key]).join(",")).join(" L ");
  const buildArea = key => buildPath(key) + ` L ${padL+innerW},${padT+innerH} L ${padL},${padT+innerH} Z`;

  const gid = "lg-" + Math.random().toString(36).slice(2,7);
  const gid2 = "lg2-" + Math.random().toString(36).slice(2,7);

  return (
    <svg className="chart" viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" style={{height, width:"100%"}}>
      <defs>
        <linearGradient id={gid} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={color} stopOpacity="0.32"/>
          <stop offset="100%" stopColor={color} stopOpacity="0"/>
        </linearGradient>
        {secondColor && (
          <linearGradient id={gid2} x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor={secondColor} stopOpacity="0.18"/>
            <stop offset="100%" stopColor={secondColor} stopOpacity="0"/>
          </linearGradient>
        )}
      </defs>

      {/* y grid + labels */}
      {Array.from({length:yTicks+1}).map((_,i) => {
        const y = padT + (innerH/yTicks)*i;
        const v = (maxV * (1 - i/yTicks));
        return (
          <g key={i}>
            <line x1={padL} x2={padL+innerW} y1={y} y2={y} className="grid-line"/>
            <text x={padL-8} y={y+3} textAnchor="end">{fmt(Math.round(v))}</text>
          </g>
        );
      })}

      {/* x labels */}
      {data.map((d,i) => (
        <text key={i} x={padL + i*step} y={H-10} textAnchor="middle">{d.x}</text>
      ))}

      {secondColor && val2Key && (
        <>
          <path d={buildArea(val2Key)} fill={`url(#${gid2})`}/>
          <path d={buildPath(val2Key)} fill="none" stroke={secondColor} strokeWidth="1.6" strokeDasharray="4 4"/>
        </>
      )}

      <path d={buildArea(valKey)} fill={`url(#${gid})`}/>
      <path d={buildPath(valKey)} fill="none" stroke={color} strokeWidth="2"/>

      {/* dots */}
      {data.map((d,i) => {
        const [x,y] = xy(i, d[valKey]);
        return <circle key={i} cx={x} cy={y} r="3" fill={color} stroke="var(--bg-card)" strokeWidth="2"/>;
      })}
    </svg>
  );
}

function Donut({ data, size=180, thickness=24, centerLabel, centerValue }) {
  const r = size/2;
  const inner = r - thickness;
  const total = data.reduce((s,d)=>s+d.value,0);
  let acc = -Math.PI/2;
  const arcs = data.map(d => {
    const ang = (d.value/total) * Math.PI*2;
    const x1 = r + r*Math.cos(acc), y1 = r + r*Math.sin(acc);
    const x2 = r + r*Math.cos(acc+ang), y2 = r + r*Math.sin(acc+ang);
    const xi1 = r + inner*Math.cos(acc+ang), yi1 = r + inner*Math.sin(acc+ang);
    const xi2 = r + inner*Math.cos(acc), yi2 = r + inner*Math.sin(acc);
    const large = ang > Math.PI ? 1 : 0;
    const path = `M ${x1} ${y1} A ${r} ${r} 0 ${large} 1 ${x2} ${y2} L ${xi1} ${yi1} A ${inner} ${inner} 0 ${large} 0 ${xi2} ${yi2} Z`;
    acc += ang;
    return { path, color:d.color, name:d.name, value:d.value };
  });
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
      {arcs.map((a,i) => <path key={i} d={a.path} fill={a.color}/>)}
      {centerValue && (
        <g>
          <text x={r} y={r-4} textAnchor="middle" fill="currentColor" style={{fontSize:18, fontWeight:600}}>{centerValue}</text>
          <text x={r} y={r+14} textAnchor="middle" fill="var(--muted)" style={{fontSize:11}}>{centerLabel}</text>
        </g>
      )}
    </svg>
  );
}

function BarsH({ data, max, fmt = v=>v, height=null }) {
  const m = max ?? Math.max(...data.map(d=>d.value || d.v || d.n));
  return (
    <div style={{display:"flex", flexDirection:"column", gap:10}}>
      {data.map((d,i) => {
        const v = d.value ?? d.v ?? d.n;
        const pct = (v/m)*100;
        return (
          <div key={i}>
            <div className="between" style={{marginBottom:4}}>
              <span style={{fontSize:12.5}}>{d.name}</span>
              <span className="small mono">{fmt(v)}</span>
            </div>
            <div className="progress" style={{height:6}}>
              <span style={{width: pct+"%", background: d.color || "linear-gradient(90deg,#5FD6D0,#4A90E2)"}}/>
            </div>
          </div>
        );
      })}
    </div>
  );
}

function VertBars({ data, height=160, color="#5FD6D0", fmt=v=>v }) {
  const W=520, H=height, padL=36, padR=8, padT=14, padB=24;
  const innerW = W-padL-padR, innerH = H-padT-padB;
  const max = Math.max(...data.map(d=>d.v))*1.2;
  const bw = innerW/data.length * 0.55;
  return (
    <svg className="chart" viewBox={`0 0 ${W} ${H}`} style={{height, width:"100%"}}>
      {[0,1,2,3].map(i => {
        const y = padT + (innerH/3)*i;
        return <line key={i} x1={padL} x2={padL+innerW} y1={y} y2={y} className="grid-line"/>;
      })}
      {data.map((d,i) => {
        const x = padL + (innerW/data.length)*i + (innerW/data.length - bw)/2;
        const h = (d.v/max)*innerH;
        const y = padT + innerH - h;
        const id = "vb-"+i;
        return (
          <g key={i}>
            <defs>
              <linearGradient id={id} x1="0" y1="0" x2="0" y2="1">
                <stop offset="0%" stopColor={color} stopOpacity="0.95"/>
                <stop offset="100%" stopColor={color} stopOpacity="0.4"/>
              </linearGradient>
            </defs>
            <rect x={x} y={y} width={bw} height={h} fill={`url(#${id})`} rx="3"/>
            <text x={x+bw/2} y={H-8} textAnchor="middle">{d.x}</text>
            <text x={x+bw/2} y={y-4} textAnchor="middle" fill="currentColor">{fmt(d.v)}</text>
          </g>
        );
      })}
    </svg>
  );
}

window.Charts = { Sparkline, LineChart, Donut, BarsH, VertBars };
