local PT = AhUI
if not PT then return end
local L = PT.L
local Welcome = {}
PT.WelcomeUI = Welcome

local ADDON_NAME = "AhUI"
local FONT = AhUI.FONT

function Welcome:Create()
    if self.frame then return self.frame end
	self.checkboxes = {}
PT.config = PT.config or {}

local defaults = {
    showConcentration     = true,
    skinningCheckEnabled  = false,
    showProfessionsWindow = true,
    confirmOK             = true,
    confirmReload         = false,
}

local function RefreshSettings()
    if PT.Settings and PT.Settings.Refresh then
        PT.Settings:Refresh()
    end
end

local function GetEnabled(key)
    return PT.config[key] ~= false
end

for k, v in pairs(defaults) do
    if PT.config[k] == nil then
        PT.config[k] = v
    end
end
    AhUI_DB = AhUI_DB or {}
    AhUI_CharConfig = AhUI_CharConfig or {}

    local f = CreateFrame("Frame", "AhUIWelcomeFrame", UIParent, "BackdropTemplate")
    f:SetSize(420, 360)
    f:SetPoint("CENTER")
    f:SetFrameStrata("DIALOG")

    f:SetBackdrop({
        bgFile   = "Interface\\Buttons\\WHITE8x8",
        edgeFile = "Interface\\Buttons\\WHITE8x8",
        edgeSize = 3,
    })
    f:SetBackdropColor(0, 0, 0, 0.95)
    f:SetBackdropBorderColor(1, 1, 1, 1)

    f:Hide()
    tinsert(UISpecialFrames, f:GetName())

    local logo = f:CreateTexture(nil, "ARTWORK")
    logo:SetSize(128, 128)
    logo:SetPoint("TOP", 0, -20)
    logo:SetTexture("Interface\\AddOns\\AhUI\\media\\logo.png")

    local text = f:CreateFontString(nil, "OVERLAY")
    text:SetFont(FONT, 14, "")
    text:SetWidth(360)
    text:SetJustifyH("CENTER")
    text:SetJustifyV("TOP")
    text:SetPoint("TOP", logo, "BOTTOM", 0, -12)
    text:SetText(L["WELCOME_TEXT"])

    local yLeft  = -220
    local yRight = -220

	local WelcomeTooltip = CreateFrame("Frame", nil, f, "BackdropTemplate")
	WelcomeTooltip:SetFrameStrata("TOOLTIP")
	WelcomeTooltip:SetBackdrop({
		bgFile   = "Interface\\Buttons\\WHITE8x8",
		edgeFile = "Interface\\Buttons\\WHITE8x8",
		edgeSize = 2,
	})
	WelcomeTooltip:SetBackdropColor(0, 0, 0, 0.95)
	WelcomeTooltip:SetBackdropBorderColor(1, 1, 1, 1)
	WelcomeTooltip:SetClampedToScreen(true)
	WelcomeTooltip:SetFrameStrata("TOOLTIP")
	WelcomeTooltip:EnableMouse(false)
	WelcomeTooltip:Hide()

	local WTText = WelcomeTooltip:CreateFontString(nil, "OVERLAY")
	WTText:SetFont(FONT, 13, "")
	WTText:SetPoint("TOPLEFT", 10, -10)
	WTText:SetPoint("BOTTOMRIGHT", -10, 10)
	WTText:SetJustifyH("LEFT")
	WTText:SetJustifyV("TOP")
	WTText:SetWordWrap(true)

local function ApplyTooltip(cb, tip)
    if not cb or not tip or tip == "" then return end

    local function UpdatePosition()
        local scale = UIParent:GetEffectiveScale()
        local x, y = GetCursorPosition()
        x = x / scale
        y = y / scale

        WelcomeTooltip:ClearAllPoints()
        WelcomeTooltip:SetPoint("BOTTOMLEFT", UIParent, "BOTTOMLEFT", x + 14, y + 18)

        if WelcomeTooltip:GetRight() and WelcomeTooltip:GetRight() > UIParent:GetRight() then
            WelcomeTooltip:ClearAllPoints()
            WelcomeTooltip:SetPoint("BOTTOMRIGHT", UIParent, "BOTTOMLEFT", x - 14, y + 18)
        end

        if WelcomeTooltip:GetTop() and WelcomeTooltip:GetTop() > UIParent:GetTop() then
            WelcomeTooltip:ClearAllPoints()
            WelcomeTooltip:SetPoint("TOPLEFT", UIParent, "BOTTOMLEFT", x + 14, y - 18)
        end
    end

    local function ShowTip()
        WTText:SetText(tip)
        WelcomeTooltip:SetWidth(300)
        WelcomeTooltip:SetHeight(WTText:GetStringHeight() + 20)
        WelcomeTooltip:Show()
        UpdatePosition()
        WelcomeTooltip:SetScript("OnUpdate", UpdatePosition)
    end

    local function HideTip()
        WelcomeTooltip:SetScript("OnUpdate", nil)
        WelcomeTooltip:Hide()
    end

    cb:EnableMouse(true)
    cb:SetScript("OnEnter", ShowTip)
    cb:SetScript("OnLeave", HideTip)

    if cb.text then
        cb.text:EnableMouse(true)
        cb.text:SetScript("OnEnter", ShowTip)
        cb.text:SetScript("OnLeave", HideTip)
    end
end

    local function AddCheckLeft(label, tip, getter, setter)
        local cb = CreateFrame("CheckButton", nil, f, "UICheckButtonTemplate")
        cb:SetPoint("TOPLEFT", 30, yLeft)
        cb.text:SetText(label)
        cb.text:SetFont(FONT, 13, "")
        cb:SetChecked(getter())

        cb:SetScript("OnClick", function(self)
            setter(self:GetChecked())
        end)

        ApplyTooltip(cb, tip)

        yLeft = yLeft - 28
        cb.GetValue = getter
		table.insert(self.checkboxes, cb)
		return cb
    end

    local function AddCheckRight(label, tip, getter, setter)
        local cb = CreateFrame("CheckButton", nil, f, "UICheckButtonTemplate")
        cb:SetPoint("TOPLEFT", 230, yRight)
        cb.text:SetText(label)
        cb.text:SetFont(FONT, 13, "")
        cb:SetChecked(getter())

        cb:SetScript("OnClick", function(self)
            setter(self:GetChecked())
        end)

        ApplyTooltip(cb, tip)

        yRight = yRight - 28
        cb.GetValue = getter
		table.insert(self.checkboxes, cb)
		return cb
    end

   AddCheckLeft(
    L["WELCOME_CONCENTRATION"],
    L["WELCOME_CONCENTRATION_TIP"],
	function() return GetEnabled("showConcentration") end,
        function(v)
            PT.config.showConcentration = v
            if PT.ConcentrationUI then
                if v then PT.ConcentrationUI:Show()
                else PT.ConcentrationUI:Hide() end
            end
			RefreshSettings()
        end
    )

AddCheckLeft(
    L["WELCOME_SKINNING"],
    L["WELCOME_SKINNING_TIP"],
	function() return GetEnabled("skinningCheckEnabled") end,
		function(v)
			PT.config.skinningCheckEnabled = v
			if PT.UI_SkinningCheck then
				PT.UI_SkinningCheck:Update()
			end
			RefreshSettings()
		end
    )

AddCheckLeft(
    L["WELCOME_PROF_WINDOW"],
    L["WELCOME_PROF_WINDOW_TIP"],
    function() return GetEnabled("showProfessionsWindow") end,
    function(v)
        PT.config.showProfessionsWindow = v

        if v then
            if PT.UI then
                PT.UI:CreateMainFrame()
            end

            if PT.RefreshData then
                PT:RefreshData()
            end

            if PT.RefreshUI then
                PT:RefreshUI()
            end
        end

        if PT.UI and PT.UI.frame then
            if v then
                PT.UI.frame:Show()
            else
                PT.UI.frame:Hide()
            end
        end

        RefreshSettings()
    end
)

AddCheckLeft(
    L["WELCOME_INFOPANEL"],
    L["WELCOME_INFOPANEL_TIP"],
	function()
            return PT.InfoPanel
               and PT.InfoPanel.config
               and PT.InfoPanel.config.enabled ~= false
        end,
function(v)
    if PT.InfoPanel then
        PT.InfoPanel:SetEnabled(v)
    end

    RefreshSettings()
end
)

AddCheckRight(
    L["WELCOME_CONFIRM_OK"],
    L["WELCOME_CONFIRM_OK_TIP"],
function() return GetEnabled("confirmOK") end,
function(v)
    PT.config.confirmOK = v

    if PT.ConfirmButtons then
        PT.ConfirmButtons:SetOKEnabled(v)
    end

    RefreshSettings()
end
)

AddCheckRight(
    L["WELCOME_CONFIRM_RELOAD"],
    L["WELCOME_CONFIRM_RELOAD_TIP"],
function() return GetEnabled("confirmReload") end,
function(v)
    PT.config.confirmReload = v

    if PT.ConfirmButtons then
        PT.ConfirmButtons:SetReloadEnabled(v)
    end

    RefreshSettings()
end
)

    local openOptions = CreateFrame("Button", nil, f, "UIPanelButtonTemplate")
    openOptions:SetSize(120, 24)
    openOptions:SetPoint("TOPLEFT", 230, yRight - 6)
    openOptions:SetText(L["WELCOME_OPEN_SETTINGS"])

    do
        local fs = openOptions:GetFontString()
        if fs then fs:SetFont(FONT, 13, "") end
    end

    openOptions:SetScript("OnClick", function()
        f:Hide()
        if PT.Settings and PT.Settings.category then
            Settings.OpenToCategory(PT.Settings.category:GetID())
        end
    end)

    local ok = CreateFrame("Button", nil, f, "UIPanelButtonTemplate")
    ok:SetSize(120, 26)
    ok:SetPoint("BOTTOM", 0, 16)
    ok:SetText(L["WELCOME_DONE"])
    do
        local fs = ok:GetFontString()
        if fs then fs:SetFont(FONT, 13, "") end
    end

    ok:SetScript("OnClick", function()
        AhUI_DB.welcomeShown = true
		AhUI_CharConfig.__welcomeApplied = true
    if PT.ConfirmButtons then
PT.ConfirmButtons:SetOKEnabled(PT.config.confirmOK == true)
PT.ConfirmButtons:SetReloadEnabled(PT.config.confirmReload == true)
    end		
        f:Hide()
    end)

    self.frame = f
    return f
end

function Welcome:Refresh()
    if not self.checkboxes then return end

    for _, cb in ipairs(self.checkboxes) do
        if cb.GetValue then
            cb:SetChecked(cb.GetValue())
        end
    end
end

function Welcome:Show()
    self:Create():Show()
end

SLASH_AHUIWELCOME1 = "/ahuiwelcome"
SLASH_AHUIWELCOME2 = "/ahwelcome"

SlashCmdList["AHUIWELCOME"] = function()
    if PT.WelcomeUI then
        PT.WelcomeUI:Show()
    end
end

local ev = CreateFrame("Frame")
ev:RegisterEvent("PLAYER_LOGIN")
ev:SetScript("OnEvent", function()
    AhUI_DB = AhUI_DB or {}

    if not AhUI_DB.welcomeShown then
        AhUI_DB.welcomeShown = true
        C_Timer.After(0.5, function()
            Welcome:Create():Show()
        end)
    end
end)