export class AudioSystem {
  constructor() {
    this.context = null;
    this.master = null;
    this.warningTimer = 0;
  }

  ensure() {
    if (this.context) {
      if (this.context.state === 'suspended') this.context.resume();
      return true;
    }
    const Context = window.AudioContext || window.webkitAudioContext;
    if (!Context) return false;
    this.context = new Context();
    this.master = this.context.createGain();
    this.master.gain.value = 0.18;
    this.master.connect(this.context.destination);
    return true;
  }

  tone({ frequency = 440, duration = .08, type = 'sine', gain = .45, endFrequency = null, delay = 0 }) {
    if (!this.ensure()) return;
    const now = this.context.currentTime + delay;
    const osc = this.context.createOscillator();
    const amp = this.context.createGain();
    osc.type = type;
    osc.frequency.setValueAtTime(frequency, now);
    if (endFrequency) osc.frequency.exponentialRampToValueAtTime(Math.max(20, endFrequency), now + duration);
    amp.gain.setValueAtTime(.0001, now);
    amp.gain.exponentialRampToValueAtTime(Math.max(.001, gain), now + .008);
    amp.gain.exponentialRampToValueAtTime(.0001, now + duration);
    osc.connect(amp);
    amp.connect(this.master);
    osc.start(now);
    osc.stop(now + duration + .03);
  }

  click() {
    this.tone({ frequency: 520, endFrequency: 760, duration: .055, type: 'square', gain: .16 });
  }

  collect(type) {
    if (type === 'coolant') {
      this.tone({ frequency: 720, endFrequency: 1160, duration: .12, type: 'sine', gain: .3 });
    } else if (type === 'heat') {
      this.tone({ frequency: 360, endFrequency: 620, duration: .11, type: 'triangle', gain: .32 });
    } else {
      this.tone({ frequency: 170, endFrequency: 65, duration: .19, type: 'sawtooth', gain: .44 });
    }
  }

  warning() {
    this.tone({ frequency: 880, duration: .08, type: 'square', gain: .18 });
    this.tone({ frequency: 660, duration: .1, type: 'square', gain: .16, delay: .11 });
  }

  record() {
    const notes = [523.25, 659.25, 783.99, 1046.5];
    notes.forEach((frequency, index) => {
      this.tone({ frequency, duration: .22, type: 'triangle', gain: .34, delay: index * .11 });
    });
    this.tone({ frequency: 1318.5, duration: .5, type: 'sine', gain: .28, delay: .48 });
  }

  explosion() {
    this.tone({ frequency: 150, endFrequency: 32, duration: .65, type: 'sawtooth', gain: .72 });
    this.tone({ frequency: 72, endFrequency: 28, duration: .9, type: 'square', gain: .45, delay: .05 });
  }
}
