local addonName, ApiVault = ...

ApiVault.CatalogBrowser = ApiVault.CatalogBrowser or {}

local ROW_HEIGHT = 22
local ROW_COUNT = 24
local FILTERS = { "All", "Constants", "Slash", "Bindings", "Settings" }

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.CatalogBrowser:Create()
	if self.frame then return end
	local frame = createBackdropFrame("ApiVaultCatalogBrowserFrame", UIParent)
	self.frame = frame
	frame:SetSize(1100, 680)
	frame:SetPoint("CENTER", 180, -90)
	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, "CatalogBrowser") 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 - Constants / Slash / Bindings / Settings Catalog")
	local total, constants, slash, bindings, settings = 0,0,0,0,0
	if ApiVault.Catalogs and ApiVault.Catalogs.GetStats then total, constants, slash, bindings, settings = ApiVault.Catalogs:GetStats() end
	local sub = createFont(frame, "GameFontDisableSmall")
	sub:SetPoint("TOPLEFT", title, "BOTTOMLEFT", 0, -4)
	sub:SetText("entries "..tostring(total).." - constants "..tostring(constants).." - slash "..tostring(slash).." - bindings "..tostring(bindings).." - settings "..tostring(settings).." | metadata-only")

	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 label = createFont(frame, "GameFontDisableSmall")
	label:SetPoint("LEFT", search, "RIGHT", 12, 0)
	label:SetText("Search catalog metadata. Nothing is executed.")

	local last
	self.filterButtons = {}
	for _, filter in ipairs(FILTERS) do
		local button = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
		button:SetSize(88, 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)
		self.filterButtons[filter] = button
		last = button
	end

	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 catalog entry.")
	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:SetScript("OnClick", function(button)
			self.selected = button.entry
			if ApiVault.Catalogs and ApiVault.Catalogs.Describe then self.detail:SetText(ApiVault.Catalogs:Describe(button.entry)) end
		end)
		self.rows[i] = row
	end
	self.filter = "All"
	self:Refresh()
end

function ApiVault.CatalogBrowser:Open(filter)
	self:Create()
	if filter then self.filter = filter end
	if ApiVault.RaiseWindow then ApiVault:RaiseWindow(self.frame) end
	self.frame:Show()
	self:Refresh()
end

function ApiVault.CatalogBrowser: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.Catalogs and ApiVault.Catalogs.Search then self.results = ApiVault.Catalogs: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.CatalogBrowser:Toggle()
	self:Create()
	if self.frame:IsShown() then self.frame:Hide() else self:Open(self.filter or "All") end
end
