local addonName, ApiVault = ...

ApiVault.SecurePatternBrowser = ApiVault.SecurePatternBrowser or {}

local ROW_HEIGHT = 22
local ROW_COUNT = 22
local FILTERS = { "All", "Protected", "SecureSensitive", "Combat", "Metadata", "Templates", "API", "TOC", "Hooks" }

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

function ApiVault.SecurePatternBrowser:Create()
	if self.frame then
		return
	end

	local frame = createBackdropFrame("ApiVaultSecurePatternBrowserFrame", UIParent)
	self.frame = frame
	frame:SetSize(1080, 660)
	frame:SetPoint("CENTER", 140, -140)
	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(880, 520)
		elseif frame.SetMinResize then
			frame:SetMinResize(880, 520)
		end
	end
	setBackdrop(frame)
	if ApiVault.PrepareWindow then
		ApiVault:PrepareWindow(frame, "SecurePatternBrowser")
	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 - Secure Pattern Reference")

	local total, protectedCount, secureSensitive, combatSensitive, metadataOnly = 0, 0, 0, 0, 0
	if ApiVault.SecurePatterns and ApiVault.SecurePatterns.GetStats then
		total, protectedCount, secureSensitive, combatSensitive, metadataOnly = ApiVault.SecurePatterns:GetStats()
	end
	local sub = createFont(frame, "GameFontDisableSmall")
	sub:SetPoint("TOPLEFT", title, "BOTTOMLEFT", 0, -4)
	sub:SetText("Inspect-only metadata. No protected/secure execution. Patterns: " .. tostring(total) .. " / protected " .. tostring(protectedCount) .. " / secure " .. tostring(secureSensitive) .. " / combat " .. tostring(combatSensitive))

	local search = CreateFrame("EditBox", nil, frame, "InputBoxTemplate")
	self.searchBox = search
	search:SetSize(330, 24)
	search:SetPoint("TOPLEFT", 18, -60)
	search:SetAutoFocus(false)
	search:SetScript("OnEnterPressed", function(box)
		box:ClearFocus()
		self:RefreshSearch()
	end)
	search:SetScript("OnTextChanged", function()
		self:RefreshSearch()
	end)

	local clear = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
	clear:SetSize(60, 24)
	clear:SetPoint("LEFT", search, "RIGHT", 8, 0)
	clear:SetText("Clear")
	clear:SetScript("OnClick", function()
		search:SetText("")
		self:RefreshSearch()
	end)

	self.filter = "All"
	self.filterButtons = {}
	local prev = clear
	for _, name in ipairs(FILTERS) do
		local button = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
		button:SetSize(name == "SecureSensitive" and 116 or 82, 22)
		button:SetPoint("LEFT", prev, "RIGHT", 5, 0)
		button:SetText(name)
		button:SetScript("OnClick", function()
			self.filter = name
			self:RefreshFilterButtons()
			self:RefreshSearch()
		end)
		self.filterButtons[name] = button
		prev = button
	end

	self.rows = {}
	for index = 1, ROW_COUNT do
		local row = CreateFrame("Button", nil, frame)
		row:SetSize(500, ROW_HEIGHT)
		if index == 1 then
			row:SetPoint("TOPLEFT", 20, -96)
		else
			row:SetPoint("TOPLEFT", self.rows[index - 1], "BOTTOMLEFT", 0, 0)
		end
		row.text = createFont(row, "GameFontNormalSmall")
		row.text:SetPoint("LEFT", 3, 0)
		row.text:SetPoint("RIGHT", -3, 0)
		row:SetScript("OnClick", function(button)
			self:SelectEntry(button.entry)
		end)
		self.rows[index] = row
	end

	self.scroll = CreateFrame("ScrollFrame", "ApiVaultSecurePatternBrowserScrollFrame", frame, "FauxScrollFrameTemplate")
	self.scroll:SetPoint("TOPLEFT", self.rows[1], "TOPLEFT", 0, 0)
	self.scroll:SetPoint("BOTTOMRIGHT", self.rows[ROW_COUNT], "BOTTOMRIGHT", 28, 0)
	self.scroll:SetScript("OnVerticalScroll", function(_, offset)
		FauxScrollFrame_OnVerticalScroll(self.scroll, offset, ROW_HEIGHT, function()
			self:RefreshRows()
		end)
	end)

	self.detailTitle = createFont(frame, "GameFontHighlight")
	self.detailTitle:SetPoint("TOPLEFT", 565, -96)
	self.detailTitle:SetText("Select a secure pattern")

	self.detailScroll = CreateFrame("ScrollFrame", nil, frame, "UIPanelScrollFrameTemplate")
	self.detailScroll:SetPoint("TOPLEFT", self.detailTitle, "BOTTOMLEFT", 0, -8)
	self.detailScroll:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", -34, 24)

	self.detailBox = CreateFrame("EditBox", nil, self.detailScroll)
	self.detailBox:SetMultiLine(true)
	self.detailBox:SetAutoFocus(false)
	self.detailBox:SetFontObject("GameFontHighlightSmall")
	self.detailBox:SetWidth(455)
	self.detailBox:SetText("Select a secure pattern.")
	self.detailBox:SetScript("OnEscapePressed", function(selfBox) selfBox:ClearFocus() end)
	self.detailScroll:SetScrollChild(self.detailBox)

	self:RefreshFilterButtons()
	self:RefreshSearch()
end

function ApiVault.SecurePatternBrowser:Toggle()
	self:Create()
	if self.frame:IsShown() then
		self.frame:Hide()
	else
		self.frame:Show()
		self.searchBox:SetFocus()
	end
end

function ApiVault.SecurePatternBrowser:RefreshFilterButtons()
	for name, button in pairs(self.filterButtons or {}) do
		button:SetEnabled(name ~= self.filter)
	end
end

function ApiVault.SecurePatternBrowser:RefreshSearch()
	if not self.frame then
		return
	end
	if not ApiVault.SecurePatterns or not ApiVault.SecurePatterns.Search then
		self.results = {}
	else
		local query = self.searchBox and self.searchBox:GetText() or ""
		self.results = ApiVault.SecurePatterns:Search(query, self.filter or "All", 300)
	end
	self:RefreshRows()
end

function ApiVault.SecurePatternBrowser:RefreshRows()
	local results = self.results or {}
	local offset = FauxScrollFrame_GetOffset(self.scroll)
	FauxScrollFrame_Update(self.scroll, #results, ROW_COUNT, ROW_HEIGHT)
	for index = 1, ROW_COUNT do
		local resultIndex = offset + index
		local row = self.rows[index]
		local entry = results[resultIndex]
		row.entry = entry
		if entry then
			row:Show()
			local data = entry.data or {}
			local policy = data.autoRunPolicy or "inspect-only"
			local badge = policy == "blocked" and "BLOCKED" or "INSPECT"
			local flags = " |cff888888" .. tostring(data.riskClass or "?") .. " / " .. tostring(policy) .. " / " .. badge .. "|r"
			row.text:SetText(tostring(entry.display or "?") .. flags)
		else
			row:Hide()
		end
	end
end

function ApiVault.SecurePatternBrowser:SelectEntry(entry)
	self.selectedEntry = entry
	if ApiVault.ChecklistExport and ApiVault.ChecklistExport.CaptureContext and entry then
		ApiVault.ChecklistExport:CaptureContext("Secure", entry.data or entry, entry.display, entry.kind, entry.module, entry.riskClass)
	end
	if not entry then
		return
	end
	local data = entry.data or {}
	self.detailTitle:SetText(tostring(data.patternName or entry.display or "Secure pattern") .. " | " .. tostring(data.autoRunPolicy or "inspect-only"))
	local text = ApiVault.SecurePatterns and ApiVault.SecurePatterns.DescribePattern and ApiVault.SecurePatterns:DescribePattern(entry) or "Secure pattern metadata unavailable."
	self.detailBox:SetText(text)
	self.detailBox:SetCursorPosition(0)
end
