'use client';

// Tiny SVG waveform for headers / track labels. Accepts pre-computed peaks
// (from lib/audio/waveform-peaks) so the renderer is cheap and re-renders
// only when the asset changes.

import { useEffect, useRef } from 'react';
import type { WaveformPeaks } from '@/lib/audio/waveform-peaks';

interface Props {
  peaks: WaveformPeaks | null;
  width?: number;
  height?: number;
  color?: string;
  fadeIn?: boolean;
  fadeOut?: boolean;
}

export function MiniWaveform({
  peaks,
  width = 80,
  height = 24,
  color = '#ff8a3d',
  fadeIn = false,
  fadeOut = false,
}: Props) {
  const ref = useRef<SVGSVGElement | null>(null);

  useEffect(() => {
    // Force re-mount via key when peaks change — simpler than imperative.
  }, [peaks]);

  if (!peaks) {
    return (
      <div
        style={{ width, height }}
        className="flex items-center justify-center text-[9px] text-capcut-muted/50"
      >
        ─
      </div>
    );
  }

  const { positive, negative } = peaks;
  const n = positive.length;
  if (n === 0) return null;
  const half = height / 2;
  const xStep = width / n;
  const points: string[] = [];
  for (let i = 0; i < n; i++) {
    const x = i * xStep;
    const yTop = half - positive[i] * (half - 1);
    const yBot = half + negative[i] * (half - 1);
    points.push(`${x.toFixed(2)},${yTop.toFixed(2)}`);
  }
  const topPath = `M0,${half} L${points.join(' L')} L${width},${half} Z`;
  // Bottom half mirror
  const botPoints: string[] = [];
  for (let i = 0; i < n; i++) {
    const x = i * xStep;
    const y = half + negative[i] * (half - 1);
    botPoints.push(`${x.toFixed(2)},${y.toFixed(2)}`);
  }
  const botPath = `M0,${half} L${botPoints.join(' L')} L${width},${half} Z`;

  // Optional fade-in/out overlay
  const fadeOverlay = (fadeIn || fadeOut)
    ? `linear-gradient(${
        fadeIn && fadeOut
          ? '90deg, transparent 0%, color 10%, color 90%, transparent 100%'
          : fadeIn
            ? '90deg, transparent 0%, color 20%'
            : '270deg, transparent 0%, color 20%'
      })`
    : undefined;

  return (
    <svg
      ref={ref}
      width={width}
      height={height}
      viewBox={`0 0 ${width} ${height}`}
      preserveAspectRatio="none"
      className="block"
      style={fadeOverlay ? ({ WebkitMaskImage: fadeOverlay, maskImage: fadeOverlay } as React.CSSProperties) : undefined}
    >
      <path d={topPath} fill={color} fillOpacity={0.6} />
      <path d={botPath} fill={color} fillOpacity={0.6} />
      <line x1={0} y1={half} x2={width} y2={half} stroke={color} strokeOpacity={0.3} strokeWidth={0.5} />
    </svg>
  );
}