-- ApiVault TODO Completion / Developer Actions panel. Added in v0.5.4.
-- Quick access to remaining v0.3-v0.5 polish workflows: favorite, navigate, export and test checklist.
local addonName, ApiVault = ...

ApiVault.TodoCompletionPanel = ApiVault.TodoCompletionPanel or {}
local Panel = ApiVault.TodoCompletionPanel

local function createFont(parent, template, justify)
    local font = parent:CreateFontString(nil, "OVERLAY", template or "GameFontNormal")
    font:SetJustifyH(justify or "LEFT")
    return font
end

local function setBackdrop(frame, r, g, b, a)
    if not frame.SetBackdrop then return end
    frame:SetBackdrop({
        bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background",
        edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Border",
        tile = true, tileSize = 32, edgeSize = 32,
        insets = { left = 8, right = 8, top = 8, bottom = 8 },
    })
    frame:SetBackdropColor(r or 0.04, g or 0.04, b or 0.06, a or 0.96)
end

local function createBackdropFrame(name, parent)
    return CreateFrame("Frame", name, parent, BackdropTemplateMixin and "BackdropTemplate" or nil)
end

local function setOutput(text)
    if Panel.outputBox then
        Panel.outputBox:SetText(tostring(text or ""))
        Panel.outputBox:SetCursorPosition(0)
    else
        ApiVault:Print(tostring(text or ""))
    end
end

function Panel:Create()
    if self.frame then return end
    local frame = createBackdropFrame("ApiVaultTodoCompletionPanelFrame", UIParent)
    self.frame = frame
    frame:SetSize(900, 620)
    frame:SetPoint("CENTER", 120, -70)
    frame:SetFrameStrata("FULLSCREEN_DIALOG")
    frame:SetMovable(true)
    frame:EnableMouse(true)
    frame:RegisterForDrag("LeftButton")
    frame:SetScript("OnDragStart", frame.StartMoving)
    frame:SetScript("OnDragStop", frame.StopMovingOrSizing)
    if frame.SetResizable then
        frame:SetResizable(true)
        if frame.SetResizeBounds then frame:SetResizeBounds(760, 500)
        elseif frame.SetMinResize then frame:SetMinResize(760, 500) end
    end
    setBackdrop(frame)
    if ApiVault.PrepareWindow then ApiVault:PrepareWindow(frame, "TodoCompletionPanel") end
    frame:Hide()

    local close = CreateFrame("Button", nil, frame, "UIPanelCloseButton")
    close:SetPoint("TOPRIGHT", -6, -6)

    local title = createFont(frame, "GameFontHighlightLarge")
    title:SetPoint("TOPLEFT", 18, -16)
    title:SetText("ApiVault - Developer Actions / TODO Completion")

    self.subText = createFont(frame, "GameFontDisableSmall")
    self.subText:SetPoint("TOPLEFT", title, "BOTTOMLEFT", 0, -4)
    self.subText:SetPoint("RIGHT", frame, "RIGHT", -24, 0)
    self.subText:SetText("Quick filters, favorites, cross-link navigation, quick-copy summaries and test checklists. Metadata-only.")

    local buttonNames = {
        { "Summary", function() setOutput(ApiVault.TodoCompletion:BuildQuickSummary()) end },
        { "Audit Note", function() setOutput(ApiVault.TodoCompletion:BuildQuickAuditNote()) end },
        { "Checklist", function() setOutput(ApiVault.TodoCompletion:BuildTestChecklist()) end },
        { "Favorite", function()
            local added, key = ApiVault.TodoCompletion:ToggleFavorite()
            setOutput((added and "Added favorite: " or "Removed favorite: ") .. tostring(key))
            if ApiVault.FavoritesRecentPanel and ApiVault.FavoritesRecentPanel.Refresh then ApiVault.FavoritesRecentPanel:Refresh() end
        end },
        { "Open Related", function()
            local ok, msg = ApiVault.TodoCompletion:OpenRelated()
            setOutput(tostring(ok and "OK: " or "NOTICE: ") .. tostring(msg))
        end },
        { "Export", function()
            if ApiVault.ExportPanel and ApiVault.ExportPanel.OpenWithContext then
                ApiVault.ExportPanel:OpenWithContext(ApiVault.TodoCompletion:GetCurrentContext(), "audit-note")
                setOutput("Export panel opened with current context.")
            else
                setOutput("Export panel unavailable.")
            end
        end },
        { "Compact", function()
            local nowCompact = not ApiVault.TodoCompletion:IsCompactMode()
            ApiVault.TodoCompletion:SetCompactMode(nowCompact)
            setOutput("Compact mode setting: " .. tostring(nowCompact) .. "\nReload/open panels to apply where supported.")
        end },
    }

    local prev
    for index, item in ipairs(buttonNames) do
        local button = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
        button:SetSize(index == 5 and 108 or 92, 23)
        if prev then button:SetPoint("LEFT", prev, "RIGHT", 6, 0)
        else button:SetPoint("TOPLEFT", frame, "TOPLEFT", 18, -68) end
        button:SetText(item[1])
        button:SetScript("OnClick", item[2])
        prev = button
    end

    local filters = createFont(frame, "GameFontNormalSmall")
    filters:SetPoint("TOPLEFT", frame, "TOPLEFT", 22, -104)
    filters:SetText("Advanced search filters now available: HasUsage, HasExamples, HasSecure, Safe, Review, Protected, Metadata, SourceBacked, InspectOnly")

    local outputPanel = createBackdropFrame(nil, frame)
    outputPanel:SetPoint("TOPLEFT", filters, "BOTTOMLEFT", -6, -14)
    outputPanel:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", -18, 20)
    setBackdrop(outputPanel, 0.015, 0.015, 0.02, 0.84)

    local scroll = CreateFrame("ScrollFrame", nil, outputPanel, "UIPanelScrollFrameTemplate")
    scroll:SetPoint("TOPLEFT", outputPanel, "TOPLEFT", 8, -8)
    scroll:SetPoint("BOTTOMRIGHT", outputPanel, "BOTTOMRIGHT", -30, 8)
    local box = CreateFrame("EditBox", nil, scroll)
    self.outputBox = box
    box:SetMultiLine(true)
    box:SetAutoFocus(false)
    box:SetFontObject(ChatFontNormal)
    box:SetWidth(820)
    box:SetTextInsets(4,4,4,4)
    box:SetScript("OnEscapePressed", function(selfBox) selfBox:ClearFocus() end)
    scroll:SetScrollChild(box)
    frame:HookScript("OnSizeChanged", function()
        if scroll.GetWidth then
            local width = scroll:GetWidth()
            if width and width > 80 then box:SetWidth(width - 18) end
        end
    end)
end

function Panel:Refresh()
    self:Create()
    local context = ApiVault.TodoCompletion and ApiVault.TodoCompletion:GetCurrentContext() or nil
    if self.subText then
        self.subText:SetText("Current context: " .. tostring(context and (context.display or context.name) or "none") .. " - metadata-only; no runtime file reads; no protected/secure execution")
    end
    if not context then
        setOutput("No current context selected. Select an item in API Browser, Global Search, Source Examples, Secure Patterns, Symbols, Modules or Resources first.")
    end
end

function Panel:Toggle()
    self:Create()
    if self.frame:IsShown() then self.frame:Hide() else self.frame:Show(); if ApiVault.RaiseWindow then ApiVault:RaiseWindow(self.frame) end; self:Refresh() end
end
