// Region trend: monthly cost + potential savings, one point per run, from
// /api/v1/regions/<key>/history (newest-first; reversed here to chart left
// to right).

import type { SummaryRow } from "@/lib/api-types";
import { utc8DateOf } from "@/lib/time";
import { Empty } from "@/components/ui/Empty";
import { CostSavingsTrendChart } from "@/components/CostSavingsTrendChart";

export function regionTrendPoints(points: SummaryRow[]): Array<{
  date: string;
  cost: number | null;
  savings: number | null;
}> {
  return [...points]
    .reverse()
    .map((p) => ({
      date: utc8DateOf(p.finishedAt),
      cost: typeof p.monthlyCostUsd === "number" ? p.monthlyCostUsd : null,
      savings:
        typeof p.potentialMonthlySavingsUsd === "number" ? p.potentialMonthlySavingsUsd : null,
    }));
}

export function RegionTrendChart({ points }: { points: SummaryRow[] }) {
  const data = regionTrendPoints(points);
  if (data.length < 2) {
    return <Empty>Need at least two runs for a trend.</Empty>;
  }
  return <CostSavingsTrendChart data={data} />;
}
