WhatsNew = {}

local whatsNewWindow = nil
local onCloseCallback = nil

function WhatsNew.init()
    g_logger.info('[WhatsNew] Module loaded')
end

function WhatsNew.terminate()
    WhatsNew.destroy()
end

function WhatsNew.shouldShow()
    local lastSeen = g_settings.get('last_seen_version')
    return lastSeen ~= APP_VERSION
end

function WhatsNew.show(callback)
    if whatsNewWindow then
        return
    end

    onCloseCallback = callback

    whatsNewWindow = g_ui.displayUI('/client_whatsnew/whatsnew')
    if not whatsNewWindow then
        g_logger.error('[WhatsNew] Failed to load OTUI')
        WhatsNew.markSeen()
        if callback then callback() end
        return
    end
    whatsNewWindow:raise()
    whatsNewWindow:focus()

    -- Set version title
    local changelog = CHANGELOGS and CHANGELOGS[APP_VERSION]
    local title = changelog and changelog.title or "Update"
    whatsNewWindow:getChildById('versionLabel'):setText('Version ' .. APP_VERSION .. ' - ' .. title)

    -- Populate changes as single text block
    local changesLabel = whatsNewWindow:recursiveGetChildById('changesLabel')
    local text = ''
    if changelog and changelog.changes then
        for _, change in ipairs(changelog.changes) do
            text = text .. '- ' .. change .. '\n'
        end
    else
        text = 'Updated to version ' .. APP_VERSION
    end
    changesLabel:setText(text)

    -- Hide scrollbar if content fits (defer one tick so layout is computed)
    addEvent(function()
        if not whatsNewWindow then return end
        local scroll = whatsNewWindow:getChildById('changesScroll')
        local bar = whatsNewWindow:getChildById('changesScrollBar')
        if scroll and bar then
            bar:setVisible(changesLabel:getHeight() > scroll:getHeight())
        end
    end)
end

function WhatsNew.close()
    WhatsNew.markSeen()
    WhatsNew.destroy()
    if onCloseCallback then
        local cb = onCloseCallback
        onCloseCallback = nil
        cb()
    end
end

function WhatsNew.markSeen()
    g_settings.set('last_seen_version', APP_VERSION)
    g_settings.save()
end

function WhatsNew.destroy()
    if whatsNewWindow then
        whatsNewWindow:destroy()
        whatsNewWindow = nil
    end
end
