-- [ ACTION BARS - CANVAS PREVIEW ] ------------------------------------------------------------------
---@type Orbit
local Orbit = Orbit
local OrbitEngine = Orbit.Engine
local L = Orbit.L

local DEFAULT_ICON_SIZE = 34
local FALLBACK_TEXTURE = "Interface\\Icons\\INV_Misc_QuestionMark"

Orbit.ActionBarsPreview = {}
local ABPreview = Orbit.ActionBarsPreview

function ABPreview:Setup(plugin, container, systemIndex)
    local LSM = LibStub("LibSharedMedia-3.0")
    container.CreateCanvasPreview = function(self, options)
        -- Resolve icon texture from first visible button
        local iconTexture = FALLBACK_TEXTURE
        local buttons = plugin.buttons[systemIndex]
        if buttons then
            for _, btn in ipairs(buttons) do
                if btn:IsShown() and btn.icon then
                    local tex = btn.icon:GetTexture()
                    if tex then iconTexture = tex; break end
                end
            end
        end

        -- Mirror the live button geometry so previewed text lands where it will on the bar.
        local iconSize = plugin:GetSetting(systemIndex, "IconSize") or DEFAULT_ICON_SIZE
        local preview = OrbitEngine.IconCanvasPreview:Create(self, options.parent or UIParent, iconSize, iconSize, iconTexture)
        preview.systemIndex = systemIndex

        -- Resolve saved positions (global sync aware)
        local useGlobal = plugin:GetSetting(systemIndex, "UseGlobalTextStyle")
        local savedPositions
        if useGlobal ~= false then savedPositions = plugin:GetSetting(1, "GlobalComponentPositions") or {}
        else savedPositions = plugin:GetSetting(systemIndex, "ComponentPositions") or {} end

        local globalFontName = Orbit.db.GlobalSettings.Font
        local fontPath = LSM:Fetch("font", globalFontName) or "Fonts\\FRIZQT__.TTF"

        local kbPreview = (C_GamePad and C_GamePad.IsEnabled and C_GamePad.IsEnabled()) and "|A:Gamepad_Gen_1_32:14:14|a" or "Q"

        -- Font sizes match ActionBarsText live formulas (w = live button width) so the preview is WYSIWYG.
        OrbitEngine.IconCanvasPreview:AttachTextComponents(preview, {
            { key = "Keybind", preview = kbPreview, anchorX = "RIGHT", anchorY = "TOP", offsetX = 2, offsetY = 2, fontSize = math.max(8, iconSize * 0.28) },
            { key = "MacroText", preview = L.PLU_AB_PREVIEW_MACRO, anchorX = "CENTER", anchorY = "BOTTOM", offsetX = 0, offsetY = 2, fontSize = math.max(7, iconSize * 0.22) },
            { key = "Timer", preview = "5", anchorX = "CENTER", anchorY = "CENTER", offsetX = 0, offsetY = 0, fontSize = math.max(10, iconSize * 0.35) },
            { key = "Stacks", preview = "3", anchorX = "LEFT", anchorY = "BOTTOM", offsetX = 2, offsetY = 2, fontSize = math.max(8, iconSize * 0.28) },
        }, savedPositions, fontPath)

        return preview
    end
end
