local addonName, L = ...

local AceGUI = LibStub("AceGUI-3.0")
local ui = L.tabSettingsUI

function ui.RefreshImageWidgets(widgets, profileKey)
    local moduleEnabled = ui.IsProfileModuleEnabled(profileKey)
    local useImage = moduleEnabled and ui.GetField(profileKey, "useImageOverlay") == true
    local selectedImage = ui.EnsureSelectedImage(profileKey)
    local selectedImageAnimated = L.IsAnimatedImageEntry and L:IsAnimatedImageEntry(selectedImage)
    local editModeEnabled = L:IsEditModeEnabled(profileKey)
    local slashTestActive = L.IsSlashAlertTestActive and L:IsSlashAlertTestActive(profileKey)

    widgets.enableImageCheckbox:SetValue(ui.GetField(profileKey, "useImageOverlay") == true)
    widgets.enableImageCheckbox:SetDisabled(not moduleEnabled)
    widgets.grayscaleCheckbox:SetValue(ui.GetField(profileKey, "imageGrayscale"))
    widgets.grayscaleCheckbox:SetDisabled(not useImage)
    widgets.imageDropdown:SetValue(ui.GetField(profileKey, "selectedImageKey"))
    widgets.imageDropdown:SetDisabled(not useImage)
    widgets.scaleSlider:SetValue(ui.GetField(profileKey, "imageScale"))
    widgets.scaleSlider:SetDisabled((not useImage) or slashTestActive)
    widgets.startMoveCheckbox:SetValue(ui.GetField(profileKey, "startMoveEnabled"))
    widgets.startMoveCheckbox:SetDisabled(not useImage)
    widgets.startFadeCheckbox:SetValue(ui.GetField(profileKey, "startFadeEnabled"))
    widgets.startFadeCheckbox:SetDisabled(not useImage)
    widgets.directionDropdown:SetValue(ui.GetField(profileKey, "imageDirection"))
    widgets.directionDropdown:SetDisabled(not useImage)
    widgets.enterEasingDropdown:SetValue(ui.GetField(profileKey, "imageEnterEasing"))
    widgets.enterEasingDropdown:SetDisabled(not useImage)
    widgets.enterEdit:SetText(string.format("%.2f", ui.GetField(profileKey, "imageEnterDuration")))
    widgets.enterEdit:SetDisabled(not useImage)
    widgets.wobbleCheckbox:SetValue(ui.GetField(profileKey, "loopWobbleEnabled"))
    widgets.wobbleCheckbox:SetDisabled(not useImage)
    widgets.wobbleStepEdit:SetText(string.format("%.2f", ui.GetField(profileKey, "imageWobbleStepDuration")))
    widgets.wobbleStepEdit:SetDisabled(not useImage)
    widgets.spinCheckbox:SetValue(ui.GetField(profileKey, "loopSpinEnabled"))
    widgets.spinCheckbox:SetDisabled(not useImage)
    widgets.spinDirectionDropdown:SetValue(ui.GetField(profileKey, "loopSpinDirection"))
    widgets.spinDirectionDropdown:SetDisabled(not useImage)
    widgets.spinDurationEdit:SetText(string.format("%.2f", ui.GetField(profileKey, "loopSpinDuration")))
    widgets.spinDurationEdit:SetDisabled(not useImage)
    widgets.endMoveCheckbox:SetValue(ui.GetField(profileKey, "endMoveEnabled"))
    widgets.endMoveCheckbox:SetDisabled(not useImage)
    widgets.endFadeCheckbox:SetValue(ui.GetField(profileKey, "endFadeEnabled"))
    widgets.endFadeCheckbox:SetDisabled(not useImage)
    widgets.exitEasingDropdown:SetValue(ui.GetField(profileKey, "imageExitEasing"))
    widgets.exitEasingDropdown:SetDisabled(not useImage)
    widgets.exitEdit:SetText(string.format("%.2f", ui.GetField(profileKey, "imageExitDuration")))
    widgets.exitEdit:SetDisabled(not useImage)
    widgets.editModeButton:SetText(editModeEnabled and "Disable Edit Mode" or "Enable Edit Mode")
    widgets.editModeButton:SetDisabled((not useImage) or slashTestActive)
    widgets.resetPositionButton:SetDisabled((not useImage) or slashTestActive)
    -- Preview/Hide stay disabled during edit mode so drag interactions cannot race
    -- against live playback state changes.
    widgets.previewImageButton:SetDisabled((not useImage) or editModeEnabled)
    widgets.hideImageButton:SetDisabled((not useImage) or editModeEnabled)
    widgets.imageLabel:SetText("Selected image: " .. (selectedImage and selectedImage.name or "None") .. (selectedImageAnimated and " | animated sprite sheet" or ""))
    widgets.posLabel:SetText("Position: x=" .. tostring(math.floor(ui.GetField(profileKey, "imageX"))) .. " | y=" .. tostring(math.floor(ui.GetField(profileKey, "imageY"))) .. " | size=" .. string.format("%.2f", ui.GetField(profileKey, "imageScale")) .. " | direction=" .. tostring(ui.GetField(profileKey, "imageDirection")))
    widgets.effectLabel1:SetText("Start animation: move=" .. tostring(ui.GetField(profileKey, "startMoveEnabled")) .. " | fade=" .. tostring(ui.GetField(profileKey, "startFadeEnabled")) .. " | duration=" .. string.format("%.2f", ui.GetField(profileKey, "imageEnterDuration")) .. "s | easing=" .. tostring(ui.GetField(profileKey, "imageEnterEasing")))
    widgets.effectLabel2:SetText("Loop animation: wobble=" .. tostring(ui.GetField(profileKey, "loopWobbleEnabled")) .. " | rotation=" .. tostring(ui.GetField(profileKey, "loopSpinEnabled")) .. " | direction=" .. tostring(ui.GetField(profileKey, "loopSpinDirection")) .. " | duration=" .. string.format("%.2f", ui.GetField(profileKey, "loopSpinDuration")) .. "s" .. (selectedImageAnimated and " | sprite playback=on" or ""))
    widgets.effectLabel3:SetText("End animation: move=" .. tostring(ui.GetField(profileKey, "endMoveEnabled")) .. " | fade=" .. tostring(ui.GetField(profileKey, "endFadeEnabled")) .. " | duration=" .. string.format("%.2f", ui.GetField(profileKey, "imageExitDuration")) .. "s | easing=" .. tostring(ui.GetField(profileKey, "imageExitEasing")))
    widgets.countsLabel:SetText("Available images: " .. tostring(#L.availableImages))
    widgets.stateLabel:SetText("Edit Mode active: " .. tostring(editModeEnabled) .. " | Slash test active: " .. tostring(slashTestActive) .. " | Overlay state: " .. tostring(L:GetOverlaySequenceState()))
end

function ui.BuildImageGroup(root, profileKey, title, intro)
    local widgets = {}
    ui.AddHeading(root, title, intro)

    local generalGroup = AceGUI:Create("InlineGroup")
    generalGroup:SetTitle("Image")
    generalGroup:SetFullWidth(true)
    generalGroup:SetLayout("List")
    root:AddChild(generalGroup)

    local enableImageCheckbox = AceGUI:Create("CheckBox")
    enableImageCheckbox:SetLabel("Show image overlay")
    enableImageCheckbox:SetCallback("OnValueChanged", function(_, _, value)
        ui.SetField(profileKey, "useImageOverlay", value == true)
        if value ~= true and not L:IsEditModeEnabled(profileKey) then
            -- Route hiding through the exit animation instead of instantly dropping
            -- the frame so runtime behavior matches the actual alert shutdown path.
            L:HideOverlay(profileKey)
        end
        L:RefreshTabbedSettingsUIState()
    end)
    generalGroup:AddChild(enableImageCheckbox)

    local grayscaleCheckbox = AceGUI:Create("CheckBox")
    grayscaleCheckbox:SetLabel("Use grayscale")
    grayscaleCheckbox:SetCallback("OnValueChanged", function(_, _, value)
        ui.SetField(profileKey, "imageGrayscale", value == true)
        L:ApplyOverlayVisuals(profileKey)
        L:RefreshTabbedSettingsUIState()
    end)
    generalGroup:AddChild(grayscaleCheckbox)

    local imageDropdown = AceGUI:Create("Dropdown")
    imageDropdown:SetLabel("Image")
    imageDropdown:SetList(L:BuildImageListForAce())
    imageDropdown:SetFullWidth(true)
    imageDropdown:SetCallback("OnValueChanged", function(_, _, value)
        if L.imageIndex[value] then
            ui.SetField(profileKey, "selectedImageKey", value)
            L:ApplyOverlayVisuals(profileKey)
            L:RefreshTabbedSettingsUIState()
        end
    end)
    generalGroup:AddChild(imageDropdown)

    local scaleSlider = AceGUI:Create("Slider")
    scaleSlider:SetLabel("Image size")
    scaleSlider:SetSliderValues(0.2, 3.0, 0.05)
    scaleSlider:SetFullWidth(true)
    scaleSlider:SetCallback("OnValueChanged", function(_, _, value)
        if L.IsSlashAlertTestActive and L:IsSlashAlertTestActive(profileKey) then
            return
        end
        ui.SetField(profileKey, "imageScale", tonumber(value) or ui.GetField(profileKey, "imageScale"))
        L:ApplyOverlayVisuals(profileKey)
        L:RefreshTabbedSettingsUIState()
    end)
    generalGroup:AddChild(scaleSlider)

    local toolsGroup = AceGUI:Create("InlineGroup")
    toolsGroup:SetTitle("Position & Preview")
    toolsGroup:SetFullWidth(true)
    toolsGroup:SetLayout("List")
    root:AddChild(toolsGroup)

    local helpLabel = AceGUI:Create("Label")
    helpLabel:SetText("Use Edit Mode to move the image on screen. Preview and Hide are disabled while Edit Mode is active.")
    helpLabel:SetFullWidth(true)
    toolsGroup:AddChild(helpLabel)

    local buttonRow = AceGUI:Create("SimpleGroup")
    buttonRow:SetFullWidth(true)
    buttonRow:SetLayout("Flow")
    toolsGroup:AddChild(buttonRow)

    local editModeButton = AceGUI:Create("Button")
    editModeButton:SetWidth(160)
    editModeButton:SetCallback("OnClick", function()
        L:SetEditMode(not L:IsEditModeEnabled(profileKey), profileKey)
        L:RefreshTabbedSettingsUIState()
    end)
    buttonRow:AddChild(editModeButton)
    ui.DisableMouseDown(editModeButton)

    local resetPositionButton = AceGUI:Create("Button")
    resetPositionButton:SetText("Reset position")
    resetPositionButton:SetWidth(140)
    resetPositionButton:SetCallback("OnClick", function()
        if L.IsSlashAlertTestActive and L:IsSlashAlertTestActive(profileKey) then
            return
        end
        ui.SetField(profileKey, "imageX", L.DEFAULT_IMAGE_X)
        ui.SetField(profileKey, "imageY", L.DEFAULT_IMAGE_Y)
        ui.SetField(profileKey, "imageScale", L.DEFAULT_IMAGE_SCALE)
        L:ApplyOverlayVisuals(profileKey)
        L:RefreshTabbedSettingsUIState()
    end)
    buttonRow:AddChild(resetPositionButton)
    ui.DisableMouseDown(resetPositionButton)

    local previewImageButton = AceGUI:Create("Button")
    previewImageButton:SetText("Preview overlay")
    previewImageButton:SetWidth(140)
    previewImageButton:SetCallback("OnClick", function()
        L:ShowOverlayPreview(profileKey)
    end)
    buttonRow:AddChild(previewImageButton)
    ui.DisableMouseDown(previewImageButton)

    local hideImageButton = AceGUI:Create("Button")
    hideImageButton:SetText("Hide overlay")
    hideImageButton:SetWidth(140)
    hideImageButton:SetCallback("OnClick", function()
        L:HideOverlay(profileKey)
    end)
    buttonRow:AddChild(hideImageButton)
    ui.DisableMouseDown(hideImageButton)

    local startGroup = AceGUI:Create("InlineGroup")
    startGroup:SetTitle("Start Animation")
    startGroup:SetFullWidth(true)
    startGroup:SetLayout("List")
    root:AddChild(startGroup)

    local startHelpLabel = AceGUI:Create("Label")
    startHelpLabel:SetText("Choose how the image enters when the alert begins.")
    startHelpLabel:SetFullWidth(true)
    startGroup:AddChild(startHelpLabel)

    local startMoveCheckbox = AceGUI:Create("CheckBox")
    startMoveCheckbox:SetLabel("Move in from this direction")
    ui.SetWidgetFullWidth(startMoveCheckbox)
    startMoveCheckbox:SetCallback("OnValueChanged", function(_, _, value)
        ui.SetField(profileKey, "startMoveEnabled", value == true)
        L:RefreshTabbedSettingsUIState()
    end)
    startGroup:AddChild(startMoveCheckbox)

    local startFadeCheckbox = AceGUI:Create("CheckBox")
    startFadeCheckbox:SetLabel("Fade in")
    ui.SetWidgetFullWidth(startFadeCheckbox)
    startFadeCheckbox:SetCallback("OnValueChanged", function(_, _, value)
        ui.SetField(profileKey, "startFadeEnabled", value == true)
        L:RefreshTabbedSettingsUIState()
    end)
    startGroup:AddChild(startFadeCheckbox)

    local directionDropdown = AceGUI:Create("Dropdown")
    directionDropdown:SetLabel("Start direction")
    directionDropdown:SetList(L:BuildDirectionListForAce())
    directionDropdown:SetFullWidth(true)
    directionDropdown:SetCallback("OnValueChanged", function(_, _, value)
        ui.SetField(profileKey, "imageDirection", value)
        L:RefreshTabbedSettingsUIState()
    end)
    startGroup:AddChild(directionDropdown)

    local enterEasingDropdown = AceGUI:Create("Dropdown")
    enterEasingDropdown:SetLabel("Start easing")
    enterEasingDropdown:SetList(L:BuildEasingListForAce())
    enterEasingDropdown:SetFullWidth(true)
    enterEasingDropdown:SetCallback("OnValueChanged", function(_, _, value)
        ui.SetField(profileKey, "imageEnterEasing", value)
        L:RefreshTabbedSettingsUIState()
    end)
    startGroup:AddChild(enterEasingDropdown)

    local enterEdit = AceGUI:Create("EditBox")
    enterEdit:SetLabel("Start duration (seconds)")
    enterEdit:SetFullWidth(true)
    enterEdit:DisableButton(true)
    enterEdit:SetCallback("OnEnterPressed", function(_, _, value)
        ui.SetField(profileKey, "imageEnterDuration", L:ParsePositiveNumber(value, ui.GetField(profileKey, "imageEnterDuration")))
        L:RefreshTabbedSettingsUIState()
    end)
    startGroup:AddChild(enterEdit)

    local loopGroup = AceGUI:Create("InlineGroup")
    loopGroup:SetTitle("While Active")
    loopGroup:SetFullWidth(true)
    loopGroup:SetLayout("List")
    root:AddChild(loopGroup)

    local loopHelpLabel = AceGUI:Create("Label")
    loopHelpLabel:SetText("Choose what the image does while the alert stays active.")
    loopHelpLabel:SetFullWidth(true)
    loopGroup:AddChild(loopHelpLabel)

    local wobbleCheckbox = AceGUI:Create("CheckBox")
    wobbleCheckbox:SetLabel("Enable wobble")
    wobbleCheckbox:SetCallback("OnValueChanged", function(_, _, value)
        ui.SetField(profileKey, "loopWobbleEnabled", value == true)
        L:RefreshTabbedSettingsUIState()
    end)
    loopGroup:AddChild(wobbleCheckbox)

    local wobbleStepEdit = AceGUI:Create("EditBox")
    wobbleStepEdit:SetLabel("Wobble speed (seconds)")
    wobbleStepEdit:SetFullWidth(true)
    wobbleStepEdit:DisableButton(true)
    wobbleStepEdit:SetCallback("OnEnterPressed", function(_, _, value)
        ui.SetField(profileKey, "imageWobbleStepDuration", L:ParsePositiveNumber(value, ui.GetField(profileKey, "imageWobbleStepDuration")))
        L:RefreshTabbedSettingsUIState()
    end)
    loopGroup:AddChild(wobbleStepEdit)

    local spinCheckbox = AceGUI:Create("CheckBox")
    spinCheckbox:SetLabel("Enable rotation")
    spinCheckbox:SetCallback("OnValueChanged", function(_, _, value)
        ui.SetField(profileKey, "loopSpinEnabled", value == true)
        L:RefreshTabbedSettingsUIState()
    end)
    loopGroup:AddChild(spinCheckbox)

    local spinDirectionDropdown = AceGUI:Create("Dropdown")
    spinDirectionDropdown:SetLabel("Spin direction")
    spinDirectionDropdown:SetList(L:BuildSpinDirectionListForAce())
    spinDirectionDropdown:SetFullWidth(true)
    spinDirectionDropdown:SetCallback("OnValueChanged", function(_, _, value)
        ui.SetField(profileKey, "loopSpinDirection", value)
        L:RefreshTabbedSettingsUIState()
    end)
    loopGroup:AddChild(spinDirectionDropdown)

    local spinDurationEdit = AceGUI:Create("EditBox")
    spinDurationEdit:SetLabel("Time per full rotation (seconds)")
    spinDurationEdit:SetFullWidth(true)
    spinDurationEdit:DisableButton(true)
    spinDurationEdit:SetCallback("OnEnterPressed", function(_, _, value)
        ui.SetField(profileKey, "loopSpinDuration", L:ParsePositiveNumber(value, ui.GetField(profileKey, "loopSpinDuration")))
        L:RefreshTabbedSettingsUIState()
    end)
    loopGroup:AddChild(spinDurationEdit)

    local endGroup = AceGUI:Create("InlineGroup")
    endGroup:SetTitle("End Animation")
    endGroup:SetFullWidth(true)
    endGroup:SetLayout("List")
    root:AddChild(endGroup)

    local endHelpLabel = AceGUI:Create("Label")
    endHelpLabel:SetText("Choose how the image leaves when the alert ends or is hidden.")
    endHelpLabel:SetFullWidth(true)
    endGroup:AddChild(endHelpLabel)

    local endMoveCheckbox = AceGUI:Create("CheckBox")
    endMoveCheckbox:SetLabel("Move out toward this direction")
    ui.SetWidgetFullWidth(endMoveCheckbox)
    endMoveCheckbox:SetCallback("OnValueChanged", function(_, _, value)
        ui.SetField(profileKey, "endMoveEnabled", value == true)
        L:RefreshTabbedSettingsUIState()
    end)
    endGroup:AddChild(endMoveCheckbox)

    local endFadeCheckbox = AceGUI:Create("CheckBox")
    endFadeCheckbox:SetLabel("Fade out")
    ui.SetWidgetFullWidth(endFadeCheckbox)
    endFadeCheckbox:SetCallback("OnValueChanged", function(_, _, value)
        ui.SetField(profileKey, "endFadeEnabled", value == true)
        L:RefreshTabbedSettingsUIState()
    end)
    endGroup:AddChild(endFadeCheckbox)

    local exitEasingDropdown = AceGUI:Create("Dropdown")
    exitEasingDropdown:SetLabel("End easing")
    exitEasingDropdown:SetList(L:BuildEasingListForAce())
    exitEasingDropdown:SetFullWidth(true)
    exitEasingDropdown:SetCallback("OnValueChanged", function(_, _, value)
        ui.SetField(profileKey, "imageExitEasing", value)
        L:RefreshTabbedSettingsUIState()
    end)
    endGroup:AddChild(exitEasingDropdown)

    local exitEdit = AceGUI:Create("EditBox")
    exitEdit:SetLabel("End duration (seconds)")
    exitEdit:SetFullWidth(true)
    exitEdit:DisableButton(true)
    exitEdit:SetCallback("OnEnterPressed", function(_, _, value)
        ui.SetField(profileKey, "imageExitDuration", L:ParsePositiveNumber(value, ui.GetField(profileKey, "imageExitDuration")))
        L:RefreshTabbedSettingsUIState()
    end)
    endGroup:AddChild(exitEdit)

    local statusGroup = AceGUI:Create("InlineGroup")
    statusGroup:SetTitle("Live Summary")
    statusGroup:SetFullWidth(true)
    statusGroup:SetLayout("List")
    root:AddChild(statusGroup)

    local imageLabel = AceGUI:Create("Label")
    imageLabel:SetFullWidth(true)
    statusGroup:AddChild(imageLabel)

    local posLabel = AceGUI:Create("Label")
    posLabel:SetFullWidth(true)
    statusGroup:AddChild(posLabel)

    local effectLabel1 = AceGUI:Create("Label")
    effectLabel1:SetFullWidth(true)
    statusGroup:AddChild(effectLabel1)

    local effectLabel2 = AceGUI:Create("Label")
    effectLabel2:SetFullWidth(true)
    statusGroup:AddChild(effectLabel2)

    local effectLabel3 = AceGUI:Create("Label")
    effectLabel3:SetFullWidth(true)
    statusGroup:AddChild(effectLabel3)

    local countsLabel = AceGUI:Create("Label")
    countsLabel:SetFullWidth(true)
    statusGroup:AddChild(countsLabel)

    local stateLabel = AceGUI:Create("Label")
    stateLabel:SetFullWidth(true)
    statusGroup:AddChild(stateLabel)

    widgets.enableImageCheckbox = enableImageCheckbox
    widgets.grayscaleCheckbox = grayscaleCheckbox
    widgets.imageDropdown = imageDropdown
    widgets.scaleSlider = scaleSlider
    widgets.startMoveCheckbox = startMoveCheckbox
    widgets.startFadeCheckbox = startFadeCheckbox
    widgets.directionDropdown = directionDropdown
    widgets.enterEasingDropdown = enterEasingDropdown
    widgets.enterEdit = enterEdit
    widgets.wobbleCheckbox = wobbleCheckbox
    widgets.wobbleStepEdit = wobbleStepEdit
    widgets.spinCheckbox = spinCheckbox
    widgets.spinDirectionDropdown = spinDirectionDropdown
    widgets.spinDurationEdit = spinDurationEdit
    widgets.endMoveCheckbox = endMoveCheckbox
    widgets.endFadeCheckbox = endFadeCheckbox
    widgets.exitEasingDropdown = exitEasingDropdown
    widgets.exitEdit = exitEdit
    widgets.editModeButton = editModeButton
    widgets.resetPositionButton = resetPositionButton
    widgets.previewImageButton = previewImageButton
    widgets.hideImageButton = hideImageButton
    widgets.imageLabel = imageLabel
    widgets.posLabel = posLabel
    widgets.effectLabel1 = effectLabel1
    widgets.effectLabel2 = effectLabel2
    widgets.effectLabel3 = effectLabel3
    widgets.countsLabel = countsLabel
    widgets.stateLabel = stateLabel
    return widgets
end
