local isMusicPlaying = false
local musicOwner = nil
local currentVehicle = nil
local musicStates = {}

lib.registerContext({
    id = 'car_music_menu',
    title = 'Car Music Menu',
    options = {
        {
            title = 'Play Music',
            icon = 'play',
            onSelect = function()
                OpenMusicInput()
            end
        },
        {
            title = 'Stop Music',
            icon = 'stop',
            onSelect = function()
                StopMusic()
            end,
        }
    }
})

RegisterCommand(Config.CommandName, function()
    if IsPedInAnyVehicle(PlayerPedId(), false) then
        lib.showContext('car_music_menu')
    else
        lib.notify({ type = 'error', description = 'You must be in a vehicle to use this command.' })
    end
end, false)

function OpenMusicInput()
    local vehicle = GetVehiclePedIsIn(PlayerPedId(), false)
    local vehicleNetId = NetworkGetNetworkIdFromEntity(vehicle)
    local musicState = musicStates[vehicleNetId]

    if musicState and musicState.isPlaying and musicState.owner ~= GetPlayerServerId(PlayerId()) then
        lib.notify({ type = 'error', description = 'Music is already playing. Only the owner can change it.' })
        return
    end

    local input = lib.inputDialog('Play Music', {
        {type = 'input', label = 'Song (YouTube Link)', required = true},
        {type = 'number', label = 'Volume (0-100)', default = 50, min = 0, max = 100},
        {type = 'number', label = 'Radius (Max 35)', default = 10, min = 1, max = 35}
    })

    if input then
        PlayMusic(input[1], input[2], input[3])
    end
end

function PlayMusic(url, volume, radius)
    local vehicle = GetVehiclePedIsIn(PlayerPedId(), false)
    local vehicleNetId = NetworkGetNetworkIdFromEntity(vehicle)

    musicStates[vehicleNetId] = {
        isPlaying = true,
        owner = GetPlayerServerId(PlayerId()),
        vehicle = vehicle
    }

    currentVehicle = vehicle
    TriggerServerEvent('tropic-carplay:playMusic', vehicleNetId, url, volume, radius)
end

function StopMusic()
    local vehicle = GetVehiclePedIsIn(PlayerPedId(), false)
    if vehicle == 0 then return end

    local vehicleNetId = NetworkGetNetworkIdFromEntity(vehicle)
    if not vehicleNetId then return end

    if musicStates[vehicleNetId] and musicStates[vehicleNetId].isPlaying then
        TriggerServerEvent('tropic-carplay:stopMusic', vehicleNetId)
    end
end

RegisterNetEvent('tropic-carplay:startMusic', function(vehicleNetId, url, volume, radius, owner)
    local vehicle = NetToVeh(vehicleNetId)
    if DoesEntityExist(vehicle) then
        local tag = 'car_music_' .. vehicleNetId

        local coords = GetEntityCoords(vehicle)
        exports.xsound:PlayUrlPos(tag, url, volume / 100, coords)
        exports.xsound:Distance(tag, radius)

        musicStates[vehicleNetId] = {
            isPlaying = true,
            owner = owner,
            vehicle = vehicle
        }

        CreateThread(function()
            while musicStates[vehicleNetId] and musicStates[vehicleNetId].isPlaying do
                if DoesEntityExist(vehicle) then
                    local coords = GetEntityCoords(vehicle)
                    exports.xsound:setVolume(tag, volume / 100)
                    exports.xsound:Position(tag, coords)
                end
                Wait(250)
            end
        end)

        lib.notify({ type = 'inform', description = 'Music started.' })
    end
end)

RegisterNetEvent('tropic-carplay:stopMusic', function(vehicleNetId)
    local tag = 'car_music_' .. vehicleNetId
    exports.xsound:Destroy(tag)
    musicStates[vehicleNetId] = nil
    lib.notify({ type = 'inform', description = 'Music stopped.' })
end)
