local nitroReplay = ac.ReplayStream({
  ac.StructItem.key('btm_nitro_replay_v1'),
  nitroActive   = ac.StructItem.int32(),
  nitroTimeLeft = ac.StructItem.double(),
  nitroDuration = ac.StructItem.double(),
  nitroUsesLeft = ac.StructItem.int32(),
}, function() end)

local sharedNitro = ac.connect({
  ac.StructItem.key('btm_nitro_audio_v1'),
  nitroPressCounter = ac.StructItem.int32(),
  nitroActive       = ac.StructItem.int32(),
  nitroTimeLeft     = ac.StructItem.double(),
  nitroDuration     = ac.StructItem.double(),
  nitroUsesLeft     = ac.StructItem.int32(),
}, true, ac.SharedNamespace.CarScript)

ac.loadSoundbank('./sfx/btm_hellkitten.bank', 'Sound/GUIDs.txt')

local sound = ac.AudioEvent('event:/cars/btm_hellkitten/door', true, true)
sound:setPosition(vec3(0, 0.68526, 1.8315))
sound:setVolumeChannel(ac.AudioChannel.CarComponents)
sound.volume = 12.0

local lastActive = 0
local playLeft = 0.0

local function startAudio(duration)
  if not sound then return end
  if sound:isPlaying() then sound:stop() end
  sound:start()
  playLeft = duration or 0.0
end

local function stopAudio()
  if not sound then return end
  if sound:isPlaying() then sound:stop() end
  playLeft = 0.0
end

function script.update(dt)
  local active = (nitroReplay.nitroActive or 0)
  local timeLeft = nitroReplay.nitroTimeLeft or 0.0
  local duration = nitroReplay.nitroDuration or 0.0

  if active ~= lastActive then
    lastActive = active

    if active == 1 and timeLeft > 0.0 then
      startAudio(duration)
    else
      stopAudio()
    end
  end

  if active == 0 then
    if playLeft > 0.0 then stopAudio() end
    return
  end

  if playLeft > 0.0 then
    playLeft = playLeft - dt
    if playLeft <= 0.0 then
      stopAudio()
    end
  end
end
