/**
 * UX-4.3 — overview data-viz transforms + render safety.
 *
 * Renders the dashboard overview chart surface with a mocked `getStats`
 * payload through react-dom/server (no DOM/jsdom needed) and asserts the
 * produced SVG markup contains no `NaN` path data. Also unit-tests the pure
 * transforms in `@/lib/overview-charts` for finite, correctly-mapped output.
 *
 * @see docs/roadmaps/UX_INTEGRATION_BYTELYST.md (UX-4)
 */

import { describe, it, expect } from 'vitest';
import { createElement } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import OverviewCharts from '@/components/overview-charts';
import { statusSlices, typeSlices, priorityBars, overviewKpis } from '@/lib/overview-charts';
import type { TrackerStats } from '@/lib/tracker-client';

const STATS: TrackerStats = {
  productId: 'tracker-test',
  total: 42,
  byType: { bug: 10, feature: 30, task: 2 },
  byStatus: { open: 20, in_progress: 12, done: 10 },
  byPriority: { critical: 2, high: 10, medium: 20, low: 10 },
};

const EMPTY_STATS: TrackerStats = {
  productId: 'tracker-test',
  total: 0,
  byType: {},
  byStatus: {},
  byPriority: {},
};

describe('overview-charts transforms', () => {
  it('maps status/type entries to donut slices with finite values', () => {
    const slices = [...statusSlices(STATS), ...typeSlices(STATS)];
    expect(slices.length).toBe(6);
    for (const s of slices) {
      expect(Number.isFinite(s.value)).toBe(true);
      expect(s.value).toBeGreaterThanOrEqual(0);
      expect(s.color).toMatch(/var\(--bl-chart-/);
    }
    expect(statusSlices(STATS).find(s => s.id === 'open')?.value).toBe(20);
  });

  it('orders priority bars critical → low with finite values', () => {
    const bars = priorityBars(STATS);
    expect(bars.map(b => b.id)).toEqual(['critical', 'high', 'medium', 'low']);
    for (const b of bars) expect(Number.isFinite(b.value)).toBe(true);
  });

  it('coerces missing / non-finite KPIs to 0', () => {
    expect(overviewKpis(STATS)).toEqual({ total: 42, open: 20, inProgress: 12, done: 10 });
    expect(overviewKpis(EMPTY_STATS)).toEqual({ total: 0, open: 0, inProgress: 0, done: 0 });
  });
});

describe('OverviewCharts render safety', () => {
  it('renders mocked stats without NaN in the SVG paths', () => {
    const html = renderToStaticMarkup(createElement(OverviewCharts, { stats: STATS }));
    expect(html).toContain('<svg');
    expect(html).not.toContain('NaN');
    expect(html).toContain('42');
  });

  it('renders empty stats without NaN (empty donut ring)', () => {
    const html = renderToStaticMarkup(createElement(OverviewCharts, { stats: EMPTY_STATS }));
    expect(html).not.toContain('NaN');
  });
});
