local addonName, ApiVault = ...

ApiVault.SourceExampleBrowser = ApiVault.SourceExampleBrowser or {}

local ROW_HEIGHT = 22
local ROW_COUNT = 22
local FILTERS = { "All", "API", "Event", "SafeRef", "Review" }

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

	local frame = createBackdropFrame("ApiVaultSourceExampleBrowserFrame", UIParent)
	self.frame = frame
	frame:SetSize(1040, 650)
	frame:SetPoint("CENTER", 120, -120)
	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(860, 500)
		elseif frame.SetMinResize then
			frame:SetMinResize(860, 500)
		end
	end
	setBackdrop(frame)
	if ApiVault.PrepareWindow then
		ApiVault:PrepareWindow(frame, "SourceExampleBrowser")
	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 - Source Example Browser")

	local total, apiExamples, eventExamples = 0, 0, 0
	if ApiVault.SourceExamples and ApiVault.SourceExamples.GetStats then
		total, apiExamples, eventExamples = ApiVault.SourceExamples:GetStats()
	end
	local meta = createFont(frame, "GameFontDisableSmall")
	meta:SetPoint("TOPLEFT", title, "BOTTOMLEFT", 0, -3)
	meta:SetText("examples " .. tostring(total) .. " - APIs " .. tostring(apiExamples) .. " - events " .. tostring(eventExamples) .. " - generated snippets only")

	local searchBox = CreateFrame("EditBox", nil, frame, "InputBoxTemplate")
	self.searchBox = searchBox
	searchBox:SetSize(360, 26)
	searchBox:SetPoint("TOPLEFT", frame, "TOPLEFT", 22, -62)
	searchBox:SetAutoFocus(false)
	searchBox:SetText("")
	searchBox:SetScript("OnTextChanged", function()
		ApiVault.SourceExampleBrowser: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 API, event, module, context, or path")

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

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

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

	local scroll = CreateFrame("ScrollFrame", "ApiVaultSourceExampleBrowserScrollFrame", 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.SourceExampleBrowser: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.SourceExampleBrowser: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 source example")

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

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

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

function ApiVault.SourceExampleBrowser: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.riskClass == "safe-reference-only" and "generated" or "inspect-only"
			local flags = " |cff888888" .. tostring(data.riskClass or "?") .. " / " .. policy .. "|r"
			row.text:SetText(tostring(entry.display or "?") .. flags)
		else
			row:Hide()
		end
	end
end

function ApiVault.SourceExampleBrowser:SelectEntry(entry)
	self.selectedEntry = entry
	if ApiVault.ChecklistExport and ApiVault.ChecklistExport.CaptureContext and entry then
		ApiVault.ChecklistExport:CaptureContext("Example", 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.ownerName or entry.display or "Source example") .. " | " .. tostring(data.riskClass or "inspect-only"))
	local text = ApiVault.SourceExamples and ApiVault.SourceExamples.DescribeExample and ApiVault.SourceExamples:DescribeExample(entry) or "Source example metadata unavailable."
	self.detailBox:SetText(text)
	self.detailBox:SetCursorPosition(0)
end
