/**
 * Pure helpers that map TrackerStats into @bytelyst/charts + @bytelyst/data-viz
 * data shapes for the dashboard overview (UX-4).
 *
 * Kept separate from the page component so the transforms are unit-testable
 * (no DOM needed) and guaranteed to emit only finite numbers — protecting the
 * SVG charts from NaN path data.
 *
 * @see docs/roadmaps/UX_INTEGRATION_BYTELYST.md (UX-4)
 */

import type { DonutSlice, BarDatum } from '@bytelyst/charts';
import type { TrackerStats } from './tracker-client';

/** Cycle the bridged --bl-chart-* palette (maps onto tracker's --chart-1..5). */
export const CHART_PALETTE = [
  'var(--bl-chart-1)',
  'var(--bl-chart-2)',
  'var(--bl-chart-3)',
  'var(--bl-chart-4)',
  'var(--bl-chart-5)',
] as const;

const LABELS: Record<string, string> = {
  open: 'Open',
  in_progress: 'In Progress',
  done: 'Done',
  closed: 'Closed',
  wont_fix: "Won't Fix",
  bug: 'Bug',
  feature: 'Feature',
  task: 'Task',
  critical: 'Critical',
  high: 'High',
  medium: 'Medium',
  low: 'Low',
};

/** Coerce any value to a finite, non-negative number (no NaN reaches the SVG). */
const safe = (v: number | undefined): number =>
  typeof v === 'number' && Number.isFinite(v) ? Math.max(0, v) : 0;

function toSlices(entries: Record<string, number>): DonutSlice[] {
  return Object.entries(entries).map(([key, value], i) => ({
    id: key,
    value: safe(value),
    label: LABELS[key] ?? key,
    color: CHART_PALETTE[i % CHART_PALETTE.length],
  }));
}

export const statusSlices = (stats: TrackerStats): DonutSlice[] => toSlices(stats.byStatus);
export const typeSlices = (stats: TrackerStats): DonutSlice[] => toSlices(stats.byType);

/** Priority bars in a fixed, meaningful order (critical → low). */
export function priorityBars(stats: TrackerStats): BarDatum[] {
  const order = ['critical', 'high', 'medium', 'low'];
  return order
    .filter(key => key in stats.byPriority)
    .map((key, i) => ({
      id: key,
      value: safe(stats.byPriority[key]),
      label: LABELS[key] ?? key,
      color: CHART_PALETTE[i % CHART_PALETTE.length],
    }));
}

export interface OverviewKpis {
  total: number;
  open: number;
  inProgress: number;
  done: number;
}

export function overviewKpis(stats: TrackerStats): OverviewKpis {
  return {
    total: safe(stats.total),
    open: safe(stats.byStatus.open),
    inProgress: safe(stats.byStatus.in_progress),
    done: safe(stats.byStatus.done),
  };
}
