DroneCardSelector = {}
class("DroneCardSelector").extends(BaseScene)
local scene = DroneCardSelector
local fontMed = Graphics.font.new('assets/fonts/onyx_9')
local elapsedTime = 0

scene.inputHandler = {
    AButtonDown = function()
        local drone = Drones[scene.menuIndex]
        -- If locked, try to buy
        if drone.locked == true then
            if drone.price <= 0 then return end
            local money = Noble.GameData.get("money")
            if money >= drone.price then
                Noble.GameData.set("money", money - drone.price)
                Noble.GameData.set("drone" .. drone.id, 1)
                drone.locked = false
                scene.menuConfirmSound:play(1)
                scene.purchaseText = "-$" .. drone.price
                scene.purchaseTimer = playdate.timer.new(1200, 0, 40, playdate.easingFunctions.outCubic)
                screenShake(200, 3)
            else
                screenShake(300, 5)
                scene.noMoneyTimer = playdate.timer.new(800, 0, 800, playdate.easingFunctions.linear)
            end
            return
        end
        CurrentMission.droneId = drone.id
        scene.menuConfirmSound:play(1)
        local mode = drone.mode
        local soundTable = playdate.sound.playingSources()
        for i=1, #soundTable do
            soundTable[i]:stop()
        end
        if mode == Modes.bomber then
            local stock = Noble.GameData.get("bomberStock")
            if stock <= 0 then
                return
            end
            Noble.GameData.set("bomberStock", stock - 1)
            Noble.transition(BomberScene)
        else
            Noble.transition(Assemble)
        end
    end,
    BButtonDown = function()
        -- B on bomber drone: buy stock
        local drone = Drones[scene.menuIndex]
        if not drone.locked and drone.mode == Modes.bomber then
            local money = Noble.GameData.get("money")
            local stockPrice = drone.stockPrice or 50
            if money >= stockPrice then
                Noble.GameData.set("money", money - stockPrice)
                Noble.GameData.set("bomberStock", Noble.GameData.get("bomberStock") + 1)
                scene.menuConfirmSound:play(1)
                scene.purchaseText = "-$" .. stockPrice
                scene.purchaseY = 0
                scene.purchaseTimer = playdate.timer.new(1200, 0, 40, playdate.easingFunctions.outCubic)
                return
            end
        end
        scene.menuBackSound:play(1)
        Noble.transition(MapSelector)
    end,
    downButtonDown = function()
    end,
    leftButtonDown = function()
        if scene.menuIndex <= 1 then
            return
        end
        scene.menuSelSound:play(1)
        scene.targetX = scene.targetX + 355
        scene.menuIndex = scene.menuIndex - 1
        scene.paginator:set(scene.menuIndex)
    end,
    rightButtonDown = function()
        if scene.menuIndex >= 4 then
            return
        end
        scene.menuSelSound:play(1)
        scene.targetX = scene.targetX - 355
        scene.menuIndex = scene.menuIndex + 1
        scene.paginator:set(scene.menuIndex)
    end,
    upButtonDown = function()
    end,
}

function scene:setValues()
    self.menuIndex = 1

    self.aKey = Graphics.image.new("assets/sprites/buttons/A")
    self.bKey = Graphics.image.new("assets/sprites/buttons/B")
    scene.menuConfirmSound = playdate.sound.fileplayer.new("assets/audio/confirm")
    scene.menuBackSound = playdate.sound.fileplayer.new("assets/audio/back")

    scene.menuSelSound = playdate.sound.fileplayer.new("assets/audio/menu_select")
    scene.menuSelSound:setVolume(0.5)

    scene.currentX = 0
    scene.targetX = 0

    scene.purchaseText = nil
    scene.purchaseTimer = nil
    scene.noMoneyTimer = nil
end

function scene:init()
    scene.super.init(self)
    scene:setValues()
end

function scene:start()
    scene.super.start(self)

    self.optionsMenu:addMenuItem("Main Menu", function() Noble.transition(Menu) end)
    Noble.showFPS = false
end

function scene:enter()
    scene.super.enter(self)

    -- Update locked state from GameData
    for i = 1, #Drones do
        Drones[i].locked = (Noble.GameData.get("drone" .. i) == 0)
    end

    scene.menuIndex = 1
    scene.currentX = 0
    scene.targetX = 0

    scene.cards = {}
    for i = 1, #Drones do
        scene.cards[i] = DroneCard(0, 0, Drones[i])
    end
    scene.paginator = PageSprite(200, 207)
end

function scene:update()
    scene.super.update(self)
    if scene.cards == nil then
        print("scene.cards is nil")
        return
    end
    elapsedTime = elapsedTime + 1 / playdate.display.getRefreshRate()

    local dy = 2 * math.sin(20 * elapsedTime)

    local speed = 40
    if math.abs(scene.targetX - scene.currentX) < speed then
        scene.currentX = scene.targetX
    else
        scene.currentX = scene.currentX + speed * ((scene.targetX > scene.currentX) and 1 or -1)
    end

    local x = 0
    for i = 1, #scene.cards do
        x = 29 + (339 + 16) * (i - 1)
        scene.cards[i]:moveTo(x + scene.currentX, 25)
    end

    local drone = Drones[scene.menuIndex]

    -- Money display
    Noble.Text.draw("$" .. Noble.GameData.get("money"), 200, 5, Noble.Text.ALIGN_CENTER, false, fontMed)

    if drone.locked and drone.price > 0 then
        self.aKey:draw(315, 207 + dy)
        Noble.Text.draw("Buy $" .. drone.price, 333, 210, Noble.Text.ALIGN_LEFT, false, fontMed)
    elseif drone.locked then
        Noble.Text.draw("Coming soon", 340, 210, Noble.Text.ALIGN_CENTER, false, fontMed)
    elseif drone.mode == Modes.bomber then
        local stock = Noble.GameData.get("bomberStock")
        self.aKey:draw(315, 207 + dy)
        Noble.Text.draw("Go (" .. stock .. "x)", 333, 210, Noble.Text.ALIGN_LEFT, false, fontMed)
    else
        self.aKey:draw(315, 207 + dy)
        Noble.Text.draw("Assemble", 333, 210, Noble.Text.ALIGN_LEFT, false, fontMed)
    end

    -- B button: back or buy stock
    if not drone.locked and drone.mode == Modes.bomber then
        self.bKey:draw(15, 207 + dy)
        Noble.Text.draw("Buy +1: $" .. (drone.stockPrice or 50), 33, 210, Noble.Text.ALIGN_LEFT, false, fontMed)
    else
        self.bKey:draw(15, 207 + dy)
        Noble.Text.draw("Back", 33, 210, Noble.Text.ALIGN_LEFT, false, fontMed)
    end

    -- Not enough money warning
    if scene.noMoneyTimer then
        if scene.noMoneyTimer.value < 800 then
            Noble.Text.draw("Not enough $!", 200, 190, Noble.Text.ALIGN_CENTER, false, fontMed)
        else
            scene.noMoneyTimer = nil
        end
    end

    -- Purchase animation
    if scene.purchaseText and scene.purchaseTimer then
        local offset = scene.purchaseTimer.value
        local alpha = 1.0 - (offset / 40)
        if alpha > 0 then
            Noble.Text.draw(scene.purchaseText, 200, 20 - offset, Noble.Text.ALIGN_CENTER, false, fontMed)
        else
            scene.purchaseText = nil
            scene.purchaseTimer = nil
        end
    end

    scene.paginator:moveTo(200, 207)
end

function scene:exit()
    scene.super.exit(self)
    for i = 1, #scene.cards do
        scene.cards[i]:remove()
    end
    Noble.showFPS = false
end

function scene:finish()
    scene.super.finish(self)
    playdate.display.setScale(1)
end
