local addonName, ApiVault = ...

ApiVault.InterfaceBrowser = ApiVault.InterfaceBrowser or {}

local ROW_HEIGHT = 22
local ROW_COUNT = 22
local FILTERS = { "All", "lua", "xml", "toc", "Folder", "Module" }

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

	local frame = createBackdropFrame("ApiVaultInterfaceBrowserFrame", UIParent)
	self.frame = frame
	frame:SetSize(1000, 650)
	frame:SetPoint("CENTER", 30, -30)
	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(820, 500)
		elseif frame.SetMinResize then
			frame:SetMinResize(820, 500)
		end
	end
	setBackdrop(frame)
	if ApiVault.PrepareWindow then
		ApiVault:PrepareWindow(frame, "InterfaceBrowser")
	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 - Interface Resource Browser")

	local files, folders, modules = 0, 0, 0
	if ApiVault.InterfaceResources and ApiVault.InterfaceResources.GetStats then
		files, folders, modules = ApiVault.InterfaceResources:GetStats()
	end
	local meta = createFont(frame, "GameFontDisableSmall")
	meta:SetPoint("TOPLEFT", title, "BOTTOMLEFT", 0, -3)
	meta:SetText("root " .. tostring(ApiVault.InterfaceResources and ApiVault.InterfaceResources.GetRoot and ApiVault.InterfaceResources:GetRoot() or "Interface/AddOns/ApiVault/Examples/Interface") .. " - files " .. tostring(files) .. " - folders " .. tostring(folders) .. " - modules " .. tostring(modules))

	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.InterfaceBrowser: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 file, folder, module, or extension")

	self.filter = "All"
	self.filterButtons = {}
	local prev
	for _, filterName in ipairs(FILTERS) do
		local button = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
		button:SetSize(filterName == "Folder" and 84 or 70, 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.InterfaceBrowser.filter = filterName
			ApiVault.InterfaceBrowser:RefreshFilterButtons()
			ApiVault.InterfaceBrowser:RefreshSearch()
		end)
		self.filterButtons[filterName] = button
		prev = button
	end

	local listTitle = createFont(frame, "GameFontNormalSmall")
	listTitle:SetPoint("TOPLEFT", frame, "TOPLEFT", 22, -120)
	listTitle:SetText("Interface resources")

	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", "ApiVaultInterfaceResourceScrollFrame", 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.InterfaceBrowser: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.InterfaceBrowser: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 a resource")

	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.InterfaceBrowser:Toggle()
	self:Create()
	if self.frame:IsShown() then
		self.frame:Hide()
	else
		self.frame:Show()
		self.searchBox:SetFocus()
	end
end

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

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

function ApiVault.InterfaceBrowser: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 prefix = entry.kind == "File" and "F " or entry.kind == "Folder" and "D " or "M "
			row.text:SetText(prefix .. tostring(entry.display or "?"))
		else
			row:Hide()
		end
	end
end

function ApiVault.InterfaceBrowser:SelectEntry(entry)
	self.selectedEntry = entry
	if ApiVault.ChecklistExport and ApiVault.ChecklistExport.CaptureContext and entry then
		ApiVault.ChecklistExport:CaptureContext("Resource", 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 entry.kind or "Resource"))
	local text = ApiVault.InterfaceResources and ApiVault.InterfaceResources.DescribeEntry and ApiVault.InterfaceResources:DescribeEntry(entry) or "Interface resource metadata unavailable."
	if ApiVault.ResourceLinks and ApiVault.ResourceLinks.AppendResourceDetail then
		text = ApiVault.ResourceLinks:AppendResourceDetail(text, entry, 5)
	end
	self.detailBox:SetText(text)
	self.detailBox:SetCursorPosition(0)
end
