'use client'
// src/components/charts/LineChart.tsx
// Input: series (DataSeries[]), height, showGrid, showAxis
// Output: animated SVG multi-series line chart with draw-on-mount
// Rationale: main chart for amplitude and FFT analysis screens

import { useMemo, useEffect, useRef, useState } from 'react'
import type { DataSeries } from '@/types'

export interface LineChartProps {
  series: DataSeries[]
  height?: number
  showGrid?: boolean
  showAxis?: boolean
  className?: string
}

const COLORS = ['#3DB8E8', '#2DD4BF', '#818CF8', '#FBBF24', '#FB7185']
const PAD = { top: 12, right: 12, bottom: 32, left: 44 }

export function LineChart({
  series,
  height = 240,
  showGrid = true,
  showAxis = true,
  className,
}: LineChartProps) {
  const svgRef = useRef<SVGSVGElement>(null)
  const containerRef = useRef<HTMLDivElement>(null)
  const [width, setWidth] = useState(600)
  const [drawn, setDrawn] = useState(false)

  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 || 600)
    return () => ro.disconnect()
  }, [])

  useEffect(() => {
    const t = setTimeout(() => setDrawn(true), 50)
    return () => clearTimeout(t)
  }, [])

  const chartW = width - PAD.left - PAD.right
  const chartH = height - PAD.top - PAD.bottom

  const { allPoints, minY, maxY, minX, maxX } = useMemo(() => {
    const all = series.flatMap((s) => s.points)
    return {
      allPoints: all,
      minY: Math.min(...all.map((p) => p.y)),
      maxY: Math.max(...all.map((p) => p.y)),
      minX: Math.min(...all.map((p) => p.x)),
      maxX: Math.max(...all.map((p) => p.x)),
    }
  }, [series])

  function scaleX(x: number) {
    return ((x - minX) / (maxX - minX || 1)) * chartW
  }
  function scaleY(y: number) {
    return chartH - ((y - minY) / (maxY - minY || 1)) * chartH
  }

  const yTicks = useMemo(() => {
    const count = 4
    const step = (maxY - minY) / count
    return Array.from({ length: count + 1 }, (_, i) => minY + i * step)
  }, [minY, maxY])

  const xTicks = useMemo(() => {
    const count = 5
    const step = (maxX - minX) / count
    return Array.from({ length: count + 1 }, (_, i) => minX + i * step)
  }, [minX, maxX])

  function buildPath(points: Array<{ x: number; y: number }>) {
    if (points.length < 2) return ''
    return points
      .map((p, i) => `${i === 0 ? 'M' : 'L'}${(PAD.left + scaleX(p.x)).toFixed(1)},${(PAD.top + scaleY(p.y)).toFixed(1)}`)
      .join(' ')
  }

  return (
    <div ref={containerRef} className={className} style={{ height }}>
      <svg
        ref={svgRef}
        width={width}
        height={height}
        viewBox={`0 0 ${width} ${height}`}
        fill="none"
        aria-label="Line chart"
      >
        {/* Grid lines */}
        {showGrid && yTicks.map((tick, i) => {
          const y = PAD.top + scaleY(tick)
          return (
            <line
              key={i}
              x1={PAD.left}
              y1={y}
              x2={PAD.left + chartW}
              y2={y}
              stroke="#1E2D3D"
              strokeWidth={1}
            />
          )
        })}

        {/* Y axis labels */}
        {showAxis && yTicks.map((tick, i) => (
          <text
            key={i}
            x={PAD.left - 6}
            y={PAD.top + scaleY(tick)}
            textAnchor="end"
            dominantBaseline="middle"
            fontSize={10}
            fill="#4E6070"
            fontFamily="var(--font-jetbrains-mono), monospace"
          >
            {tick.toFixed(1)}
          </text>
        ))}

        {/* X axis labels */}
        {showAxis && xTicks.map((tick, i) => (
          <text
            key={i}
            x={PAD.left + scaleX(tick)}
            y={height - 8}
            textAnchor="middle"
            fontSize={10}
            fill="#4E6070"
            fontFamily="var(--font-jetbrains-mono), monospace"
          >
            {tick.toFixed(0)}
          </text>
        ))}

        {/* Series paths */}
        {series.map((s, si) => {
          const color = s.color ?? COLORS[si % COLORS.length]
          const d = buildPath(s.points)
          if (!d) return null

          // Calculate total path length for animation
          return (
            <g key={si}>
              {/* Area fill */}
              <path
                d={`${d} L${(PAD.left + scaleX(s.points[s.points.length - 1].x)).toFixed(1)},${(PAD.top + chartH).toFixed(1)} L${PAD.left},${(PAD.top + chartH).toFixed(1)} Z`}
                fill={color}
                fillOpacity={0.08}
              />
              {/* Line */}
              <path
                d={d}
                stroke={color}
                strokeWidth={2}
                strokeLinecap="round"
                strokeLinejoin="round"
                style={{
                  strokeDasharray: drawn ? 'none' : '10000',
                  strokeDashoffset: drawn ? '0' : '10000',
                  transition: drawn ? `stroke-dashoffset 0.6s cubic-bezier(0.16,1,0.3,1)` : 'none',
                }}
              />
            </g>
          )
        })}
      </svg>
    </div>
  )
}
