NoiseAnimation = {}
class('NoiseAnimation').extends(NobleSprite)

-- Global EW (РЕБ) state accessible by crosshair
NoiseAnimation.isJamming = false

function NoiseAnimation:init(x, y)
    NoiseAnimation.super.init(self, "assets/sprites/noise", true)
    self.animation:addState("run", 2, 11)
    self.animation:addState("idle", 1, 1)
    self.animation.run.frameDuration = 2.5
    self.animation:setState("idle")
    self:setZIndex(ZIndex.foreground)
    self:setSize(400, 240)
    self:add()
    self:moveTo(x, y)

    self.state = "idle"
    self.timer = 0

    -- РЕБ timing: long idle periods, short jam bursts
    self.minIdleDuration = 300
    self.maxIdleDuration = 600
    self.minJamDuration = 40
    self.maxJamDuration = 120

    self.nextSwitch = math.random(self.minIdleDuration, self.maxIdleDuration)
end

function NoiseAnimation:update()
    self.timer = self.timer + 1

    if self.timer >= self.nextSwitch then
        self.timer = 0
        if self.state == "idle" then
            self.state = "jamming"
            self.animation:setState("run")
            self.nextSwitch = math.random(self.minJamDuration, self.maxJamDuration)
            NoiseAnimation.isJamming = true
        else
            self.state = "idle"
            self.animation:setState("idle")
            self.nextSwitch = math.random(self.minIdleDuration, self.maxIdleDuration)
            NoiseAnimation.isJamming = false
            playdate.display.setOffset(0, 0)
        end
    end

    -- Micro screen shake during jamming
    if self.state == "jamming" then
        local sx = math.random(-1, 1)
        local sy = math.random(-1, 1)
        playdate.display.setOffset(sx, sy)
    end
end
