local addonName, ApiVault = ...

ApiVault.XMLTemplateBrowser = ApiVault.XMLTemplateBrowser or {}

local ROW_HEIGHT = 22
local ROW_COUNT = 22
local FILTERS = { "All", "Virtual", "Secure", "Scripted", "Frame", "Button", "CheckButton", "ScrollFrame", "EditBox", "FontString", "Texture" }

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.XMLTemplateBrowser:Create()
	if self.frame then
		return
	end

	local frame = createBackdropFrame("ApiVaultXMLTemplateBrowserFrame", UIParent)
	self.frame = frame
	frame:SetSize(1000, 650)
	frame:SetPoint("CENTER", 60, -60)
	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(840, 500)
		elseif frame.SetMinResize then
			frame:SetMinResize(840, 500)
		end
	end
	setBackdrop(frame)
	if ApiVault.PrepareWindow then
		ApiVault:PrepareWindow(frame, "XMLTemplateBrowser")
	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 - XML Template Catalog")

	local templates, xmlFiles, virtuals, secure = 0, 0, 0, 0
	if ApiVault.XMLCatalog and ApiVault.XMLCatalog.GetStats then
		templates, xmlFiles, virtuals, secure = ApiVault.XMLCatalog:GetStats()
	end
	local meta = createFont(frame, "GameFontDisableSmall")
	meta:SetPoint("TOPLEFT", title, "BOTTOMLEFT", 0, -3)
	meta:SetText("templates " .. tostring(templates) .. " - XML files " .. tostring(xmlFiles) .. " - virtual " .. tostring(virtuals) .. " - secure refs " .. tostring(secure))

	local searchBox = CreateFrame("EditBox", nil, frame, "InputBoxTemplate")
	self.searchBox = searchBox
	searchBox:SetSize(340, 26)
	searchBox:SetPoint("TOPLEFT", frame, "TOPLEFT", 22, -62)
	searchBox:SetAutoFocus(false)
	searchBox:SetText("")
	searchBox:SetScript("OnTextChanged", function()
		ApiVault.XMLTemplateBrowser:RefreshSearch()
	end)
	searchBox:SetScript("OnEnterPressed", function(selfBox)
		selfBox:ClearFocus()
	end)

	local placeholder = createFont(frame, "GameFontDisableSmall")
	placeholder:SetPoint("LEFT", searchBox, "RIGHT", 10, 0)
	placeholder:SetText("Search template, frame, mixin, inherit, file, or module")

	self.filter = "All"
	self.filterButtons = {}
	local prev
	for _, filterName in ipairs(FILTERS) do
		local button = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
		button:SetSize(filterName == "CheckButton" and 96 or filterName == "ScrollFrame" and 96 or filterName == "FontString" and 94 or 78, 22)
		if prev then
			button:SetPoint("LEFT", prev, "RIGHT", 4, 0)
		else
			button:SetPoint("TOPLEFT", searchBox, "BOTTOMLEFT", 0, -8)
		end
		button:SetText(filterName)
		button:SetScript("OnClick", function()
			ApiVault.XMLTemplateBrowser.filter = filterName
			ApiVault.XMLTemplateBrowser:RefreshFilterButtons()
			ApiVault.XMLTemplateBrowser:RefreshSearch()
		end)
		self.filterButtons[filterName] = button
		prev = button
	end

	local listTitle = createFont(frame, "GameFontNormalSmall")
	listTitle:SetPoint("TOPLEFT", frame, "TOPLEFT", 22, -120)
	listTitle:SetText("XML templates / frames")

	local listBg = createBackdropFrame(nil, frame)
	self.listBg = listBg
	listBg:SetPoint("TOPLEFT", frame, "TOPLEFT", 16, -138)
	listBg:SetSize(430, 475)
	setBackdrop(listBg, 0.02, 0.02, 0.03, 0.82)

	local scroll = CreateFrame("ScrollFrame", "ApiVaultXMLTemplateScrollFrame", frame, "FauxScrollFrameTemplate")
	self.scroll = scroll
	scroll:SetPoint("TOPLEFT", listBg, "TOPLEFT", 10, -10)
	scroll:SetPoint("BOTTOMRIGHT", listBg, "BOTTOMRIGHT", -28, 10)
	scroll:SetScript("OnVerticalScroll", function(selfScroll, offset)
		FauxScrollFrame_OnVerticalScroll(selfScroll, offset, ROW_HEIGHT, function()
			ApiVault.XMLTemplateBrowser:RefreshRows()
		end)
	end)

	self.rows = {}
	for index = 1, ROW_COUNT do
		local row = CreateFrame("Button", nil, frame)
		row:SetHeight(ROW_HEIGHT)
		row:SetPoint("TOPLEFT", scroll, "TOPLEFT", 0, -((index - 1) * ROW_HEIGHT))
		row:SetPoint("RIGHT", scroll, "RIGHT", -4, 0)
		row.text = createFont(row, "GameFontHighlightSmall")
		row.text:SetPoint("LEFT", row, "LEFT", 2, 0)
		row.text:SetPoint("RIGHT", row, "RIGHT", -4, 0)
		row.text:SetWordWrap(false)
		row:SetScript("OnClick", function(selfRow)
			ApiVault.XMLTemplateBrowser:SelectEntry(selfRow.entry)
		end)
		self.rows[index] = row
	end

	local detailBg = createBackdropFrame(nil, frame)
	self.detailBg = detailBg
	detailBg:SetPoint("TOPLEFT", listBg, "TOPRIGHT", 14, 0)
	detailBg:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", -16, 38)
	setBackdrop(detailBg, 0.025, 0.025, 0.035, 0.86)

	self.detailTitle = createFont(detailBg, "GameFontHighlightLarge")
	self.detailTitle:SetPoint("TOPLEFT", detailBg, "TOPLEFT", 14, -14)
	self.detailTitle:SetPoint("RIGHT", detailBg, "RIGHT", -14, 0)
	self.detailTitle:SetWordWrap(false)
	self.detailTitle:SetText("Select an XML template")

	self.detailScroll = CreateFrame("ScrollFrame", nil, detailBg, "UIPanelScrollFrameTemplate")
	self.detailScroll:SetPoint("TOPLEFT", self.detailTitle, "BOTTOMLEFT", 0, -12)
	self.detailScroll:SetPoint("BOTTOMRIGHT", detailBg, "BOTTOMRIGHT", -30, 14)
	self.detailBox = CreateFrame("EditBox", nil, self.detailScroll)
	self.detailBox:SetMultiLine(true)
	self.detailBox:SetAutoFocus(false)
	self.detailBox:SetFontObject(ChatFontNormal)
	self.detailBox:SetWidth(500)
	self.detailBox:SetTextInsets(4, 4, 4, 4)
	self.detailBox:SetScript("OnEscapePressed", function(selfBox) selfBox:ClearFocus() end)
	self.detailScroll:SetScrollChild(self.detailBox)

	self:RefreshFilterButtons()
	self:RefreshSearch()
end

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

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

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

function ApiVault.XMLTemplateBrowser: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 prefix = data.v == 1 and "T " or "F "
			local suffix = data.sec == 1 and " |cffff8080secure ref|r" or " |cff888888" .. tostring(data.ty or "?") .. "|r"
			row.text:SetText(prefix .. tostring(entry.display or "?") .. suffix)
		else
			row:Hide()
		end
	end
end

function ApiVault.XMLTemplateBrowser:SelectEntry(entry)
	self.selectedEntry = entry
	if ApiVault.ChecklistExport and ApiVault.ChecklistExport.CaptureContext and entry then
		ApiVault.ChecklistExport:CaptureContext("XML", entry.data or entry, entry.display, entry.kind, entry.module, entry.riskClass)
	end
	if not entry then
		return
	end
	self.detailTitle:SetText(tostring(entry.display or "XML template"))
	local text = ApiVault.XMLCatalog and ApiVault.XMLCatalog.DescribeTemplate and ApiVault.XMLCatalog:DescribeTemplate(entry) or "XML template metadata unavailable."
	if ApiVault.ResourceLinks and ApiVault.ResourceLinks.AppendXMLDetail then
		text = ApiVault.ResourceLinks:AppendXMLDetail(text, entry, 5)
	end
	self.detailBox:SetText(text)
	self.detailBox:SetCursorPosition(0)
end
