export interface AudioState {
  leftChannel: Float32Array;
  rightChannel: Float32Array;
  params: any;
  isProcessed: boolean;
  waveformColor: string;
  engineIndex: number;
}

export class UndoManager {
  private undoStack: AudioState[] = [];
  private readonly maxHistorySize: number;

  constructor(maxHistorySize: number = 20) {
    this.maxHistorySize = maxHistorySize;
  }

  pushState(state: AudioState): void {
    this.undoStack.push({
      leftChannel: state.leftChannel.slice(),
      rightChannel: state.rightChannel.slice(),
      params: state.params,
      isProcessed: state.isProcessed,
      waveformColor: state.waveformColor,
      engineIndex: state.engineIndex,
    });

    if (this.undoStack.length > this.maxHistorySize) {
      this.undoStack.shift();
    }
  }

  undo(): AudioState | null {
    const previousState = this.undoStack.pop();
    return previousState || null;
  }

  canUndo(): boolean {
    return this.undoStack.length > 0;
  }

  clear(): void {
    this.undoStack = [];
  }

  static captureState(
    buffer: AudioBuffer | null,
    params: any,
    isProcessed: boolean,
    waveformColor: string,
    engineIndex: number
  ): AudioState | null {
    if (!buffer) return null;

    return {
      leftChannel: buffer.getChannelData(0).slice(),
      rightChannel: buffer.getChannelData(1).slice(),
      params,
      isProcessed,
      waveformColor,
      engineIndex,
    };
  }
}
