import { getLS, setLS, KEYS } from './storage'

class SFX {
  constructor(){
    this.ctx = null
    this.muted = getLS(KEYS.mute, false)
  }
  ensure(){ if(!this.ctx){ this.ctx = new (window.AudioContext||window.webkitAudioContext)() } }
  setMuted(m){ this.muted = m; setLS(KEYS.mute, m) }
  play(type){ if(this.muted) return; this.ensure(); const t = this.ctx.currentTime
    const o = this.ctx.createOscillator(); const g = this.ctx.createGain();
    o.connect(g); g.connect(this.ctx.destination)
    g.gain.setValueAtTime(0.06, t)
    const env = (d)=>{ g.gain.exponentialRampToValueAtTime(0.0001, t+d) }
    switch(type){
      case 'click': o.type='triangle'; o.frequency.setValueAtTime(640,t); env(0.06); o.start(t); o.stop(t+0.06); break;
      case 'success': o.type='sine'; o.frequency.setValueAtTime(660,t); o.frequency.linearRampToValueAtTime(990,t+0.3); env(0.3); o.start(t); o.stop(t+0.32); break;
      case 'error': o.type='sawtooth'; o.frequency.setValueAtTime(180,t); env(0.2); o.start(t); o.stop(t+0.22); break;
      case 'notify': o.type='square'; o.frequency.setValueAtTime(880,t); env(0.15); o.start(t); o.stop(t+0.16); break;
      case 'reward': o.type='sine'; o.frequency.setValueAtTime(740,t); o.frequency.linearRampToValueAtTime(1200,t+0.35); env(0.35); o.start(t); o.stop(t+0.37); break;
      default: return
    }
  }
}

export const sfx = new SFX()
