// tdd-guard:skip — pure visualization, logic + tests in lib/lsc-workshop/cycle-histogram.ts
'use client'

import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
} from 'recharts'
import { computeCycleHistogram, type CycleDatum } from '@/lib/lsc-workshop/cycle-histogram'

const DEFAULT_BIN_WIDTH_SEC = 5

interface Props {
  data: CycleDatum[]
  binWidthSec?: number
}

export default function WorkshopCycleHistogramChart({ data, binWidthSec = DEFAULT_BIN_WIDTH_SEC }: Props) {
  const chartData = computeCycleHistogram(data, binWidthSec)

  if (chartData.length === 0) {
    return (
      <div className="bg-card border border-border rounded-md p-6 text-center text-xs text-muted-foreground">
        Cycle-Time-Histogramm erscheint sobald die ersten Zykluszeiten erfasst sind.
      </div>
    )
  }

  return (
    <div className="bg-card border border-border rounded-md p-4 space-y-2">
      <header className="flex items-center justify-between">
        <h3 className="text-sm font-bold text-foreground">
          Cycle-Time Histogramm
        </h3>
        <span className="text-xs text-muted-foreground">
          Bin-Breite: {binWidthSec}s
        </span>
      </header>
      <div className="w-full h-64">
        <ResponsiveContainer>
          <BarChart data={chartData} margin={{ top: 8, right: 16, bottom: 24, left: 8 }}>
            <CartesianGrid stroke="var(--border)" strokeDasharray="3 3" />
            <XAxis
              dataKey="bin_label"
              tick={{ fontSize: 10, fill: 'var(--muted-foreground)' }}
              interval={0}
            />
            <YAxis
              tick={{ fontSize: 10, fill: 'var(--muted-foreground)' }}
              label={{
                value: 'Messungen',
                position: 'insideLeft',
                offset: 12,
                style: { fontSize: 10, fill: 'var(--muted-foreground)' },
              }}
              allowDecimals={false}
            />
            <Tooltip
              contentStyle={{
                background: 'var(--popover)',
                border: '1px solid var(--border)',
                fontSize: 11,
                color: 'var(--popover-foreground)',
                borderRadius: 3,
              }}
              formatter={(value) => {
                const num = typeof value === 'number' ? value : Number(value)
                return [
                  Number.isFinite(num)
                    ? num.toLocaleString('de-DE', { maximumFractionDigits: 0 })
                    : String(value),
                  'Messungen',
                ]
              }}
            />
            <Bar dataKey="count" fill="var(--primary)" radius={[2, 2, 0, 0]} />
          </BarChart>
        </ResponsiveContainer>
      </div>
    </div>
  )
}
