local addonName, SinsToolkit = ...

SinsToolkit.UI = SinsToolkit.UI or {}
SinsToolkit.UI.Pages = SinsToolkit.UI.Pages or {}

local PageBase = SinsToolkit.UI.Pages.Base or {}
local Helpers = SinsToolkit.UI.Pages.Helpers or {}
local Page = {}
setmetatable(Page, { __index = PageBase })
SinsToolkit.UI.Pages.FrameInspector = Page
Page.density = Helpers.GetDefaultDensity and Helpers.GetDefaultDensity() or "compact"

function Page:Create(CreateScrollablePage, Window, CreateWrappedText, SetFlatBackdrop)
    local Theme = Helpers.GetTheme and Helpers.GetTheme()
    local frameInspectorPage, content = CreateScrollablePage("Frame Inspector")
    Helpers.CreatePageIntro(content, Window, "Frame Inspector", "Use the Toolkit Hover Inspector for quick live identification, or open Blizzard's built-in /fstack for deeper frame stack debugging.", CreateWrappedText, 680)

    local function WithFrameInspector(action)
        local inspector = SinsToolkit.DevTools and SinsToolkit.DevTools.FrameInspector
        if inspector and action then action(inspector) end
        if frameInspectorPage.OnShowCallback then frameInspectorPage.OnShowCallback() end
    end

    local flowCard = Helpers.CreatePageCard(content, "Toolkit Hover Inspector", 666, 214)
    flowCard:SetPoint("TOPLEFT", content, "TOPLEFT", 0, -92)
    Helpers.SetCardDescription(flowCard, "Step 1: Start the hover inspector. Step 2: Hover the UI. Step 3: Copy the report.")

    local stepRows = Helpers.CreatePropertyRows(flowCard, {
        { label = "Step 1", value = "Start Hover Inspector" },
        { label = "Step 2", value = "Hover a visible UI frame" },
        { label = "Step 3", value = "Press the copy key or Copy Current" },
    }, { x = 16, y = -70, labelWidth = 66, valueWidth = 320, rowHeight = 18 })

    local buttons = Helpers.CreateButtonRow(Window, flowCard, {
        { text = "Start Hover Inspector", width = 170, height = 26, onClick = function()
            WithFrameInspector(function(inspector) inspector:StartHoverInspector() end)
        end, tooltip = "Hide the Toolkit window and inspect frames as you move your cursor." },
        { text = "Stop Hover Inspector", width = 160, height = 26, onClick = function()
            WithFrameInspector(function(inspector) inspector:StopHoverInspector(false) end)
        end, tooltip = "Stop the hover overlay." },
        { text = "Copy Current", width = 130, height = 26, onClick = function()
            WithFrameInspector(function(inspector) inspector:CopyCurrent() end)
        end, tooltip = "Open a copyable popup for the current hovered frame report." },
    }, 16, -132, 10)
    local startHover, stopHover, copyCurrent = buttons[1], buttons[2], buttons[3]

    local copyKeyBox = CreateFrame("Frame", nil, flowCard, "BackdropTemplate")
    copyKeyBox:SetSize(210, 44)
    copyKeyBox:SetPoint("BOTTOMLEFT", flowCard, "BOTTOMLEFT", 16, 14)
    Helpers.ApplyListBackdrop(copyKeyBox, 0.015, 0.014, 0.020, 0.80, 0.18, 0.12, 0.25, 0.60)

    local copyKeyLabel = copyKeyBox:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
    copyKeyLabel:SetPoint("LEFT", copyKeyBox, "LEFT", 12, 0)
    copyKeyLabel:SetWidth(186)
    copyKeyLabel:SetJustifyH("LEFT")
    copyKeyLabel:SetText("Current Copy Key: Not Assigned")
    if Theme and Theme.ApplyStatusText then Theme.ApplyStatusText(copyKeyLabel) end

    local keyButtons = Helpers.CreateButtonRow(Window, flowCard, {
        { text = "Set Copy Key", width = 120, height = 24, onClick = function()
            WithFrameInspector(function(inspector)
                inspector:BeginCopyKeyCapture(function()
                    if frameInspectorPage.OnShowCallback then frameInspectorPage.OnShowCallback() end
                end)
            end)
        end, tooltip = "Capture the next key press and bind it to Copy Current." },
        { text = "Clear Copy Key", width = 120, height = 24, onClick = function()
            WithFrameInspector(function(inspector) inspector:ClearCopyKey() end)
        end, tooltip = "Remove the Frame Inspector copy key binding." },
    }, 242, -172, 10)

    local selectionCard = Helpers.ClearCardBody(Helpers.CreatePageCard(content, "Current Selection", 666, 278))
    selectionCard:SetPoint("TOPLEFT", flowCard, "BOTTOMLEFT", 0, -12)

    local fiSummary = selectionCard:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
    fiSummary:SetPoint("TOPLEFT", selectionCard, "TOPLEFT", 16, -42)
    fiSummary:SetPoint("RIGHT", selectionCard, "RIGHT", -16, 0)
    fiSummary:SetJustifyH("LEFT")
    fiSummary:SetJustifyV("TOP")
    fiSummary:SetText("No frame selected. Click Start Hover Inspector, hover a UI element, then reopen /stk to review or copy the current report.")
    if Theme and Theme.ApplyStatusText then Theme.ApplyStatusText(fiSummary) end

    local advancedCard = Helpers.CreatePageCard(content, "Advanced", 666, 116)
    advancedCard:SetPoint("TOPLEFT", selectionCard, "BOTTOMLEFT", 0, -12)
    Helpers.SetCardDescription(advancedCard, "Blizzard's built-in /fstack remains available for advanced frame stack inspection. You can also type /fstack directly.")

    local openFStack = Window:CreateButton(advancedCard, "Open Blizzard /fstack", 180, 26, function()
        WithFrameInspector(function(inspector) inspector:OpenFrameStack() end)
    end, "Open Blizzard's separate Frame Stack overlay.")
    openFStack:SetPoint("BOTTOMLEFT", advancedCard, "BOTTOMLEFT", 16, 14)

    local function SetButtonEnabled(button, enabled)
        if enabled then
            button:Enable()
        else
            button:Disable()
        end
    end

    local function RefreshFrameInspectorPage()
        local inspector = SinsToolkit.DevTools and SinsToolkit.DevTools.FrameInspector
        if not inspector then
            fiSummary:SetText("Frame Inspector is not loaded.")
            return
        end

        local rows, report, name = inspector:Refresh()
        local selected = inspector:GetSelection()
        SetButtonEnabled(startHover, not inspector:IsHoverInspecting())
        SetButtonEnabled(stopHover, inspector:IsHoverInspecting())
        copyKeyLabel:SetText("Current Copy Key: " .. (inspector:GetCopyKeyText() or "Not Assigned"))
        if not selected or not rows or #rows == 0 then
            fiSummary:SetText("No frame selected. Click Start Hover Inspector, hover a UI element, then reopen /stk to review or copy the current report.")
            return report
        end

        local lines = {
            "Selected: |cffd8a84a" .. (name or "(anonymous)") .. "|r",
            inspector:IsHoverInspecting() and "Mode: Hover Inspector active" or "Mode: Last inspected frame",
            "",
        }
        for i, row in ipairs(rows) do
            if i > 10 then
                lines[#lines + 1] = "...additional details are included in Copy Current."
                break
            end
            lines[#lines + 1] = row.label .. ": " .. row.value
        end
        fiSummary:SetText(table.concat(lines, "\n"))
        return report
    end

    frameInspectorPage.OnShowCallback = function()
        RefreshFrameInspectorPage()
    end
    frameInspectorPage:SetScript("OnHide", function()
        local inspector = SinsToolkit.DevTools and SinsToolkit.DevTools.FrameInspector
        if inspector then inspector:ClearHighlight() end
    end)
    content:SetHeight(750)

    self.frame = frameInspectorPage
    return frameInspectorPage
end

Page:Register("Frame Inspector")

return Page
