// Hook that lazily computes + caches waveform peaks for a single asset.
// The actual decode work happens in a Web Worker-style pattern: we return
// the cached value immediately and trigger async compute in the background.

'use client';

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

/**
 * Compute waveform peaks for a single asset. Returns null until the first
 * decode completes; the result is cached so subsequent hook calls return
 * the same data immediately.
 */
export function usePeaks(
  assetId: string | null | undefined,
  source: Blob | ArrayBuffer | null | undefined,
  enabled = true,
): WaveformPeaks | null {
  const [peaks, setPeaks] = useState<WaveformPeaks | null>(null);

  useEffect(() => {
    if (!assetId || !source || !enabled) {
      setPeaks(null);
      return;
    }
    let cancelled = false;
    (async () => {
      try {
        const result = await getOrComputePeaks(assetId, source);
        if (cancelled) return;
        setPeaks(result);
      } catch {
        /* ignore decode errors */
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [assetId, source, enabled]);

  return peaks;
}