local addonName, ns = ...

function ns.CreateProfilesTab()
    local UI = ns.UI
    local Palette = ns.Palette

    UI.tabFrames[4] = UI.CreateTabContent()
    UI.tabButtons[4] = UI.CreateTabButton("Profiles", 4)

    local frame = UI.tabFrames[4]

    -- ============================================================
    -- Profile-tab buttons share the chrome look from Framework
    -- ============================================================
    local CreateButton = UI.CreateChromeButton

    -- ============================================================
    -- Import / Export dialog (lazy-created, shared between buttons)
    -- ============================================================
    local profileDialog

    local function GetProfileDialog()
        if profileDialog then return profileDialog end

        local f = CreateFrame("Frame", "BlitzFramesTargetsProfileDialog", UIParent, "BackdropTemplate")
        f:SetSize(540, 320)
        f:SetPoint("CENTER")
        f:SetFrameStrata("FULLSCREEN_DIALOG")
        f:SetFrameLevel(200)
        f:SetToplevel(true)
        f:SetBackdrop({
            bgFile   = "Interface\\Buttons\\WHITE8x8",
            edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
            edgeSize = 14,
            insets   = { left = 4, right = 4, top = 4, bottom = 4 },
        })
        f:SetBackdropColor(0.05, 0.05, 0.05, 0.95)
        -- Same neutral edge as the main panel — accent hues never live on
        -- static borders in this skin
        f:SetBackdropBorderColor(unpack(Palette.panelBorder))
        f:EnableMouse(true)
        f:SetMovable(true)
        f:RegisterForDrag("LeftButton")
        f:SetScript("OnDragStart", f.StartMoving)
        f:SetScript("OnDragStop",  f.StopMovingOrSizing)
        f:Hide()

        f.title = f:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
        f.title:SetPoint("TOP", 0, -14)
        f.title:SetTextColor(unpack(Palette.textBright))

        local scroll = CreateFrame("ScrollFrame", "BlitzFramesTargetsProfileDialogScroll", f, "UIPanelScrollFrameTemplate")
        scroll:SetPoint("TOPLEFT",     16, -44)
        scroll:SetPoint("BOTTOMRIGHT", -32, 60)

        local editBox = CreateFrame("EditBox", nil, scroll)
        editBox:SetMultiLine(true)
        editBox:SetMaxBytes(0)
        editBox:SetFontObject(ChatFontNormal)
        editBox:SetWidth(490)
        editBox:SetAutoFocus(false)
        editBox:SetScript("OnEscapePressed", function(self) self:ClearFocus() end)
        scroll:SetScrollChild(editBox)
        f.editBox = editBox

        f.errorText = f:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
        f.errorText:SetPoint("BOTTOMLEFT", 16, 36)
        f.errorText:SetTextColor(unpack(Palette.textError))
        f.errorText:SetText("")

        local actionBtn = CreateButton(f, 120, 26, "Close")
        actionBtn:SetPoint("BOTTOMRIGHT", -16, 12)
        f.actionBtn = actionBtn

        local cancelBtn = CreateButton(f, 120, 26, "Cancel")
        cancelBtn:SetPoint("RIGHT", actionBtn, "LEFT", -8, 0)
        cancelBtn:SetScript("OnClick", function() f:Hide() end)
        f.cancelBtn = cancelBtn

        function f:Configure(mode, initialText, titleText, onAccept)
            self.title:SetText(titleText or "Profile")
            self.errorText:SetText("")
            self.editBox:SetText(initialText or "")
            self.editBox:ClearFocus()
            if mode == "export" then
                self.editBox:SetScript("OnTextChanged", function(eb)
                    eb:SetText(initialText or "")
                    eb:HighlightText()
                end)
                self.cancelBtn:Hide()
                self.actionBtn.text:SetText("Close")
                self.actionBtn:SetScript("OnClick", function() f:Hide() end)
                C_Timer.After(0, function()
                    self.editBox:SetFocus()
                    self.editBox:HighlightText()
                end)
            else
                self.editBox:SetScript("OnTextChanged", nil)
                self.cancelBtn:Show()
                self.actionBtn.text:SetText("Import")
                self.actionBtn:SetScript("OnClick", function()
                    local ok, msg = onAccept(self.editBox:GetText())
                    if ok then
                        f:Hide()
                    else
                        self.errorText:SetText("Error: " .. (msg or "unknown"))
                    end
                end)
                C_Timer.After(0, function() self.editBox:SetFocus() end)
            end
        end

        profileDialog = f
        return f
    end

    -- ============================================================
    -- Layout constants
    -- ============================================================
    local LEFT_X    = 60
    local MID_X     = 555
    local RIGHT_X   = 1090
    local BTN_W     = 160
    local BTN_H     = 32
    local INPUT_W   = 220
    local DROP_W    = 280
    local COL_Y     = -190  -- all column first-sections start here
    local SECTION2_Y = -345 -- Rename and Reset align here

    local function MakeHeader(text, x, y, size)
        local fs = frame:CreateFontString(nil, "OVERLAY")
        fs:SetFont(ns.LOCALE_FONT, size or 14, "")
        fs:SetPoint("TOPLEFT", x, y)
        fs:SetText(text)
        fs:SetTextColor(1, 1, 1)
        return fs
    end

    local function MakeInput(x, y)
        local box = CreateFrame("EditBox", nil, frame, "InputBoxTemplate")
        box:SetSize(INPUT_W, 20)
        box:SetPoint("TOPLEFT", x, y)
        box:SetAutoFocus(false)
        box:SetFont(ns.LOCALE_FONT, 11, "")
        box:SetMaxLetters(64)
        return box
    end

    local function ReplayAnimation()
        if ns.settingsPanel then
            ns.settingsPanel:Hide()
            ns.settingsPanel:Show()
        end
    end

    -- ============================================================
    -- Active Profile (centrepiece, top of middle column)
    -- ============================================================
    MakeHeader("Active Profile", MID_X, -30, 22)

    local dropdown = CreateFrame("DropdownButton", "BlitzFramesTargetsProfileDropdown", frame, "WowStyle1DropdownTemplate")
    dropdown:SetPoint("TOPLEFT", MID_X, -64)
    dropdown:SetWidth(DROP_W)

    local function RefreshDropdown()
        dropdown:GenerateMenu()
    end

    dropdown:SetupMenu(function(_, rootDescription)
        if not ns.db or not ns.db.profiles then return end
        local names = {}
        for name in pairs(ns.db.profiles) do names[#names + 1] = name end
        table.sort(names)
        for _, name in ipairs(names) do
            rootDescription:CreateRadio(name,
                function() return ns.db.activeProfile == name end,
                function()
                    if InCombatLockdown() then
                        print("|cffff0000BlitzFramesTargets:|r Cannot switch profile in combat.")
                        return
                    end
                    ns.ActivateProfile(name)
                    ns.RebuildBars()
                    ReplayAnimation()
                end
            )
        end
    end)

    -- ============================================================
    -- Left column: New Profile (COL_Y), Rename (SECTION2_Y)
    -- ============================================================
    MakeHeader("New Profile", LEFT_X, COL_Y)
    local createInput = MakeInput(LEFT_X, COL_Y - 28)
    local createBtn = CreateButton(frame, BTN_W, BTN_H, "Create")
    createBtn:SetPoint("TOPLEFT", LEFT_X, COL_Y - 58)
    createBtn:SetScript("OnClick", function()
        local name = createInput:GetText():match("^%s*(.-)%s*$")
        if name == "" then return end
        if InCombatLockdown() then
            print("|cffff0000BlitzFramesTargets:|r Cannot create profile in combat.")
            return
        end
        if ns.db.profiles[name] then
            print("|cffff0000BlitzFramesTargets:|r A profile named '" .. name .. "' already exists.")
            return
        end
        ns.db.profiles[name] = ns.DeepCopy(ns.settings)
        ns.ActivateProfile(name)
        createInput:SetText("")
        print("|cff00ff00BlitzFramesTargets:|r Profile '" .. name .. "' created.")
        ReplayAnimation()
    end)

    MakeHeader("Rename Current Profile", LEFT_X, SECTION2_Y)
    local renameInput = MakeInput(LEFT_X, SECTION2_Y - 28)
    local renameBtn = CreateButton(frame, BTN_W, BTN_H, "Rename")
    renameBtn:SetPoint("TOPLEFT", LEFT_X, SECTION2_Y - 58)
    renameBtn:SetScript("OnClick", function()
        local newName = renameInput:GetText():match("^%s*(.-)%s*$")
        if newName == "" then return end
        if InCombatLockdown() then
            print("|cffff0000BlitzFramesTargets:|r Cannot rename profile in combat.")
            return
        end
        local ok, err = ns.RenameProfile(ns.db.activeProfile, newName)
        if ok then
            renameInput:SetText("")
            RefreshDropdown()
            print("|cff00ff00BlitzFramesTargets:|r Profile renamed to '" .. newName .. "'.")
        elseif err == "exists" then
            print("|cffff0000BlitzFramesTargets:|r A profile named '" .. newName .. "' already exists.")
        end
    end)

    -- ============================================================
    -- Middle column: Delete (COL_Y), Reset (SECTION2_Y)
    -- ============================================================
    MakeHeader("Delete Current Profile", MID_X, COL_Y)
    local deleteBtn = CreateButton(frame, BTN_W, BTN_H, "Delete Profile")
    deleteBtn:SetPoint("TOPLEFT", MID_X, COL_Y - 44)
    deleteBtn:SetScript("OnClick", function()
        if InCombatLockdown() then
            print("|cffff0000BlitzFramesTargets:|r Cannot delete profile in combat.")
            return
        end
        local count = 0
        for _ in pairs(ns.db.profiles) do count = count + 1 end
        if count <= 1 then
            print("|cffff0000BlitzFramesTargets:|r Cannot delete the only remaining profile.")
            return
        end
        local name = ns.db.activeProfile
        UI.ShowConfirm({
            title      = "Delete Profile",
            body       = "Permanently delete the profile \"" .. name .. "\"?\n\nEvery setting stored in it is lost. This cannot be undone.",
            acceptText = "Delete",
            onAccept   = function()
                -- Re-check on accept: the dialog is modeless, so combat or a
                -- profile switch could have happened while it was open.
                if InCombatLockdown() then
                    print("|cffff0000BlitzFramesTargets:|r Cannot delete profile in combat.")
                    return
                end
                if not ns.db.profiles[name] then return end
                local n = 0
                for _ in pairs(ns.db.profiles) do n = n + 1 end
                if n <= 1 then return end
                ns.DeleteProfile(name)
                ns.RebuildBars()
                ReplayAnimation()
                print("|cffffd100BlitzFramesTargets:|r Profile '" .. name .. "' deleted.")
            end,
        })
    end)

    MakeHeader("Reset Current Profile", MID_X, SECTION2_Y)
    local resetBtn = CreateButton(frame, BTN_W, BTN_H, "Reset to Defaults")
    resetBtn:SetPoint("TOPLEFT", MID_X, SECTION2_Y - 44)
    resetBtn:SetScript("OnClick", function()
        if InCombatLockdown() then
            print("|cffff0000BlitzFramesTargets:|r Cannot reset profile in combat.")
            return
        end
        local name = ns.db.activeProfile
        UI.ShowConfirm({
            title      = "Reset Profile",
            body       = "Reset every setting in \"" .. name .. "\" to its default?\n\nThis cannot be undone.",
            acceptText = "Reset",
            onAccept   = function()
                if InCombatLockdown() then
                    print("|cffff0000BlitzFramesTargets:|r Cannot reset profile in combat.")
                    return
                end
                for k, v in pairs(ns.defaults) do
                    if not ns.SHARED_KEYS[k] then
                        ns.settings[k] = (type(v) == "table") and ns.DeepCopy(v) or v
                    end
                end
                ns.RebuildBars()
                print("|cffffd100BlitzFramesTargets:|r Current profile reset to defaults.")
            end,
        })
    end)

    -- ============================================================
    -- Right column: Share Profile
    -- ============================================================
    MakeHeader("Share Profile", RIGHT_X, COL_Y)
    local exportBtn = CreateButton(frame, BTN_W, BTN_H, "Export")
    exportBtn:SetPoint("TOPLEFT", RIGHT_X, COL_Y - 44)
    exportBtn:SetScript("OnClick", function()
        local name = ns.db.activeProfile
        local encoded, err = ns.ExportProfile(name)
        if not encoded then
            print("|cffff0000BlitzFramesTargets:|r Export failed: " .. (err or "unknown"))
            return
        end
        GetProfileDialog():Configure("export", encoded, "Export: " .. name)
        GetProfileDialog():Show()
    end)

    local importBtn = CreateButton(frame, BTN_W, BTN_H, "Import")
    importBtn:SetPoint("TOPLEFT", RIGHT_X, COL_Y - 108)
    importBtn:SetScript("OnClick", function()
        GetProfileDialog():Configure("import", "", "Import Profile", function(text)
            local ok, data = ns.ImportProfileString(text)
            if not ok then return false, data end

            local name = data.sourceName or "Imported"
            if ns.db.profiles[name] then
                local base, i = name, 2
                repeat name = base .. " (" .. i .. ")"; i = i + 1
                until not ns.db.profiles[name]
            end

            local target = ns.GetOrCreateProfile(name)
            ns.ApplyImportToProfile(target, data.settings)
            ns.ActivateProfile(name)
            ns.RebuildBars()
            print("|cff00ff00BlitzFramesTargets:|r Profile '" .. name .. "' imported.")
            ReplayAnimation()
            return true
        end)
        GetProfileDialog():Show()
    end)

    -- ============================================================
    -- OnShow sync
    -- ============================================================
    return function()
        RefreshDropdown()
    end
end
