'use client'
// src/components/charts/BarChart.tsx
// Input: data [{label, value}], height, colors
// Output: animated SVG bar chart with staggered height entry
// Rationale: used for FFT spectra and other distribution charts

import { useMemo, useEffect, useRef, useState } from 'react'

export interface BarDataItem {
  label: string
  value: number
  color?: string
}

export interface BarChartProps {
  data: BarDataItem[]
  height?: number
  color?: string
  className?: string
  showLabels?: boolean
}

const PAD = { top: 12, right: 8, bottom: 28, left: 8 }
const DEFAULT_COLOR = '#3DB8E8'

export function BarChart({
  data,
  height = 200,
  color = DEFAULT_COLOR,
  className,
  showLabels = true,
}: BarChartProps) {
  const containerRef = useRef<HTMLDivElement>(null)
  const [width, setWidth] = useState(400)
  const [animated, setAnimated] = useState<boolean[]>([])

  useEffect(() => {
    const el = containerRef.current
    if (!el) return
    const ro = new ResizeObserver((entries) => {
      const w = entries[0]?.contentRect.width
      if (w) setWidth(w)
    })
    ro.observe(el)
    setWidth(el.offsetWidth || 400)
    return () => ro.disconnect()
  }, [])

  // Stagger bars
  useEffect(() => {
    data.forEach((_, i) => {
      setTimeout(() => {
        setAnimated((prev) => {
          const next = [...prev]
          next[i] = true
          return next
        })
      }, i * 30)
    })
  }, [data])

  const maxVal = useMemo(() => Math.max(...data.map((d) => d.value), 1), [data])
  const chartW = width - PAD.left - PAD.right
  const chartH = height - PAD.top - PAD.bottom
  const barW = Math.max(4, chartW / data.length - 3)

  return (
    <div ref={containerRef} className={className} style={{ height }}>
      <svg width={width} height={height} viewBox={`0 0 ${width} ${height}`} fill="none">
        {data.map((item, i) => {
          const x = PAD.left + i * (chartW / data.length) + (chartW / data.length - barW) / 2
          const fullH = (item.value / maxVal) * chartH
          const barH = animated[i] ? fullH : 0
          const barY = PAD.top + chartH - barH
          const barColor = item.color ?? color

          return (
            <g key={i}>
              {/* Ghost bar */}
              <rect
                x={x}
                y={PAD.top}
                width={barW}
                height={chartH}
                fill="#111B28"
                rx={3}
              />
              {/* Actual bar */}
              <rect
                x={x}
                y={barY}
                width={barW}
                height={barH}
                fill={barColor}
                rx={3}
                style={{
                  transition: `y 0.4s cubic-bezier(0.16,1,0.3,1), height 0.4s cubic-bezier(0.16,1,0.3,1)`,
                }}
              />
              {/* Label */}
              {showLabels && (
                <text
                  x={x + barW / 2}
                  y={height - 8}
                  textAnchor="middle"
                  fontSize={9}
                  fill="#4E6070"
                  fontFamily="var(--font-jetbrains-mono), monospace"
                >
                  {item.label.length > 4 ? item.label.slice(0, 4) : item.label}
                </text>
              )}
            </g>
          )
        })}
      </svg>
    </div>
  )
}
