// Reusable advanced chart components — donut/pie and waterfall (pure SVG)

function DonutChart({ segments, size = 180, thickness = 30, centerLabel, centerSub }) {
  // segments: [{ label, value, color }]
  const total = segments.reduce((s, x) => s + x.value, 0) || 1;
  const r = (size - thickness) / 2;
  const cx = size / 2,cy = size / 2;
  const circ = 2 * Math.PI * r;
  let offset = 0;
  const arcs = segments.map((seg) => {
    const frac = seg.value / total;
    const dash = frac * circ;
    const arc = { ...seg, frac, dash, offset };
    offset += dash;
    return arc;
  });
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 20 }}>
      <svg width={size} height={size} style={{ flexShrink: 0 }}>
        <g transform={`rotate(-90 ${cx} ${cy})`}>
          {arcs.map((a, i) =>
          <circle
            key={i}
            cx={cx} cy={cy} r={r}
            fill="none"
            stroke={a.color}
            strokeWidth={thickness}
            strokeDasharray={`${a.dash} ${circ - a.dash}`}
            strokeDashoffset={-a.offset} />

          )}
        </g>
        {centerLabel != null &&
        <text x={cx} y={cy - 2} textAnchor="middle" fontSize="22" fontWeight="600" fill="var(--ink)" fontFamily="Geist Mono" style={{ letterSpacing: '-0.02em' }}>{centerLabel}</text>
        }
        {centerSub &&
        <text x={cx} y={cy + 16} textAnchor="middle" fontSize="10.5" fill="var(--ink-3)">{centerSub}</text>
        }
      </svg>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8, flex: 1, minWidth: 0 }}>
        {arcs.map((a, i) =>
        <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12.5 }}>
            <span style={{ width: 10, height: 10, borderRadius: 3, background: a.color, flexShrink: 0 }}></span>
            <span style={{ flex: 1, minWidth: 0, color: 'var(--ink-2)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{a.label}</span>
            <span className="num" style={{ fontWeight: 500 }}>{a.display != null ? a.display : a.value}</span>
            <span className="num" style={{ color: 'var(--ink-3)', width: 38, textAlign: 'right' }}>{Math.round(a.frac * 100)}%</span>
          </div>
        )}
      </div>
    </div>);

}

function WaterfallChart({ steps, height = 220, fmtVal }) {
  // steps: [{ label, value, type: 'start'|'add'|'subtract'|'total' }]
  const fmtv = fmtVal || ((v) => v);
  // Compute running cumulative for floating bars
  let running = 0;
  const bars = steps.map((s) => {
    if (s.type === 'start' || s.type === 'total') {
      const bar = { ...s, base: 0, top: s.value, abs: s.value };
      running = s.value;
      return bar;
    } else if (s.type === 'subtract') {
      const top = running;
      running -= Math.abs(s.value);
      return { ...s, base: running, top, abs: Math.abs(s.value) };
    } else {// add
      const base = running;
      running += Math.abs(s.value);
      return { ...s, base, top: running, abs: Math.abs(s.value) };
    }
  });
  const maxVal = Math.max(...bars.map((b) => b.top), 1);
  const W = 100; // percentage-based
  const colW = 100 / steps.length;
  const colorFor = (t) => t === 'start' ? 'var(--ink-3)' : t === 'total' ? 'var(--won)' : t === 'subtract' ? 'var(--lost)' : 'var(--s-in_progress)';

  return (
    <div>
      <div style={{ position: 'relative', height, borderBottom: '1px solid var(--border)' }}>
        {bars.map((b, i) => {
          const hPct = (b.top - b.base) / maxVal * 100;
          const yPct = (1 - b.top / maxVal) * 100;
          const left = i * colW;
          return (
            <div key={i} style={{ position: 'absolute', left: left + '%', width: colW + '%', height: '100%' }}>
              <div style={{
                position: 'absolute',
                top: yPct + '%',
                height: Math.max(hPct, 0.8) + '%',
                left: '18%', right: '18%',
                background: colorFor(b.type),
                borderRadius: 3,
                minHeight: 2
              }} title={`${b.label}: ${fmtv(b.abs)}`}></div>
              <div style={{ position: 'absolute', top: `calc(${yPct}% - 16px)`, left: 0, right: 0, textAlign: 'center', fontWeight: 500, color: 'var(--ink-2)', fontSize: "13px" }} className="num">
                {b.type === 'subtract' ? `(${fmtv(b.abs)})` : fmtv(b.abs)}
              </div>
              {/* connector line */}
              {i < bars.length - 1 &&
              <div style={{ position: 'absolute', top: (1 - b.top / maxVal) * 100 + '%', right: 0, width: colW + '%', borderTop: '1px dashed var(--border-strong)' }}></div>
              }
            </div>);

        })}
      </div>
      <div style={{ display: 'flex' }}>
        {bars.map((b, i) =>
        <div key={i} style={{ width: colW + '%', textAlign: 'center', fontSize: 10.5, color: 'var(--ink-3)', paddingTop: 6 }}>{b.label}</div>
        )}
      </div>
    </div>);

}

window.DonutChart = DonutChart;
window.WaterfallChart = WaterfallChart;