// Dependency-free donut chart. data: [{ label, value, color }]
export default function DonutChart({ data = [], size = 180, thickness = 26, centerLabel, centerValue }) {
  const total = data.reduce((s, d) => s + d.value, 0) || 1;
  const r = (size - thickness) / 2;
  const c = 2 * Math.PI * r;
  let offset = 0;

  return (
    <div
      style={{
        display: 'flex',
        flexDirection: 'row',
        gap: '24px',
        alignItems: 'center',
        justifyContent: 'center',
        flexWrap: 'wrap',
        fontFamily: 'system-ui, sans-serif'
      }}
    >
      <div style={{ position: 'relative', width: `${size}px`, maxWidth: '100%', aspectRatio: '1 / 1' }}>
        <svg width="100%" height="100%" viewBox={`0 0 ${size} ${size}`}>
          <g transform={`rotate(-90 ${size / 2} ${size / 2})`}>
            <circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke="#F0F0F0" strokeWidth={thickness} />
            {data.map((d, i) => {
              const len = (d.value / total) * c;
              const seg = (
                <circle
                  key={i}
                  cx={size / 2}
                  cy={size / 2}
                  r={r}
                  fill="none"
                  stroke={d.color}
                  strokeWidth={thickness}
                  strokeDasharray={`${len} ${c - len}`}
                  strokeDashoffset={-offset}
                  strokeLinecap="butt"
                />
              );
              offset += len;
              return seg;
            })}
          </g>
        </svg>
        <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }}>
          <div style={{ fontSize: '2rem', fontWeight: 700, color: '#1e293b' }}>{centerValue ?? total}</div>
          <div style={{ fontSize: '0.75rem', color: '#64748b' }}>{centerLabel ?? 'Total'}</div>
        </div>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
        {data.map((d) => (
          <div key={d.label} style={{ display: 'flex', flexDirection: 'row', gap: '8px', alignItems: 'center' }}>
            <div style={{ width: '10px', height: '10px', borderRadius: '3px', backgroundColor: d.color }} />
            <div style={{ fontSize: '0.875rem', color: '#64748b', minWidth: '80px' }}>{d.label}</div>
            <div style={{ fontSize: '0.875rem', fontWeight: 600, color: '#1e293b' }}>{d.value.toLocaleString('en-IN')}</div>
          </div>
        ))}
      </div>
    </div>
  );
}
