-- Flashcard Types
local FLASHCARD_TYPES = {
    HIDDEN = "hidden",
    MULTI = "multi",
}

local fontPath = "Interface/AddOns/WoWStudy/Fonts/NotoSansCJK-Medium.ttc"

local currentCard = nil
local flashcardDisplayed = false

-----------------------------------
-- Flashcard Frame
-----------------------------------
local frame = CreateFrame("Frame", "WSFlashcardFrame", UIParent, "BackdropTemplate")
frame:SetSize(500, 400)
frame:SetPoint("CENTER")
frame:EnableMouse(true)
frame:SetMovable(true)
frame:SetClampedToScreen(true)
frame:RegisterForDrag("LeftButton")
frame:SetScript("OnDragStart", frame.StartMoving)
frame:SetScript("OnDragStop", frame.StopMovingOrSizing)
--frame:SetResizable(true)
frame:Hide()

-- Add a background texture
local background = frame:CreateTexture(nil, "BACKGROUND")
background:SetAllPoints(frame)
background:SetTexture("Interface\\DialogFrame\\UI-DialogBox-Background")
background:SetVertexColor(0.1, 0.1, 0.1, 0.8) -- Dark with 80% opacity

-- Add a border to mimic classic frames
local border = CreateFrame("Frame", nil, frame, "BackdropTemplate")
border:SetAllPoints(frame)
border:SetBackdrop({
    edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border", -- Classic tooltip border
    edgeSize = 16,
})
border:SetBackdropBorderColor(1, 0.84, 0, 1) -- Gold border

-- Header Section (Correct Count and Total Answered)
local header = CreateFrame("Frame", nil, frame, "BackdropTemplate")
header:SetPoint("TOP", frame, "TOP", 0, -5)
header:SetBackdrop({
    bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background",
    edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
    edgeSize = 12,
})
header:SetBackdropBorderColor(0.8, 0.8, 0.8, 1)

-- Initialize header width
local initialBorderSize = 4
local initialAdjustedWidth = frame:GetWidth() - initialBorderSize
header:SetSize(initialAdjustedWidth, 40)

local correctCountText = header:CreateFontString(nil, "OVERLAY", "GameFontNormal")
correctCountText:SetPoint("LEFT", header, "LEFT", 10, 0)
correctCountText:SetText("Correct: 0")

local totalCountText = header:CreateFontString(nil, "OVERLAY", "GameFontNormal")
totalCountText:SetPoint("RIGHT", header, "RIGHT", -10, 0)
totalCountText:SetText("Total: 0")

local timerBar = CreateFrame("StatusBar", nil, frame)
timerBar:SetSize(480, 20)
timerBar:SetPoint("TOP", frame, "TOP", 0, 20)
timerBar:SetStatusBarTexture("Interface\\RaidFrame\\Raid-Bar-Hp-Fill")

timerBar:SetStatusBarColor(1, 0, 0, 1) -- Red color

-- Set the draw layer to ensure it appears above other elements
timerBar:SetFrameStrata("HIGH")
timerBar:SetFrameLevel(10)

local timerBarBackground = timerBar:CreateTexture(nil, "BACKGROUND")
timerBarBackground:SetAllPoints(timerBar)
timerBarBackground:SetColorTexture(0, 0, 0, 0.5) -- Semi-transparent dark background

local timerBarBorder = CreateFrame("Frame", nil, timerBar, "BackdropTemplate")
timerBarBorder:SetAllPoints(timerBar)
timerBarBorder:SetBackdrop({
    edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
    edgeSize = 12,
})
timerBarBorder:SetBackdropBorderColor(0.8, 0.8, 0.8, 1) -- Light grey border

--------------------------------------------
-- Question / Answer button frames/display
--------------------------------------------
local selector = CreateFrame("Frame", nil, frame, "BackdropTemplate")
selector:SetPoint("TOP", header, "BOTTOM", 0, -5)
selector:SetSize(frame:GetWidth() - 10, 25)

local questionButton = CreateFrame("Button", nil, frame)
local answerButton = CreateFrame("Button", nil, frame)

local questionButtonClickFunc = nil
local answerButtonClickFunc = nil

-- Variable to track the currently selected button
local selectedButton = nil

-- Add a light blue glow to the mouseover option
local function OnEnter(self)
    if self ~= selectedButton then
        -- light yellow glow
        self.bg:SetColorTexture(1, 1, 0, 0.3)

        -- Set the text color to default
        self.title:SetTextColor(1, 1, 1)
    end
end

local function OnLeave(self)
    if self ~= selectedButton then
        self.bg:SetColorTexture(0, 0, 0, 0) -- Transparent

        -- Set the text color to default
        self.title:SetTextColor(1, 1, 1)
    end
end

-- Function to handle button clicks
local function OnClick(self, optionFunc)
    if selectedButton then
        selectedButton.bg:SetColorTexture(0, 0, 0, 0) -- Reset to transparent
    end

    selectedButton = self

    self.bg:SetColorTexture(1, 1, 0, 0.6) -- Brighter yellow to indicate selection
    self.title:SetTextColor(1, 1, 1) -- Set the text color to default

    optionFunc()
end

-- Create buttons for question/answer selector
local function createSelectorButton(name, parent, point, x, func)
    local button = CreateFrame("Button", nil, parent)
    button:SetSize(selector:GetWidth() / 2 - 5, 50)
    button:SetPoint(point, parent, point, x, 0)

    local bg = button:CreateTexture(nil, "BACKGROUND")
    bg:SetAllPoints(button)
    bg:SetColorTexture(0, 0, 0, 0)
    button.bg = bg

    local title = button:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    title:SetPoint("CENTER")
    title:SetText(name)
    title:SetFont(fontPath, 12)
    button.title = title

    button:SetScript("OnEnter", OnEnter)
    button:SetScript("OnLeave", OnLeave)
    button:SetScript("OnClick", function() OnClick(button, func) end)

    return button
end

---------------------------------------
-- Question Frame
---------------------------------------

-- Below the selector, create a frame to display the question or answer
local questionFrame = CreateFrame("Frame", nil, frame, "BackdropTemplate")
questionFrame:SetPoint("TOP", selector, "BOTTOM", 0, -10)
questionFrame:SetSize(frame:GetWidth(), frame:GetHeight())
questionFrame:SetClipsChildren(true)

-- Display the Question Frame in the content frame
local questionText = questionFrame:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
questionText:SetPoint("TOPLEFT", questionFrame, "TOPLEFT", 10, -5)
questionText:SetWidth(questionFrame:GetWidth())
questionText:SetJustifyH("LEFT")
questionText:SetJustifyV("TOP")
questionText:SetWordWrap(true)
questionText:SetFont(fontPath, 12)
questionText:SetSpacing(4)
questionText:SetText("placeholder")

---------------------------------------
-- Adjust the frame size based on text
---------------------------------------
local function resizeFrameForMultiAnswer(multiAnswerFrame, buttons, maxWidth, maxHeight)
    local gridPadding = 10
    local totalColumns = 2
    local totalRows = 2
    local minButtonWidth = 50 -- Starting minimum width
    local minButtonHeight = 35 -- Starting minimum height (50 * 7/10 for aspect ratio)

    -- Calculate maximum button dimensions based on grid constraints
    local maxButtonWidth = (maxWidth - gridPadding * (totalColumns + 1)) / totalColumns
    local maxButtonHeight = (maxHeight - gridPadding * (totalRows + 1)) / totalRows

    -- Initialize button dimensions to minimum size
    local buttonWidth = minButtonWidth
    local buttonHeight = minButtonHeight

    -- Determine the required size by checking the longest text
    for _, button in ipairs(buttons) do
        local title = button.title
        local currentWidth = minButtonWidth

        while true do
            -- Set the text width to the current button width minus padding
            title:SetWidth(currentWidth - 20)
            title:SetWordWrap(true)

            -- Get the dimensions of the text
            local textWidth = title:GetStringWidth()
            local textHeight = title:GetStringHeight()

            -- Calculate the height of the button based on the aspect ratio
            local currentHeight = currentWidth * 7 / 10
            local paddedTextHeight = textHeight + 10

            -- Check if the text fits within the button
            if paddedTextHeight <= currentHeight then
                -- Update button size if this width works
                buttonWidth = math.max(buttonWidth, max(100, currentWidth))
                buttonHeight = math.max(buttonHeight, paddedTextHeight)
                break
            end

            -- Increase width and height while maintaining the aspect ratio
            currentWidth = currentWidth + 20
            currentHeight = currentWidth * 7 / 10

            -- Stop if dimensions exceed the maximum allowed size
            if currentWidth > maxButtonWidth or currentHeight > maxButtonHeight then
                buttonWidth = maxButtonWidth
                buttonHeight = maxButtonHeight
                break
            end
        end
    end

    -- Resize and position buttons uniformly
    for i, button in ipairs(buttons) do
        button:SetSize(buttonWidth, buttonHeight)

        local title = button.title
        title:SetWidth(buttonWidth - 20)
        title:SetWordWrap(true)

        -- Position buttons in a grid
        local col = (i - 1) % totalColumns
        local row = math.floor((i - 1) / totalColumns)
        button:ClearAllPoints()
        button:SetPoint(
            "TOPLEFT",
            multiAnswerFrame,
            "TOPLEFT",
            gridPadding + col * (buttonWidth + gridPadding),
            -(gridPadding + row * (buttonHeight + gridPadding))
        )
    end

    -- Calculate the frame size based on the grid
    local gridWidth = totalColumns * (buttonWidth + gridPadding) + gridPadding
    local gridHeight = totalRows * (buttonHeight + gridPadding) + gridPadding

    multiAnswerFrame:SetSize(gridWidth, gridHeight)

    -- Adjust the parent frame size
    local headerHeight = header:GetHeight() + 10
    local selectorHeight = selector:GetHeight() + 5
    local parentVerticalPadding = 25
    frame:SetSize(multiAnswerFrame:GetWidth() + 5, multiAnswerFrame:GetHeight() + 5 + headerHeight + selectorHeight + parentVerticalPadding)

    -- Resize header and selector
    header:SetWidth(multiAnswerFrame:GetWidth() - 5)
    selector:SetWidth(multiAnswerFrame:GetWidth() - 20)
    questionButton:SetWidth(selector:GetWidth() / 2 - 2)
    questionButton:SetHeight(30)
    answerButton:SetWidth(selector:GetWidth() / 2 - 2)
    answerButton:SetHeight(30)
    timerBar:SetWidth(multiAnswerFrame:GetWidth())
end

local function resizeFrameForHiddenAnswer(answerText, answerFrame, correctButton, wrongButton)
    -- Make sure the text and answer frame are shown so measurements are accurate
    answerFrame:Show()
    answerText:Show()

    local horizontalPadding = 15
    local verticalPadding = 32
    local maxWidth = 800
    local maxHeight = 800
    local minWidth = 200
    local minHeight = 100
    local maxTextWidth = maxWidth - horizontalPadding
    local maxTextHeight = maxHeight - verticalPadding

    local frameWidth = minWidth
    local frameHeight = minHeight
    local currentWidth = minWidth

    while true do
        answerText:SetJustifyH("LEFT")
        answerText:SetWidth(currentWidth - horizontalPadding)
        answerText:SetWordWrap(true)

        local textWidth = answerText:GetStringWidth()
        local textHeight = answerText:GetStringHeight()

        local aspectRatioHeight = currentWidth * 7 / 10
        local paddedTextHeight = textHeight + verticalPadding

        if paddedTextHeight <= aspectRatioHeight then
            frameWidth = math.max(frameWidth, currentWidth)
            frameHeight = paddedTextHeight
            break
        end

        currentWidth = currentWidth + 20
        aspectRatioHeight = currentWidth * 7 / 10

        -- Stop if dimensions exceed the maximum allowed size
        if currentWidth > maxTextWidth or aspectRatioHeight > maxTextHeight then
            frameWidth = maxTextWidth
            frameHeight = maxTextHeight
            break
        end
    end

    local bottomButtonHeight = math.max(correctButton:GetHeight(), wrongButton:GetHeight())
    local buttonMargin       = bottomButtonHeight

    -- Resize the frame and update child elements
    frame:SetSize(frameWidth, frameHeight + buttonMargin)

    -- Update the answerText width and ensure alignment
    answerText:SetWidth(frameWidth - horizontalPadding)
    answerText:SetWordWrap(true)

    local headerHeight   = header:GetHeight()   + 10
    local selectorHeight = selector:GetHeight() + 5

    frame:SetSize(
        frameWidth,
        frameHeight + headerHeight + selectorHeight + buttonMargin
    )

    timerBar:SetWidth(frameWidth)

    -- Update child elements
    header:SetWidth(frameWidth - 10)
    selector:SetWidth(frameWidth - horizontalPadding)
    answerFrame:SetWidth(frameWidth)
    answerFrame:SetHeight(frameHeight)
    questionButton:SetWidth(selector:GetWidth() / 2 - 2)
    answerButton:SetWidth(selector:GetWidth() / 2 - 2)
    questionButton:SetHeight(30)
    answerButton:SetHeight(30)
    answerText:SetWidth(frameWidth - horizontalPadding)

    correctButton:ClearAllPoints()
    correctButton:SetPoint("BOTTOMLEFT", frame, "BOTTOMLEFT", 10, 10)

    wrongButton:ClearAllPoints()
    wrongButton:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", -10, 10)

    correctButton:SetWidth(70)
    wrongButton:SetWidth(70)

    answerFrame:Show()
    correctButton:Show()
    wrongButton:Show()
end

local function resizeFrameToFitContent()
    local horizontalPadding = 15
    local verticalPadding = 32
    local maxWidth = 800
    local maxHeight = 800
    local minWidth = 200
    local minHeight = 100
    local maxTextWidth = maxWidth - horizontalPadding
    local maxTextHeight = maxHeight - verticalPadding

    local frameWidth = minWidth
    local frameHeight = minHeight
    local currentWidth = minWidth

    while true do
        questionText:SetJustifyH("LEFT")
        questionText:SetWidth(currentWidth - horizontalPadding)
        questionText:SetWordWrap(true)

        local textWidth = questionText:GetStringWidth()
        local textHeight = questionText:GetStringHeight()

        local aspectRatioHeight = currentWidth * 7 / 10
        local paddedTextHeight = textHeight + verticalPadding

        if paddedTextHeight <= aspectRatioHeight then
            frameWidth = math.max(frameWidth, currentWidth)
            frameHeight = paddedTextHeight
            break
        end

        currentWidth = currentWidth + 20
        aspectRatioHeight = currentWidth * 7 / 10

        -- Stop if dimensions exceed the maximum allowed size
        if currentWidth > maxTextWidth or aspectRatioHeight > maxTextHeight then
            frameWidth = maxTextWidth
            frameHeight = maxTextHeight
            break
        end
    end

    -- Resize the frame and update child elements
    frame:SetSize(frameWidth, frameHeight)

    -- Update the questionText width and ensure alignment
    questionText:SetWidth(frameWidth - horizontalPadding)
    questionText:SetWordWrap(true)

    local headerHeight   = header:GetHeight()   + 10
    local selectorHeight = selector:GetHeight() + 5

    frame:SetSize(
        frameWidth,
        frameHeight + headerHeight + selectorHeight
    )

    timerBar:SetWidth(frameWidth)

    -- Update child elements
    header:SetWidth(frameWidth - 10)
    selector:SetWidth(frameWidth - horizontalPadding)
    questionFrame:SetWidth(frameWidth)
    questionFrame:SetHeight(frameHeight)
    questionButton:SetWidth(selector:GetWidth() / 2 - 2)
    answerButton:SetWidth(selector:GetWidth() / 2 - 2)
    questionButton:SetHeight(30)
    answerButton:SetHeight(30)
    questionText:SetWidth(frameWidth - horizontalPadding)
end

-------------------------------------------------------
-- Answer Frame and logic
-------------------------------------------------------

-------------------
-- MULTI ANSWER
-------------------

local multiAnswerFrame
local multiAnswerButtons = {}

local function showMultiAnswer(choices)
    if not multiAnswerFrame then
        -- Create the multi-answer frame
        multiAnswerFrame = CreateFrame("Frame", nil, frame, "BackdropTemplate")
        multiAnswerFrame:SetPoint("TOP", selector, "BOTTOM", 0, -5)
        multiAnswerFrame:SetBackdrop({
            bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background",
        })
        -- multiAnswerFrame:SetBackdropBorderColor(0.8, 0.8, 0.8, 1)
        multiAnswerFrame:Hide()
    end

    -- Randomly shuffle the choices
    for i = #choices, 2, -1 do
        local j = math.random(i)
        choices[i], choices[j] = choices[j], choices[i]
    end


    -- Create or reuse buttons
    for i, choice in ipairs(choices) do
        local button = multiAnswerButtons[i]
        if not button then
            button = CreateFrame("Button", nil, multiAnswerFrame)
            button:SetSize(140, 30)
            button:SetClipsChildren(true)

            -- Add translucent background
            local bg = button:CreateTexture(nil, "BACKGROUND")
            bg:SetAllPoints(button)
            bg:SetColorTexture(0, 0, 0, 0.5) -- Semi-transparent black
            button.bg = bg

            -- Add text
            local title = button:CreateFontString(nil, "OVERLAY", "GameFontNormal")
            title:SetPoint("TOP", 0, -5)
            title:SetFont(fontPath, 12)
            title:SetJustifyH("LEFT")
            title:SetJustifyV("TOP")
            title:SetWordWrap(true)
            title:SetSpacing(4)

            button.title = title

            -- Mouseover effects
            button:SetScript("OnEnter", function()
                bg:SetColorTexture(1, 1, 0, 0.3) -- Highlight
            end)
            button:SetScript("OnLeave", function()
                bg:SetColorTexture(0, 0, 0, 0.5) -- Reset
            end)

            multiAnswerButtons[i] = button
        end

        button.title:SetText(choice)
        button:SetScript("OnClick", function()
            FlashcardSubmit(choice, frame)
        end)
        button:Show()
    end

    -- Hide unused buttons
    for i = #choices + 1, #multiAnswerButtons do
        multiAnswerButtons[i]:Hide()
    end

    -- Resize and arrange the buttons and grid
    resizeFrameForMultiAnswer(multiAnswerFrame, multiAnswerButtons, 800, 600) -- Adjust maxWidth and maxHeight as needed

    multiAnswerFrame:Show()
end

-------------------
-- HIDDEN ANSWER
-------------------
local answerFrame, answerText, correctButton, wrongButton

local function showHiddenAnswer(answer)
    if not answerFrame then

        -- Create the answer frame
        answerFrame = CreateFrame("Frame", nil, frame, "BackdropTemplate")
        answerFrame:SetPoint("TOP", selector, "BOTTOM", 0, -10)
        answerFrame:SetSize(frame:GetWidth(), frame:GetHeight())
        answerFrame:SetClipsChildren(true)
        answerFrame:Hide()

        -- Create the answer text
        answerText = answerFrame:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
        answerText:SetPoint("TOPLEFT", answerFrame, "TOPLEFT", 10, -5)
        answerText:SetWidth(answerFrame:GetWidth())
        answerText:SetJustifyH("LEFT")
        answerText:SetJustifyV("TOP")
        answerText:SetWordWrap(true)
        answerText:SetFont(fontPath, 12)
        answerText:SetSpacing(4)


        -- Create Correct Button
        correctButton = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
        correctButton:SetSize(140, 30)
        correctButton:SetPoint("BOTTOMLEFT", answerText, "BOTTOMLEFT", 20, 0)
        correctButton:SetText("Correct")
        correctButton:SetScript("OnClick", function()
            correctButton:Disable()
            wrongButton:Disable()
            FlashcardSubmit("Correct", frame)
        end)

        -- Create Wrong Button
        wrongButton = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
        wrongButton:SetSize(140, 30)
        wrongButton:SetPoint("BOTTOMRIGHT", answerText, "BOTTOMRIGHT", -20, 0)
        wrongButton:SetText("Wrong")
        wrongButton:SetScript("OnClick", function()
            wrongButton:Disable()
            correctButton:Disable()
            FlashcardSubmit("Wrong", frame)
        end)
    else
        correctButton:Enable()
        wrongButton:Enable()
    end

    answerText:SetText(answer)

    resizeFrameForHiddenAnswer(answerText, answerFrame, correctButton, wrongButton)
end

-- Function to display the question and resize the frame
local function showQuestion(text)
    -- Hide all answer components
    if answerFrame then
        answerFrame:Hide()
    end

    if multiAnswerFrame then
        multiAnswerFrame:Hide()
    end

    if correctButton then
        correctButton:Hide()
    end

    if wrongButton then
        wrongButton:Hide()
    end

    -- Display the question
    questionText:SetText(text)

    -- Unhinged way to fix this not rendering on first load properly
    questionText:GetWidth()
    questionText:GetStringHeight()
    questionText:GetHeight()
    questionText:GetText()
    
    resizeFrameToFitContent() -- Adjust the frame size based on the text
    questionFrame:Show()
   
end

-- Function to hide the question
local function showAnswer()
    questionFrame:Hide()
    if currentCard.type == FLASHCARD_TYPES.HIDDEN then
        showHiddenAnswer(currentCard.answer)
    elseif currentCard.type == FLASHCARD_TYPES.MULTI then
        showMultiAnswer(currentCard.choices)
    end
end
------------------------------------
-- Init buttons and onClick funtions
------------------------------------
questionButton = createSelectorButton("Question", selector, "LEFT", 0, function() showQuestion(currentCard.question) end)
answerButton = createSelectorButton("Answer", selector, "RIGHT", 0, function() showAnswer() end)

questionButtonClickFunc = questionButton:GetScript("OnClick")
answerButtonClickFunc = answerButton:GetScript("OnClick")

-- -----------------------------------------
-- --     Flashcard functionality         --
-- -----------------------------------------
local function StartTimer()
    -- Timer logic
    local MAX_TIME = WoWStudySaved.settings.timerValue or 60
    local timerDuration = MAX_TIME
    timerBar:SetMinMaxValues(0, MAX_TIME)
    timerBar:SetValue(MAX_TIME)

    timerBar:SetValue(MAX_TIME)
    if timer then
        timer:Cancel()
    end
    timer = C_Timer.NewTicker(1, function()
        timerDuration = timerDuration - 1
        timerBar:SetValue(timerDuration)
        if timerDuration <= 0 then
            timer:Cancel()
            FlashcardSubmit(nil, frame)
        end
    end)
end

function FlashcardSubmit(selectedAnswer, frame)
    if timer then
        timer:Cancel()
    end

    local greenGlow = {0, 1, 0, 0.8} -- Green
    local redGlow = {1, 0, 0, 0.8}   -- Red

    -- Handle multiple-choice flashcards
    if currentCard.type == "multi" and selectedAnswer then
        if selectedAnswer == currentCard.answer then
            WoWStudyFunction.RecordAnswer(currentCard.question, currentCard.deckName, "correct")
            WoWStudyFunction.PlayGlowAnimation(frame, greenGlow)

            for _, button in ipairs(multiAnswerButtons) do
                button:Disable()
            end
            C_Timer.After(1, function()
                frame:Hide() -- Hide the frame after 1 second
                for _, button in ipairs(multiAnswerButtons) do
                    button:Enable() -- Re-enable all buttons
                    button.bg:SetColorTexture(0, 0, 0, 0) -- Reset button color
                    button:Hide() -- Hide all buttons
                end
                flashcardDisplayed = false
            end)
        else
            -- Incorrect answer logic
            WoWStudyFunction.RecordAnswer(currentCard.question, currentCard.deckName, "wrong")
            for _, button in ipairs(multiAnswerButtons) do
                button:Disable() -- Disable all buttons
                if button.title:GetText() == currentCard.answer then
                    -- Highlight the correct answer in green
                    button.bg:SetColorTexture(unpack(greenGlow))
                elseif button.title:GetText() == selectedAnswer then
                    -- Highlight the selected incorrect answer in red
                    button.bg:SetColorTexture(unpack(redGlow))
                end
            end

            -- Show a close button to dismiss the frame
            local closeButton = CreateFrame("Button", nil, multiAnswerFrame, "UIPanelButtonTemplate")
            closeButton:SetSize(70, 15)
            closeButton:SetPoint("BOTTOM", frame, "BOTTOM", 0, 8)
            closeButton:SetText("Close")
            closeButton:SetScript("OnClick", function()
                frame:Hide()
                flashcardDisplayed = false
                for _, button in ipairs(multiAnswerButtons) do
                    button:Enable() -- Re-enable all buttons
                    button.bg:SetColorTexture(0, 0, 0, 0) -- Reset button color
                    button:Hide() -- Hide all buttons
                end
                closeButton:Hide()
            end)
            closeButton:Show()
        end
    elseif currentCard.type == "hidden" and selectedAnswer then
        if selectedAnswer == "Correct" then
            WoWStudyFunction.RecordAnswer(currentCard.question, currentCard.deckName, "correct")
            WoWStudyFunction.PlayGlowAnimation(frame, greenGlow)
            C_Timer.After(1, function() frame:Hide() flashcardDisplayed = false end)
        else
            WoWStudyFunction.RecordAnswer(currentCard.question, currentCard.deckName, "incorrect")
            WoWStudyFunction.PlayGlowAnimation(frame, redGlow)
            C_Timer.After(1, function() frame:Hide() flashcardDisplayed = false end)
        end
    else
        -- Handle timeout or unhandled case
        WoWStudyFunction.RecordAnswer(currentCard.question, currentCard.deckName, "incorrect")
        WoWStudyFunction.PlayGlowAnimation(frame, redGlow)
        C_Timer.After(1, function() frame:Hide() flashcardDisplayed = false end)
    end

    local ratio = WoWStudyGlobal.currentSession.totalAnswered > 0 and (WoWStudyGlobal.currentSession.totalCorrect / WoWStudyGlobal.currentSession.totalAnswered * 100) or 0
    local ratioNumber = tonumber(string.format("%.0f", ratio))
    -- Update correct count text
    correctCountText:SetText("Correct: " .. WoWStudyGlobal.currentSession.totalCorrect .. " (" .. ratioNumber .. "%)")
    totalCountText:SetText("Total: " .. WoWStudyGlobal.currentSession.totalAnswered)
end

---
-- Show a user a flashcard
---
function WoWStudyFunction.ShowFlashcard()
    if flashcardDisplayed then
        return
    end

    flashcardDisplayed = true
    
    local flashcardFound = false

    local flashcards = {}
    for i, card in ipairs(WoWStudyGlobal.selectedFlashcards) do
        table.insert(flashcards, card)
    end

    local defaultFlashcard = nil
    local maxAttempts = #flashcards

    while (not flashcardFound) and (#flashcards > 0) do
        local index = math.random(1, #flashcards)
        local question = flashcards[index].question
        local deckName = flashcards[index].deckName

        if not defaultFlashcard then
            defaultFlashcard = WoWStudySaved.decks[deckName].cardsByQuestion[question]
        end

        currentCard = WoWStudySaved.decks[deckName].cardsByQuestion[question]

        local currentTime = time()
        flashcardFound = WoWStudyFunction.SpacedRepetitionCheck(currentCard.lastTime, currentTime, currentCard.spacedRepetitionLevel)

        if flashcardFound then
            currentCard.lastTime = currentTime
        else
            table.remove(flashcards, index)
        end
    end

    if not flashcardFound then
        if defaultFlashcard then
            currentCard = defaultFlashcard
        else
            return
        end
    end

    -- Clear all answer components
    if answerFrame then
        answerFrame:Hide()
    end

    if multiAnswerFrame then
        multiAnswerFrame:Hide()
    end

    -- Redraw unhinged way to make answer text appear
    answerButton.title:SetText("Answer")
    answerButton.title:GetWidth()
    answerButton.title:GetStringHeight()
    questionButton.title:SetText("Question")
    questionButton.title:GetWidth()
    questionButton.title:GetStringHeight()


    questionButtonClickFunc(questionButton) -- Select the question button by default (UI - highlights question button)
    frame:Show()
    StartTimer()

end