local ScoreFont <const> = playdate.graphics.font.new("fonts/font-full-circle.pft")
local OutBubbleRadius <const> = 5
local ScoreboardMarginX <const> = 6
local ScoreboardMarginRight <const> = 4
local ScoreboardHeight <const> = 55
local Indicator = "> "
local IndicatorWidth <const> = ScoreFont:getTextWidth(Indicator)

local BallStrikeWidth <const> = 60
local BallStrikeHeight <const> = 20

---@param teams any
---@param battingTeam any
---@return string, number, string, number
function getIndicators(teams, battingTeam)
    if teams.home == battingTeam then
        return Indicator, 0, "", IndicatorWidth
    end
    return "", IndicatorWidth, Indicator, 0
end

function drawBallsAndStrikes(x, y, balls, strikes)
    if balls == 0 and strikes == 0 then
        return
    end

    local gfx = playdate.graphics
    gfx.setColor(gfx.kColorBlack)
    gfx.fillRect(x, y, BallStrikeWidth, BallStrikeHeight)
    local originalDrawMode = gfx.getImageDrawMode()
    gfx.setImageDrawMode(gfx.kDrawModeInverted)

    local text = tostring(balls) .. " - " .. tostring(strikes)
    local textWidth = ScoreFont:getTextWidth(text)
    local widthDiff = BallStrikeWidth - textWidth
    ScoreFont:drawText(text, x + (widthDiff / 2), y + 4)
    gfx.setImageDrawMode(originalDrawMode)
end

function drawScoreboard(x, y, teams, outs, battingTeam, inning)
    local gfx = playdate.graphics
    local homeScore = teams.home.score
    local awayScore = teams.away.score

    local homeIndicator, homeOffset, awayIndicator, awayOffset = getIndicators(teams, battingTeam)

    local homeScoreText = homeIndicator .. "HOME " .. (homeScore > 9 and homeScore or "  " .. homeScore)
    local awayScoreText = awayIndicator .. "AWAY " .. (awayScore > 9 and awayScore or "  " .. awayScore)

    local rectWidth = (ScoreboardMarginX * 2)
        + ScoreboardMarginRight
        + ScoreFont:getTextWidth(homeScoreText)
        + homeOffset

    gfx.setLineWidth(1)
    gfx.setColor(gfx.kColorBlack)
    gfx.fillRect(x, y, rectWidth, ScoreboardHeight)

    local originalDrawMode = gfx.getImageDrawMode()
    gfx.setImageDrawMode(gfx.kDrawModeInverted)

    ScoreFont:drawText(homeScoreText, x + ScoreboardMarginX + homeOffset, y + 6)
    ScoreFont:drawText(awayScoreText, x + ScoreboardMarginX + awayOffset, y + 22)
    local inningOffsetX = (x + ScoreboardMarginX + IndicatorWidth) + (4 * 2.5 * OutBubbleRadius)
    ScoreFont:drawText(inning, inningOffsetX, y + 39)

    gfx.setImageDrawMode(originalDrawMode)

    gfx.setColor(gfx.kColorWhite)

    function circleParams(i)
        local circleOffset = i * 2.5 * OutBubbleRadius
        return (x + ScoreboardMarginX + OutBubbleRadius + IndicatorWidth) + circleOffset, y + 46, OutBubbleRadius
    end

    for i = outs, 2 do
        gfx.drawCircleAtPoint(circleParams(i))
    end
    for i = 0, (outs - 1) do
        gfx.fillCircleAtPoint(circleParams(i))
    end
end
