-- ApiVault Developer Debug Bridge UI. Added in v1.1.0.
local addonName, ApiVault = ...

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

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("ApiVaultDeveloperDebugPanel", UIParent)
	self.frame = frame
	frame:SetSize(980, 650)
	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(840, 540) elseif frame.SetMinResize then frame:SetMinResize(840, 540) end
	end
	setBackdrop(frame)
	if ApiVault.PrepareWindow then ApiVault:PrepareWindow(frame, "DeveloperDebug") 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 - Public Developer Debug API")

	local note = createText(frame, "GameFontDisableSmall")
	note:SetPoint("TOPLEFT", title, "BOTTOMLEFT", 0, -4)
	note:SetText("Data-only bridge. Addons can submit logs/errors/traces; ApiVault executes none of that data.")

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

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

	local all = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
	all:SetSize(86, 22)
	all:SetPoint("LEFT", refresh, "RIGHT", 6, 0)
	all:SetText("All Reports")
	all:SetScript("OnClick", function() Panel:ShowAll() end)

	local clear = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
	clear:SetSize(70, 22)
	clear:SetPoint("LEFT", all, "RIGHT", 6, 0)
	clear:SetText("Clear")
	clear:SetScript("OnClick", function()
		if ApiVault.DeveloperAPI then ApiVault.DeveloperAPI:Clear() end
		Panel:Refresh()
	end)

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

	local holder = createBackdropFrame(nil, frame)
	holder:SetPoint("TOPLEFT", frame, "TOPLEFT", 18, -102)
	holder:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", -18, 18)
	setBackdrop(holder)

	local scroll = CreateFrame("ScrollFrame", nil, holder, "UIPanelScrollFrameTemplate")
	scroll:SetPoint("TOPLEFT", holder, "TOPLEFT", 10, -10)
	scroll:SetPoint("BOTTOMRIGHT", holder, "BOTTOMRIGHT", -28, 10)

	local output = CreateFrame("EditBox", nil, scroll)
	self.output = output
	output:SetMultiLine(true)
	output:SetAutoFocus(false)
	output:SetFontObject(ChatFontNormal)
	output:SetWidth(900)
	output:SetText("")
	output:SetScript("OnEscapePressed", function(box) box:ClearFocus() end)
	scroll:SetScrollChild(output)

	frame:SetScript("OnSizeChanged", function()
		if output then output:SetWidth(math.max(500, holder:GetWidth() - 48)) end
	end)
end

function Panel:AddSample()
	local bridge = ApiVault and ApiVault.GetPublicAPI and ApiVault:GetPublicAPI("ApiVaultSampleAddon", 1)
	if bridge then
		bridge:RegisterAddon({ name = "ApiVaultSampleAddon", version = "1.0.0", interface = ApiVault.interface, note = "Generated sample data" })
		bridge:Log("info", "Sample addon initialized")
		bridge:TraceAPI("C_Item.GetItemInfo", { file = "Sample/Items.lua", line = 42, context = "Item cache refresh" })
		bridge:TraceEvent("BAG_UPDATE", { file = "Sample/Events.lua", line = 18, registration = "RegisterEvent" })
		bridge:ReportSecureRisk({ pattern = "SetAttribute", file = "Sample/Secure.lua", line = 55, context = "right-click action", combatSensitive = true })
		bridge:ReportSavedVariables({ name = "SampleDB", initialized = true, schemaVersion = 1 })
		bridge:Checkpoint("Sample checkpoint", { items = 12, durationMs = 4 })
		bridge:ReportError({ message = "attempt to index field 'settings' (a nil value)", file = "Sample/Core.lua", line = 88, stack = "Sample/Core.lua:88: in function <Sample/Core.lua:70>" })
	end
	self:Refresh()
end

function Panel:ShowAll()
	self:Create()
	if ApiVault.DeveloperAPI then
		self.output:SetText(ApiVault.DeveloperAPI:FormatAllReports())
	else
		self.output:SetText("DeveloperAPI unavailable.")
	end
	self.output:SetCursorPosition(0)
end

function Panel:Refresh()
	self:Create()
	if not ApiVault.DeveloperAPI then
		self.output:SetText("DeveloperAPI unavailable.")
		return
	end
	local query = self.searchBox and self.searchBox:GetText() or ""
	if query and query ~= "" then
		self.output:SetText(ApiVault.DeveloperAPI:FormatAddonReport(query))
	else
		self.output:SetText(ApiVault.DeveloperAPI:FormatAllReports())
	end
	self.output:SetCursorPosition(0)
end

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

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