-- ApiVault Bug Advisor Bridge UI. Added in v1.1.4.
local addonName, ApiVault = ...

ApiVault.BugAdvisorPanel = ApiVault.BugAdvisorPanel or {}
local Panel = ApiVault.BugAdvisorPanel

local function createBackdropFrame(name, parent)
	return CreateFrame("Frame", name, parent, BackdropTemplateMixin and "BackdropTemplate" or nil)
end

local function setBackdrop(frame)
	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(0.04, 0.04, 0.06, 0.96)
end

local function createText(parent, template)
	local fs = parent:CreateFontString(nil, "OVERLAY", template or "GameFontNormal")
	fs:SetJustifyH("LEFT")
	return fs
end

function Panel:Create()
	if self.frame then return end

	local frame = createBackdropFrame("ApiVaultBugAdvisorPanel", UIParent)
	self.frame = frame
	frame:SetSize(1000, 660)
	frame:SetPoint("CENTER", 0, 0)
	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, 560) elseif frame.SetMinResize then frame:SetMinResize(860, 560) end
	end
	setBackdrop(frame)
	if ApiVault.PrepareWindow then ApiVault:PrepareWindow(frame, "BugAdvisor") end
	frame:Hide()

	local close = CreateFrame("Button", nil, frame, "UIPanelCloseButton")
	close:SetPoint("TOPRIGHT", -6, -6)

	local title = createText(frame, "GameFontHighlightLarge")
	title:SetPoint("TOPLEFT", 18, -18)
	title:SetText("ApiVault - Bug Advisor / External Error Bridge")

	local note = createText(frame, "GameFontDisableSmall")
	note:SetPoint("TOPLEFT", title, "BOTTOMLEFT", 0, -4)
	note:SetText("Generic data-only error ingestion. No BugGrabber internals assumed unless records are supplied.")

	local search = CreateFrame("EditBox", nil, frame, "InputBoxTemplate")
	self.searchBox = search
	search:SetSize(250, 24)
	search:SetPoint("TOPLEFT", 18, -66)
	search:SetAutoFocus(false)
	search:SetScript("OnEnterPressed", function(box) box:ClearFocus(); Panel:RefreshList() end)

	local refresh = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
	refresh:SetSize(80, 22)
	refresh:SetPoint("LEFT", search, "RIGHT", 10, 0)
	refresh:SetText("Refresh")
	refresh:SetScript("OnClick", function() Panel:RefreshList() end)

	local sample = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
	sample:SetSize(110, 22)
	sample:SetPoint("LEFT", refresh, "RIGHT", 6, 0)
	sample:SetText("Sample Error")
	sample:SetScript("OnClick", function() Panel:AddSample() end)

	local sources = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
	sources:SetSize(110, 22)
	sources:SetPoint("LEFT", sample, "RIGHT", 6, 0)
	sources:SetText("Sources")
	sources:SetScript("OnClick", function() Panel:ShowSources() end)

	local first = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
	first:SetSize(120, 22)
	first:SetPoint("LEFT", sources, "RIGHT", 6, 0)
	first:SetText("Latest Report")
	first:SetScript("OnClick", function() Panel:ShowLatestReport() end)

	local left = createBackdropFrame(nil, frame)
	left:SetPoint("TOPLEFT", frame, "TOPLEFT", 18, -102)
	left:SetPoint("BOTTOMLEFT", frame, "BOTTOMLEFT", 18, 18)
	left:SetWidth(390)
	setBackdrop(left)

	local right = createBackdropFrame(nil, frame)
	right:SetPoint("TOPLEFT", left, "TOPRIGHT", 12, 0)
	right:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", -18, 18)
	setBackdrop(right)

	local listScroll = CreateFrame("ScrollFrame", nil, left, "UIPanelScrollFrameTemplate")
	listScroll:SetPoint("TOPLEFT", left, "TOPLEFT", 10, -10)
	listScroll:SetPoint("BOTTOMRIGHT", left, "BOTTOMRIGHT", -28, 10)
	local listOutput = CreateFrame("EditBox", nil, listScroll)
	self.listOutput = listOutput
	listOutput:SetMultiLine(true)
	listOutput:SetAutoFocus(false)
	listOutput:SetFontObject(ChatFontNormal)
	listOutput:SetWidth(320)
	listOutput:SetScript("OnEscapePressed", function(box) box:ClearFocus() end)
	listScroll:SetScrollChild(listOutput)

	local reportScroll = CreateFrame("ScrollFrame", nil, right, "UIPanelScrollFrameTemplate")
	reportScroll:SetPoint("TOPLEFT", right, "TOPLEFT", 10, -10)
	reportScroll:SetPoint("BOTTOMRIGHT", right, "BOTTOMRIGHT", -28, 10)
	local reportOutput = CreateFrame("EditBox", nil, reportScroll)
	self.reportOutput = reportOutput
	reportOutput:SetMultiLine(true)
	reportOutput:SetAutoFocus(false)
	reportOutput:SetFontObject(ChatFontNormal)
	reportOutput:SetWidth(520)
	reportOutput:SetScript("OnEscapePressed", function(box) box:ClearFocus() end)
	reportScroll:SetScrollChild(reportOutput)

	frame:SetScript("OnSizeChanged", function()
		if listOutput then listOutput:SetWidth(math.max(260, left:GetWidth() - 46)) end
		if reportOutput then reportOutput:SetWidth(math.max(420, right:GetWidth() - 46)) end
	end)
end

function Panel:AddSample()
	if ApiVault.ExternalErrorBridge and ApiVault.ExternalErrorBridge.IngestError then
		ApiVault.ExternalErrorBridge:RegisterSource("CustomBugDetector", { sample = true })
		ApiVault.ExternalErrorBridge:IngestError({
			addon = "ApiVaultSampleAddon",
			message = "ApiVaultSampleAddon/Core.lua:42: attempt to index field 'settings' (a nil value)",
			stack = "Interface/AddOns/ApiVaultSampleAddon/Core.lua:42: in function `RefreshSettings'\nInterface/AddOns/ApiVaultSampleAddon/Core.lua:88: in function <Interface/AddOns/ApiVaultSampleAddon/Core.lua:80>",
			file = "Interface/AddOns/ApiVaultSampleAddon/Core.lua",
			line = 42,
			context = "Sample error generated by ApiVault BugAdvisorPanel",
			source = "CustomBugDetector",
		})
	end
	self:RefreshList()
	self:ShowLatestReport()
end

function Panel:RefreshList()
	self:Create()
	local query = self.searchBox and self.searchBox:GetText() or ""
	if ApiVault.BugAdvisor and ApiVault.BugAdvisor.FormatErrorList then
		self.listOutput:SetText(ApiVault.BugAdvisor:FormatErrorList(query))
	else
		self.listOutput:SetText("BugAdvisor unavailable.")
	end
	self.listOutput:SetCursorPosition(0)
end

function Panel:ShowLatestReport()
	self:Create()
	local errors = ApiVault.BugAdvisor and ApiVault.BugAdvisor.GetErrors and ApiVault.BugAdvisor:GetErrors() or {}
	local record = errors and errors[1]
	if record and ApiVault.BugAdvisor.FormatBugReport then
		self.reportOutput:SetText(ApiVault.BugAdvisor:FormatBugReport(record))
	else
		self.reportOutput:SetText("No ingested error available yet.")
	end
	self.reportOutput:SetCursorPosition(0)
end

function Panel:ShowSources()
	self:Create()
	if ApiVault.ExternalErrorBridge and ApiVault.ExternalErrorBridge.FormatSources then
		self.reportOutput:SetText(ApiVault.ExternalErrorBridge:FormatSources())
	else
		self.reportOutput:SetText("ExternalErrorBridge unavailable.")
	end
	self.reportOutput:SetCursorPosition(0)
end

function Panel:Open()
	self:Create()
	self.frame:Show()
	if ApiVault.RaiseWindow then ApiVault:RaiseWindow(self.frame) end
	self:RefreshList()
	self:ShowLatestReport()
end

function Panel:Toggle()
	self:Create()
	if self.frame:IsShown() then self.frame:Hide() else self:Open() end
end
