import React, { useCallback } from 'react';
import { Audio, interpolate, useCurrentFrame, useVideoConfig, staticFile } from 'remotion';
import type { AudioConfig } from '../renderer';

const DEFAULTS = {
  volume: 0.3,
  fadeInSeconds: 0.5,
  fadeOutSeconds: 1.0,
} as const;

export const BackgroundMusic: React.FC<{ audio: AudioConfig }> = ({ audio }) => {
  const frame = useCurrentFrame();
  const { fps, durationInFrames } = useVideoConfig();

  const baseVolume = audio.volume ?? DEFAULTS.volume;
  const fadeInFrames = Math.round((audio.fadeInSeconds ?? DEFAULTS.fadeInSeconds) * fps);
  const fadeOutFrames = Math.round((audio.fadeOutSeconds ?? DEFAULTS.fadeOutSeconds) * fps);
  const fadeOutStart = durationInFrames - fadeOutFrames;

  const volumeFunction = useCallback(() => {
    if (frame < fadeInFrames) {
      return interpolate(frame, [0, fadeInFrames], [0, baseVolume], {
        extrapolateLeft: 'clamp',
        extrapolateRight: 'clamp',
      });
    }
    if (frame >= fadeOutStart) {
      return interpolate(frame, [fadeOutStart, durationInFrames], [baseVolume, 0], {
        extrapolateLeft: 'clamp',
        extrapolateRight: 'clamp',
      });
    }
    return baseVolume;
  }, [frame, fadeInFrames, fadeOutStart, durationInFrames, baseVolume]);

  const src = audio.src.includes('/')
    ? staticFile(audio.src)
    : staticFile(`audio/${audio.src}`);

  return <Audio src={src} volume={volumeFunction()} />;
};
