// Charts (SVG) for analytics dashboards

const ChartA = {};

ChartA.RevenueLine = function({ series, height = 110 }) {
  const W = 800, H = height, PAD = 8;
  const innerW = W - PAD*2, innerH = H - PAD*2;
  const max = Math.max(...series.flatMap(p => [p.now, p.prev]));
  const min = Math.min(...series.flatMap(p => [p.now, p.prev])) * 0.9;
  const x = (i) => PAD + (i / (series.length - 1)) * innerW;
  const y = (v) => PAD + innerH - ((v - min) / (max - min)) * innerH;
  const path = (k) => series.map((p, i) => `${i === 0 ? 'M' : 'L'}${x(i)},${y(p[k])}`).join(' ');
  const area = `${path('now')} L${x(series.length-1)},${PAD+innerH} L${x(0)},${PAD+innerH} Z`;
  return (
    <svg viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" style={{width:'100%', height:'100%', display:'block'}}>
      <defs>
        <linearGradient id="g1" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="rgba(229,57,53,0.20)"/>
          <stop offset="100%" stopColor="rgba(229,57,53,0)"/>
        </linearGradient>
      </defs>
      <path d={area} fill="url(#g1)"/>
      <path d={path('prev')} fill="none" stroke="#a8acc0" strokeWidth="1.4" strokeDasharray="4 4"/>
      <path d={path('now')} fill="none" stroke="#e53935" strokeWidth="2"/>
    </svg>
  );
};

ChartA.Sparkline = function({ values, color = '#00b4a0' }) {
  const W = 200, H = 36;
  const max = Math.max(...values), min = Math.min(...values);
  const x = (i) => (i / (values.length-1)) * W;
  const y = (v) => H - ((v - min) / (max - min || 1)) * (H - 4) - 2;
  const path = values.map((v,i) => `${i === 0 ? 'M' : 'L'}${x(i)},${y(v)}`).join(' ');
  return (
    <svg viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" className="sparkline">
      <path d={path} fill="none" stroke={color} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
};

ChartA.Donut = function({ slices, size = 120 }) {
  const total = slices.reduce((a,b) => a + b.value, 0);
  const r = size/2 - 8, cx = size/2, cy = size/2;
  let acc = 0;
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
      {slices.map((s, i) => {
        const start = acc / total * Math.PI * 2 - Math.PI/2;
        acc += s.value;
        const end = acc / total * Math.PI * 2 - Math.PI/2;
        const x1 = cx + r*Math.cos(start), y1 = cy + r*Math.sin(start);
        const x2 = cx + r*Math.cos(end),   y2 = cy + r*Math.sin(end);
        const large = (end - start) > Math.PI ? 1 : 0;
        return <path key={i} d={`M${cx},${cy} L${x1},${y1} A${r},${r} 0 ${large} 1 ${x2},${y2} Z`} fill={s.color} stroke="white" strokeWidth="1.5"/>;
      })}
      <circle cx={cx} cy={cy} r={r*0.55} fill="white"/>
    </svg>
  );
};

ChartA.Waterfall = function({ items }) {
  const W = 900, H = 280, PAD_L = 60, PAD_R = 20, PAD_T = 24, PAD_B = 60;
  const innerW = W - PAD_L - PAD_R, innerH = H - PAD_T - PAD_B;
  const start = items[0].value, end = items[items.length-1].value;
  let running = start;
  const points = items.map((it, i) => {
    const before = running;
    if (i > 0 && i < items.length - 1) running += it.value;
    return { ...it, before, after: running, idx: i };
  });
  const all = points.flatMap(p => [p.before, p.after, p.value]);
  const max = Math.max(...all, 0) * 1.05;
  const min = Math.min(...all, 0) * 1.05;
  const yScale = (v) => PAD_T + innerH - ((v - min) / (max - min)) * innerH;
  const barW = innerW / points.length * 0.55;
  const xc = (i) => PAD_L + (i + 0.5) * (innerW / points.length);
  return (
    <svg viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="xMidYMid meet" style={{width:'100%', height:'100%'}}>
      {/* zero line */}
      <line x1={PAD_L} x2={W-PAD_R} y1={yScale(0)} y2={yScale(0)} stroke="#d8dae6" strokeDasharray="3 3"/>
      {points.map((p, i) => {
        const isFirst = i === 0, isLast = i === points.length - 1;
        const isAnchor = isFirst || isLast;
        let top, h, color;
        if (isAnchor) {
          top = yScale(Math.max(p.value, 0));
          h = Math.abs(yScale(p.value) - yScale(0));
          color = '#1e1e5a';
        } else {
          top = yScale(Math.max(p.before, p.after));
          h = Math.abs(yScale(p.after) - yScale(p.before));
          color = p.value >= 0 ? '#00b4a0' : '#e53935';
        }
        return (
          <g key={i}>
            <rect x={xc(i) - barW/2} y={top} width={barW} height={Math.max(h, 1)} fill={color} rx="3"/>
            {!isAnchor && i < points.length - 1 && (
              <line x1={xc(i) + barW/2} x2={xc(i+1) - barW/2} y1={yScale(p.after)} y2={yScale(p.after)} stroke="#a8acc0" strokeDasharray="2 3"/>
            )}
            <text x={xc(i)} y={top - 6} textAnchor="middle" fontSize="11" fontWeight="700" fill={isAnchor ? '#1e1e5a' : color}>
              {isAnchor ? `€${(p.value/1000).toFixed(0)}k` : `${p.value >= 0 ? '+' : ''}€${(p.value/1000).toFixed(0)}k`}
            </text>
            <text x={xc(i)} y={H - 32} textAnchor="middle" fontSize="11" fill="#2a2a4a" fontWeight="600">
              {p.label}
            </text>
            <text x={xc(i)} y={H - 18} textAnchor="middle" fontSize="10" fill="#7e8298">
              {p.sub || ''}
            </text>
          </g>
        );
      })}
    </svg>
  );
};

ChartA.Heatmap = function({ matrix }) {
  const cellW = 56, cellH = 30, gap = 3, labelW = 72;
  const cols = Math.max(...matrix.map(r => r.retention.length));
  const W = labelW + cols * (cellW + gap) + 60;
  const H = matrix.length * (cellH + gap) + 30;
  return (
    <svg viewBox={`0 0 ${W} ${H}`} style={{width:'100%', height: H}}>
      {matrix.map((row, ri) => (
        <g key={ri} transform={`translate(0, ${ri * (cellH + gap) + 24})`}>
          <text x={0} y={cellH/2 + 4} fontSize="11" fill="#2a2a4a" fontWeight="600">{row.month}</text>
          {row.retention.map((v, ci) => {
            const opacity = ci === 0 ? 1 : Math.max(0.1, v / 100);
            return (
              <g key={ci} transform={`translate(${labelW + ci*(cellW+gap)}, 0)`}>
                <rect width={cellW} height={cellH} rx="4" fill={`rgba(0,180,160,${opacity})`}/>
                <text x={cellW/2} y={cellH/2 + 4} textAnchor="middle" fontSize="10" fontWeight="700" fill={opacity > 0.45 ? 'white' : '#2a2a4a'}>{v}%</text>
              </g>
            );
          })}
          <text x={labelW + row.retention.length*(cellW+gap) + 8} y={cellH/2 + 4} fontSize="10" fill="#7e8298">{row.size} klanten</text>
        </g>
      ))}
      <g transform="translate(0, 0)">
        {Array.from({length: cols}).map((_, ci) => (
          <text key={ci} x={labelW + ci*(cellW+gap) + cellW/2} y={16} fontSize="10" textAnchor="middle" fill="#7e8298">M+{ci}</text>
        ))}
      </g>
    </svg>
  );
};

ChartA.Funnel = function({ steps }) {
  const W = 800, H = 220, PAD = 12;
  const max = steps[0].val;
  const stepW = (W - PAD*2) / steps.length;
  return (
    <svg viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="xMidYMid meet" style={{width:'100%', height:'100%'}}>
      {steps.map((s, i) => {
        const ratio = s.val / max;
        const h = ratio * (H - 80);
        const x = PAD + i*stepW;
        const y = (H - 60 - h)/2 + 10;
        return (
          <g key={i}>
            <rect x={x + 6} y={y} width={stepW - 12} height={h} rx="6" fill="#1e1e5a" opacity={0.85 - i*0.1}/>
            <text x={x + stepW/2} y={y - 8} textAnchor="middle" fontSize="13" fontWeight="700" fill="#1e1e5a">{(s.val/1000).toFixed(0)}k</text>
            <text x={x + stepW/2} y={y + h + 18} textAnchor="middle" fontSize="11" fontWeight="600" fill="#2a2a4a">{s.step}</text>
            <text x={x + stepW/2} y={y + h + 32} textAnchor="middle" fontSize="10" fill="#7e8298">{s.pct}% · Δ{s.delta}pp</text>
          </g>
        );
      })}
    </svg>
  );
};

window.ChartA = ChartA;
