import { Card } from "@/shared/ui/Card.jsx";
import { DistributionPieChart } from "@/shared/charts/DistributionPieChart.jsx";

const GENDER_COLOR_TOKENS = {
  female: "--chart-red",
  male: "--chart-blue",
  unknown: "--stopped"
};

export function DashboardCharts({ overview }) {
  const genderDistribution = withGenderColors(overview?.genderDistribution);
  const appVersionDistribution = overview?.appVersionDistribution || [];

  return (
    <section className="overview-charts" aria-label="用户画像分布">
      <Card className="chart-card dashboard-distribution-card" component="article">
        <div className="card-head dashboard-distribution-card__head">
          <h3 className="card-title">性别人数分布</h3>
          <span>自然用户 · 已完成资料 · 排除机器人/快捷账号</span>
        </div>
        <DistributionPieChart ariaLabel="自然用户性别人数分布饼图" data={genderDistribution} />
      </Card>
      <Card className="chart-card dashboard-distribution-card" component="article">
        <div className="card-head dashboard-distribution-card__head">
          <h3 className="card-title">App 版本号人数分布</h3>
          <span>自然用户 · 最近一次成功登录版本</span>
        </div>
        <DistributionPieChart ariaLabel="自然用户最近一次成功登录 App 版本号人数分布饼图" data={appVersionDistribution} />
      </Card>
    </section>
  );
}

function withGenderColors(distribution) {
  return (Array.isArray(distribution) ? distribution : []).map((item) => ({
    ...item,
    // 性别颜色按稳定 key 固定，避免后端排序变化导致同一性别在刷新后换色。
    colorToken: GENDER_COLOR_TOKENS[String(item?.key || "").toLowerCase()]
  }));
}
