import type { AudioProcessor, ProcessorCategory } from './AudioProcessor';

export class TapeWobble implements AudioProcessor {
	getName(): string {
		return 'Tape Wobble';
	}

	getDescription(): string {
		return 'Simulates tape machine speed instability with pitch variations';
	}

	getCategory(): ProcessorCategory {
		return 'Time';
	}

	process(leftIn: Float32Array, rightIn: Float32Array): [Float32Array, Float32Array] {
		const length = leftIn.length;
		const leftOut = new Float32Array(length);
		const rightOut = new Float32Array(length);

		const sampleRate = 44100;
		const wobbleFreq = 2.0 + Math.random() * 2.0;
		const wobbleDepth = 0.015;

		let readPos = 0;

		for (let i = 0; i < length; i++) {
			const t = i / sampleRate;
			const wobble = Math.sin(2.0 * Math.PI * wobbleFreq * t) * wobbleDepth;
			const speed = 1.0 + wobble;

			readPos += speed;

			const idx = Math.floor(readPos);
			const frac = readPos - idx;

			if (idx < length - 1) {
				leftOut[i] = leftIn[idx] * (1.0 - frac) + leftIn[idx + 1] * frac;
				rightOut[i] = rightIn[idx] * (1.0 - frac) + rightIn[idx + 1] * frac;
			} else if (idx < length) {
				leftOut[i] = leftIn[idx];
				rightOut[i] = rightIn[idx];
			}
		}

		return [leftOut, rightOut];
	}
}
