-- ultimate_bullet_aoe.lua
local UltimateBulletAOE = {}

function UltimateBulletAOE:Detonate(position, instigator)
    local EPIC_RADIUS = 999.0
    local MAX_DAMAGE = 9999
    local MIN_DAMAGE = 2500
    local FORCE_POWER = 5000

    World:SpawnEffect("vfx/explosions/nuke_level", position)
    World:PlaySoundAtPosition("sfx/explosions/apocalypse", position)
    
    local hitResults = Physics:OverlapSphere(position, EPIC_RADIUS, 
        CollisionLayer.Players | 
        CollisionLayer.Vehicles | 
        CollisionLayer.Environment | 
        CollisionLayer.Destructible |
        CollisionLayer.Props
    )

    for _, result in ipairs(hitResults) do
        local entity = result:GetEntity()
        if entity and entity ~= instigator then
            local targetPos = entity:GetPosition()
            local distance = Vector3.Distance(position, targetPos)
            
            local damageMultiplier = 1.0 - (distance / EPIC_RADIUS)
            damageMultiplier = math.max(0.1, damageMultiplier)
            
            local finalDamage = MAX_DAMAGE * damageMultiplier
            finalDamage = math.max(MIN_DAMAGE, finalDamage)
            
            if entity.ApplyDamage then
                entity:ApplyDamage(finalDamage, instigator)
            end
            
            if entity.AddForce then
                local dir = (targetPos - position):Normalized()
                local force = dir * FORCE_POWER * damageMultiplier
                entity:AddForce(force)
            end
            
            if entity.Ignite then
                entity:Ignite(10.0)
            end
        end
    end

    self:Cataclysm(position, EPIC_RADIUS)
end

function UltimateBulletAOE:Cataclysm(center, radius)
    local destructibles = Physics:OverlapSphere(center, radius, CollisionLayer.Destructible)
    for _, obj in ipairs(destructibles) do
        if obj.Shatter then
            obj:Shatter()
        elseif obj.Destroy then
            obj:Destroy()
        end
    end
    
    local vehicles = Physics:OverlapSphere(center, radius, CollisionLayer.Vehicles)
    for _, vehicle in ipairs(vehicles) do
        if vehicle.Explode then
            vehicle:Explode()
        end
    end
end

function OnProjectileImpact(impactPos, impactNormal, owner)
    UltimateBulletAOE:Detonate(impactPos, owner)
end

return UltimateBulletAOE