local addonName, ApiVault = ...

ApiVault.SymbolBrowser = ApiVault.SymbolBrowser or {}

local ROW_HEIGHT = 22
local ROW_COUNT = 24
local FILTERS = { "All", "DocumentedAPI", "Global", "Local", "TableFunction", "Method", "Mixin", "XMLScript", "Slash" }

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

	local frame = createBackdropFrame("ApiVaultSymbolBrowserFrame", UIParent)
	self.frame = frame
	frame:SetSize(1100, 680)
	frame:SetPoint("CENTER", 160, -80)
	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(900, 540)
		elseif frame.SetMinResize then
			frame:SetMinResize(900, 540)
		end
	end
	setBackdrop(frame)
	if ApiVault.PrepareWindow then ApiVault:PrepareWindow(frame, "SymbolBrowser") 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 - Function & Symbol Browser")

	local total, documented, mixins, xmlScripts, slash = 0, 0, 0, 0, 0
	if ApiVault.Symbols and ApiVault.Symbols.GetStats then
		total, documented, mixins, xmlScripts, slash = ApiVault.Symbols:GetStats()
	end
	local sub = createFont(frame, "GameFontDisableSmall")
	sub:SetPoint("TOPLEFT", title, "BOTTOMLEFT", 0, -4)
	sub:SetPoint("RIGHT", frame, "RIGHT", -28, 0)
	sub:SetText("symbols " .. tostring(total) .. " - documented APIs " .. tostring(documented) .. " - mixins " .. tostring(mixins) .. " - XML scripts " .. tostring(xmlScripts) .. " - slash " .. tostring(slash))

	local search = CreateFrame("EditBox", nil, frame, "InputBoxTemplate")
	self.search = search
	search:SetSize(360, 24)
	search:SetPoint("TOPLEFT", frame, "TOPLEFT", 18, -72)
	search:SetAutoFocus(false)
	search:SetScript("OnTextChanged", function() self:Refresh() end)

	local searchLabel = createFont(frame, "GameFontDisableSmall")
	searchLabel:SetPoint("LEFT", search, "RIGHT", 12, 0)
	searchLabel:SetText("Search symbols, owner tables, modules, source paths")

	local buttons = {}
	local last = nil
	for _, filter in ipairs(FILTERS) do
		local button = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
		button:SetSize(filter == "TableFunction" and 104 or 86, 22)
		if last then
			button:SetPoint("LEFT", last, "RIGHT", 6, 0)
		else
			button:SetPoint("TOPLEFT", search, "BOTTOMLEFT", 0, -12)
		end
		button:SetText(filter)
		button:SetScript("OnClick", function()
			self.filter = filter
			self:Refresh()
		end)
		buttons[filter] = button
		last = button
	end
	self.filterButtons = buttons

	local listFrame = createBackdropFrame(nil, frame)
	self.listFrame = listFrame
	listFrame:SetPoint("TOPLEFT", frame, "TOPLEFT", 18, -136)
	listFrame:SetPoint("BOTTOMLEFT", frame, "BOTTOMLEFT", 18, 28)
	listFrame:SetWidth(430)
	setBackdrop(listFrame, 0.02, 0.02, 0.03, 0.72)

	local detail = CreateFrame("EditBox", nil, frame)
	self.detail = detail
	detail:SetMultiLine(true)
	detail:SetAutoFocus(false)
	detail:SetFontObject(ChatFontNormal)
	detail:SetPoint("TOPLEFT", listFrame, "TOPRIGHT", 20, -6)
	detail:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", -28, 32)
	detail:SetText("Select a symbol.")
	detail:EnableMouse(true)

	self.rows = {}
	for i = 1, ROW_COUNT do
		local row = CreateFrame("Button", nil, listFrame)
		row:SetHeight(ROW_HEIGHT)
		row:SetPoint("LEFT", listFrame, "LEFT", 12, 0)
		row:SetPoint("RIGHT", listFrame, "RIGHT", -12, 0)
		if i == 1 then
			row:SetPoint("TOP", listFrame, "TOP", 0, -12)
		else
			row:SetPoint("TOP", self.rows[i - 1], "BOTTOM", 0, 0)
		end
		row.text = createFont(row, "GameFontNormalSmall")
		row.text:SetPoint("LEFT")
		row.text:SetPoint("RIGHT")
		row.text:SetText("")
		row:SetScript("OnClick", function(button)
			self.selected = button.entry
			if ApiVault.Symbols and ApiVault.Symbols.DescribeSymbol then
				self.detail:SetText(ApiVault.Symbols:DescribeSymbol(button.entry))
			end
		end)
		self.rows[i] = row
	end

	self.filter = "All"
	self:Refresh()
end

function ApiVault.SymbolBrowser:Refresh()
	if not self.frame then return end
	local query = self.search and self.search:GetText() or ""
	local filter = self.filter or "All"
	self.results = {}
	if ApiVault.Symbols and ApiVault.Symbols.Search then
		self.results = ApiVault.Symbols:Search(query, filter, ROW_COUNT) or {}
	end
	for i, row in ipairs(self.rows or {}) do
		local entry = self.results[i]
		row.entry = entry
		if entry then
			row.text:SetText(tostring(entry.display or "?"))
			row:Show()
		else
			row.text:SetText("")
			row:Hide()
		end
	end
end

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