// tdd-guard:skip — pure visualization; aggregation + tests live in lib/stopwatch/evaluation.ts
'use client'

import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  LabelList,
} from 'recharts'
import { formatSeconds, type ProcessAverage } from '@/lib/stopwatch/evaluation'

interface Props {
  data: ProcessAverage[]
}

/**
 * Diagram 2 — one bar per process, height = average cycle time (s).
 * X-axis: process names, Y-axis: average time. Outliers/invalid values are
 * already excluded upstream in {@link buildProcessAverages}.
 */
export default function StopwatchAverageChart({ data }: Props) {
  if (data.length === 0) {
    return (
      <div className="bg-card border border-border rounded-md p-6 text-center text-xs text-muted-foreground">
        Der Durchschnittsvergleich erscheint, sobald mindestens ein Prozess eine
        gültige Messung hat.
      </div>
    )
  }

  // Grow the bottom margin with the longest label so rotated names stay readable.
  const longest = data.reduce((max, d) => Math.max(max, d.stationName.length), 0)
  const bottomMargin = Math.min(120, 28 + longest * 5)

  return (
    <div className="bg-card border border-border rounded-md p-4 space-y-2">
      <header className="flex items-center justify-between gap-2">
        <h3 className="text-sm font-bold text-foreground">
          Durchschnittszeit pro Prozess
        </h3>
        <span className="text-xs text-muted-foreground">
          {data.length} Prozesse · Ø ohne Ausreißer
        </span>
      </header>
      <div className="w-full" style={{ height: Math.max(256, bottomMargin + 200) }}>
        <ResponsiveContainer>
          <BarChart
            data={data}
            margin={{ top: 16, right: 16, bottom: bottomMargin, left: 8 }}
          >
            <CartesianGrid stroke="var(--border)" strokeDasharray="3 3" />
            <XAxis
              dataKey="stationName"
              tick={{ fontSize: 10, fill: 'var(--muted-foreground)' }}
              interval={0}
              angle={-35}
              textAnchor="end"
              height={bottomMargin}
            />
            <YAxis
              tick={{ fontSize: 10, fill: 'var(--muted-foreground)' }}
              label={{
                value: 'Ø Zeit (s)',
                angle: -90,
                position: 'insideLeft',
                offset: 12,
                style: { fontSize: 10, fill: 'var(--muted-foreground)' },
              }}
              allowDecimals
            />
            <Tooltip
              contentStyle={{
                background: 'var(--popover)',
                border: '1px solid var(--border)',
                fontSize: 11,
                color: 'var(--popover-foreground)',
                borderRadius: 3,
              }}
              formatter={(value, _name, item) => {
                const num = typeof value === 'number' ? value : Number(value)
                const count = (item?.payload as ProcessAverage | undefined)?.count
                return [
                  `${formatSeconds(num)}${count != null ? ` · ${count} Messungen` : ''}`,
                  'Ø Zeit',
                ]
              }}
            />
            <Bar dataKey="avgSec" fill="var(--primary)" radius={[2, 2, 0, 0]}>
              <LabelList
                dataKey="avgSec"
                position="top"
                formatter={(v) => formatSeconds(Number(v ?? 0), 1)}
                style={{ fontSize: 10, fill: 'var(--muted-foreground)' }}
              />
            </Bar>
          </BarChart>
        </ResponsiveContainer>
      </div>
    </div>
  )
}
