/* ============ Rehab donut (SVG) ============ */
function RehabDonut({ items, total }) {
  const data = items
    .filter((d) => Number(d.v) > 0)
    .sort((a, b) => b.v - a.v)
    .map((d, i) => ({ ...d, color: CHART_PALETTE[i % CHART_PALETTE.length] }));

  const size = 188, stroke = 30, r = (size - stroke) / 2, c = 2 * Math.PI * r, cx = size / 2;
  let offset = 0;
  const [hover, setHover] = React.useState(null);

  if (total <= 0) {
    return <div style={{ textAlign: 'center', color: 'var(--muted)', fontSize: 13, padding: '40px 0' }}>Add rehab costs to see the breakdown.</div>;
  }

  return (
    <div className="donut-wrap">
      <div style={{ position: 'relative', width: size, height: size }}>
        <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ transform: 'rotate(-90deg)' }}>
          <circle cx={cx} cy={cx} r={r} fill="none" stroke="var(--paper-2)" strokeWidth={stroke} />
          {data.map((d, i) => {
            const frac = d.v / total;
            const len = frac * c;
            const seg = (
              <circle
                key={i} cx={cx} cy={cx} r={r} fill="none"
                stroke={d.color}
                strokeWidth={hover === i ? stroke + 4 : stroke}
                strokeDasharray={`${len} ${c - len}`}
                strokeDashoffset={-offset}
                style={{ transition: 'stroke-width .15s', cursor: 'pointer' }}
                onMouseEnter={() => setHover(i)}
                onMouseLeave={() => setHover(null)}
              />
            );
            offset += len;
            return seg;
          })}
        </svg>
        <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', textAlign: 'center', pointerEvents: 'none' }}>
          <div className="donut-center" style={{ fontSize: 22, fontWeight: 700, color: 'var(--green-900)' }}>
            {hover !== null ? fmtPct((data[hover].v / total) * 100) : fmtMoney(total)}
          </div>
          <div style={{ fontSize: 11.5, color: 'var(--muted)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '.06em', marginTop: 2 }}>
            {hover !== null ? data[hover].k : 'Total rehab'}
          </div>
        </div>
      </div>
      <div className="legend">
        {data.map((d, i) => (
          <div className="legend-item" key={i}
            onMouseEnter={() => setHover(i)} onMouseLeave={() => setHover(null)}
            style={{ opacity: hover === null || hover === i ? 1 : 0.45, transition: 'opacity .12s' }}>
            <span className="sw" style={{ background: d.color }}></span>
            <span className="nm">{d.k}</span>
            <span className="pc">{fmtPct((d.v / total) * 100)}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ============ Cost & profit bars ============ */
function CostBars({ rows }) {
  const max = Math.max(...rows.map((r) => Math.abs(r.value)), 1);
  return (
    <div className="bars">
      {rows.map((r, i) => {
        const pct = (Math.abs(r.value) / max) * 100;
        const outside = pct < 26;
        return (
          <div className="bar-row" key={i}>
            <div className="bl">{r.label}</div>
            <div className="bar-track">
              <div className={'bar-fill' + (outside ? ' out' : '')}
                style={{ width: outside ? 'auto' : pct + '%', background: r.color }}>
                {outside ? null : fmtMoney(r.value)}
              </div>
              {outside ? (
                <div style={{ position: 'absolute', top: 0, left: 0, height: '100%', display: 'flex', alignItems: 'center', gap: 8 }}>
                  <div style={{ width: 4, height: '100%', borderRadius: 4, background: r.color }}></div>
                  <span style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--ink-2)', fontVariantNumeric: 'tabular-nums' }}>{fmtMoney(r.value)}</span>
                </div>
              ) : null}
            </div>
          </div>
        );
      })}
    </div>
  );
}

Object.assign(window, { RehabDonut, CostBars });
