'use client'
// src/components/analyses/FFTPanel.tsx
// Input: project: Project
// Output: FFT bar chart + RingMeter quality + stats panel
// Rationale: US13 — frequency spectrum with dominant modes annotation

import { useMemo } from 'react'
import { motion } from 'framer-motion'
import { BarChart } from '@/components/charts/BarChart'
import { RingMeter } from '@/components/charts/RingMeter'
import { Stat } from '@/components/ui/Stat'
import { generateFFT } from '@/lib/mock'
import type { Project } from '@/types'

interface FFTPanelProps {
  project: Project
}

// Stable per-project FFT params based on project id hash
function getFFTParams(projectId: string): { baseFreq: number; harmonics: number } {
  const params: Record<string, { baseFreq: number; harmonics: number }> = {
    'proj-001': { baseFreq: 0.48, harmonics: 4 },
    'proj-002': { baseFreq: 0.82, harmonics: 5 },
    'proj-005': { baseFreq: 0.65, harmonics: 3 },
    'proj-007': { baseFreq: 1.85, harmonics: 3 },
    'proj-009': { baseFreq: 0.72, harmonics: 4 },
  }
  return params[projectId] ?? { baseFreq: 2.3, harmonics: 3 }
}

export function FFTPanel({ project }: FFTPanelProps) {
  const { baseFreq, harmonics } = getFFTParams(project.id)

  const fftSeries = useMemo(
    () => generateFFT(baseFreq, harmonics, project.id, 25, 256),
    [project.id, baseFreq, harmonics]
  )

  // Downsample for display (256 bins → 64 bars)
  const barData = useMemo(() => {
    const step = 4
    const result = []
    for (let i = 0; i < fftSeries.points.length; i += step) {
      const chunk = fftSeries.points.slice(i, i + step)
      const maxPt = chunk.reduce((a, b) => (a.y > b.y ? a : b))
      result.push({
        label: `${maxPt.x.toFixed(1)}`,
        value: Math.round(maxPt.y * 1000) / 1000,
      })
    }
    return result
  }, [fftSeries])

  // Dominant frequency = highest amplitude bin
  const dominantFreq = useMemo(() => {
    const peak = fftSeries.points.reduce((a, b) => (a.y > b.y ? a : b))
    return Math.round(peak.x * 100) / 100
  }, [fftSeries])

  // Pseudo quality: 75-95 based on project
  const quality = useMemo(() => {
    let h = 0
    for (let i = 0; i < project.id.length; i++) {
      h = (h * 31 + project.id.charCodeAt(i)) >>> 0
    }
    return 75 + (h % 21)
  }, [project.id])

  // Damping: 1-8% typical for bridges/buildings
  const damping = useMemo(() => {
    let h = 0
    for (let i = 0; i < project.id.length; i++) {
      h = (h * 37 + project.id.charCodeAt(i)) >>> 0
    }
    return (1.2 + (h % 68) / 10).toFixed(1)
  }, [project.id])

  return (
    <motion.div
      initial={{ opacity: 0, y: 8 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.25, ease: [0.16, 1, 0.3, 1] }}
      className="flex gap-4"
    >
      {/* Main chart */}
      <div className="flex-1 bg-bg-elevated border border-bg-border rounded-lg p-4">
        <div className="mb-3 flex items-center justify-between">
          <span className="text-body-sm text-text-secondary font-medium">
            Spectre fréquentiel (FFT) — modes propres
          </span>
          <span className="text-caption text-text-muted">amplitude normalisée / Hz</span>
        </div>
        <BarChart
          data={barData}
          height={380}
          color="#3DB8E8"
          showLabels
        />
        <div className="mt-3 text-caption text-text-muted">
          Fondamentale : <span className="text-data-teal font-mono-small">{baseFreq} Hz</span>
          &nbsp;—&nbsp;
          {harmonics} harmoniques &nbsp;—&nbsp; Résolution : 0.098 Hz/bin
        </div>
      </div>

      {/* Side panel */}
      <div className="w-64 flex flex-col gap-3">
        <div className="bg-bg-elevated border border-bg-border rounded-lg p-4 flex flex-col items-center gap-3">
          <span className="text-caption text-text-muted uppercase tracking-[0.05em]">
            Qualité analyse
          </span>
          <RingMeter
            value={quality}
            max={100}
            label="qualité"
            color={quality >= 85 ? '#34D399' : quality >= 75 ? '#FBBF24' : '#F87171'}
            size={96}
            strokeWidth={8}
          />
          <span className="text-body text-text-secondary text-center">
            {quality >= 85 ? 'Excellente cohérence' : quality >= 75 ? 'Bonne cohérence' : 'Cohérence faible'}
          </span>
        </div>

        <div className="bg-bg-elevated border border-bg-border rounded-lg p-4 flex flex-col gap-4">
          <div>
            <Stat label="Fréquence dominante" value={dominantFreq} unit="Hz" digits={2} />
          </div>
          <div>
            <Stat label="Amortissement estimé" value={parseFloat(damping)} unit="%" digits={1} />
          </div>
          <div>
            <Stat label="Cohérence" value={quality} unit="%" digits={0} />
          </div>
        </div>

        <div className="bg-bg-elevated border border-bg-border rounded-lg p-4">
          <div className="text-caption text-text-muted uppercase tracking-[0.05em] mb-2">
            Modes identifiés
          </div>
          {Array.from({ length: Math.min(harmonics, 4) }, (_, i) => (
            <div key={i} className="flex items-center justify-between py-1 border-b border-bg-border last:border-0">
              <span className="text-caption text-text-secondary">Mode {i + 1}</span>
              <span className="font-mono-small text-data-blue">
                {(baseFreq * (i + 1)).toFixed(2)} Hz
              </span>
            </div>
          ))}
        </div>
      </div>
    </motion.div>
  )
}
