<template>
  <div class="p-4">
    <h1 class="text-xl font-bold mb-4">Audio Fade-In Beispiel</h1>
    <audio
      ref="audioEl"
      :src="source"
      crossorigin="anonymous"
    />
    <button
      class="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition"
      @click="playWithFadeIn"
    >
      Abspielen mit Fade-In
    </button>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import tracksConfig from '~/tracks.config'

const audioEl = ref(null)
const source = ref(tracksConfig.lagoon_48_mp3_src)

const playWithFadeIn = async () => {
  const audio = audioEl.value
  const sink = useUserStore().audioOutputDevice
  audio.value?.setSinkId(sink.deviceId)

  if (!audio) { return }

  const audioContext = new (window.AudioContext || window.webkitAudioContext)()
  const sourceNode = audioContext.createMediaElementSource(audio)
  const gainNode = audioContext.createGain()

  // Anfangslautstärke auf 0 setzen
  gainNode.gain.setValueAtTime(0, audioContext.currentTime)

  // Ziel-Lautstärke in 3 Sekunden erreichen
  gainNode.gain.linearRampToValueAtTime(1.0, audioContext.currentTime + 3)

  // Verkabeln
  sourceNode.connect(gainNode)
  gainNode.connect(audioContext.destination)

  // Abspielen
  await audio.play()
}
</script>
