import React from 'react';
import type { PieChartProps } from '../../types.js';
const COLORS = ['#6366f1','#8b5cf6','#22c55e','#3b82f6','#f59e0b','#ef4444','#ec4899','#f97316'];
export const PieChart: React.FC<PieChartProps> = ({ segments = [], donut = false, title, showLegend = true }) => {
  const total = segments.reduce((s, seg) => s + seg.value, 0) || 1;
  const r = 70, cx = 90, cy = 90;
  let cumAngle = -Math.PI / 2;
  const arcs = segments.map((seg, i) => {
    const frac = seg.value / total, angle = frac * Math.PI * 2;
    const startAngle = cumAngle, endAngle = cumAngle + angle;
    cumAngle = endAngle;
    const x1 = cx + r * Math.cos(startAngle), y1 = cy + r * Math.sin(startAngle);
    const x2 = cx + r * Math.cos(endAngle), y2 = cy + r * Math.sin(endAngle);
    const color = seg.color || COLORS[i % COLORS.length];
    if (frac >= 0.9999) return <circle key={i} cx={cx} cy={cy} r={r} fill={color} />;
    return <path key={i} d={`M${cx},${cy} L${x1},${y1} A${r},${r} 0 ${angle > Math.PI ? 1 : 0},1 ${x2},${y2} Z`} fill={color} />;
  });
  return (
    <div className="chart-container">
      {title && <div className="chart-title">{title}</div>}
      <div className="pie-chart-layout">
        <svg viewBox="0 0 180 180" className="pie-chart-svg">
          {arcs}
          {donut && <circle cx={cx} cy={cy} r={r * 0.55} fill="#1a1d27" />}
          {donut && <text x={cx} y={cy + 5} textAnchor="middle" className="pie-center-text">{total.toLocaleString()}</text>}
        </svg>
        {showLegend && (
          <div className="pie-legend">
            {segments.map((seg, i) => (
              <div className="pie-legend-item" key={i}>
                <span className="pie-legend-dot" style={{ background: seg.color || COLORS[i % COLORS.length] }} />
                <span className="pie-legend-label">{seg.label}</span>
                <span className="pie-legend-value">{((seg.value / total) * 100).toFixed(1)}%</span>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
};
