-- ApiVault Addon Audit Mode UI. Added in v0.6.0.
-- Paste-based audit panel. Does not read files at runtime.
local addonName, ApiVault = ...

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

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

local function createScrollEdit(parent, name)
	local holder = createBackdropFrame(nil, parent)
	setBackdrop(holder, 0.015, 0.015, 0.02, 0.9)
	local scroll = CreateFrame("ScrollFrame", name .. "Scroll", holder, "UIPanelScrollFrameTemplate")
	scroll:SetPoint("TOPLEFT", 10, -10)
	scroll:SetPoint("BOTTOMRIGHT", -28, 10)
	local edit = CreateFrame("EditBox", name, scroll)
	edit:SetMultiLine(true)
	edit:SetAutoFocus(false)
	edit:SetFontObject(ChatFontNormal)
	edit:SetTextColor(1, 1, 1, 1)
	edit:SetWidth(480)
	edit:SetHeight(700)
	edit:SetScript("OnEscapePressed", function(self) self:ClearFocus() end)
	scroll:SetScrollChild(edit)
	holder.editBox = edit
	holder.scroll = scroll
	return holder, edit
end

local BUTTONS = {
	{ label = "Auto Audit", kind = "auto" },
	{ label = "Audit Lua", kind = "lua" },
	{ label = "Audit XML", kind = "xml" },
	{ label = "Audit TOC", kind = "toc" },
}

function Panel:Create()
	if self.frame then return end
	local frame = createBackdropFrame("ApiVaultAddonAuditFrame", UIParent)
	self.frame = frame
	frame:SetSize(1180, 760)
	frame:SetPoint("CENTER", 40, -20)
	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(980, 620) elseif frame.SetMinResize then frame:SetMinResize(980, 620) end
	end
	setBackdrop(frame)
	if ApiVault.PrepareWindow then ApiVault:PrepareWindow(frame, "AddonAudit") 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 - Addon Audit Mode")

	local sub = createFont(frame, "GameFontDisableSmall")
	sub:SetPoint("TOPLEFT", title, "BOTTOMLEFT", 0, -4)
	sub:SetPoint("RIGHT", frame, "RIGHT", -20, 0)
	sub:SetText("Paste Lua, XML or TOC text. ApiVault scans metadata/checklist patterns only; no file reads, execution or rewrite.")

	local leftLabel = createFont(frame, "GameFontNormal")
	leftLabel:SetPoint("TOPLEFT", frame, "TOPLEFT", 24, -68)
	leftLabel:SetText("Paste addon source / TOC / XML")
	local rightLabel = createFont(frame, "GameFontNormal")
	rightLabel:SetPoint("TOPLEFT", frame, "TOP", 14, -68)
	rightLabel:SetText("Audit report")

	local inputHolder, inputEdit = createScrollEdit(frame, "ApiVaultAddonAuditInput")
	self.inputEdit = inputEdit
	inputHolder:SetPoint("TOPLEFT", frame, "TOPLEFT", 18, -92)
	inputHolder:SetPoint("BOTTOMLEFT", frame, "BOTTOMLEFT", 18, 58)
	inputHolder:SetWidth(540)

	local outputHolder, outputEdit = createScrollEdit(frame, "ApiVaultAddonAuditOutput")
	self.outputEdit = outputEdit
	outputHolder:SetPoint("TOPLEFT", inputHolder, "TOPRIGHT", 18, 0)
	outputHolder:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", -18, 58)
	outputEdit:SetText("Paste addon code on the left, then choose an audit mode. Output can be copied with Ctrl+A / Ctrl+C.")

	local buttonRow = createBackdropFrame(nil, frame)
	self.buttonRow = buttonRow
	buttonRow:SetPoint("BOTTOMLEFT", frame, "BOTTOMLEFT", 18, 14)
	buttonRow:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", -18, 14)
	buttonRow:SetHeight(36)
	setBackdrop(buttonRow, 0.02, 0.02, 0.025, 0.82)

	local x = 12
	for _, config in ipairs(BUTTONS) do
		local button = CreateFrame("Button", nil, buttonRow, "UIPanelButtonTemplate")
		button:SetSize(95, 22)
		button:SetPoint("LEFT", buttonRow, "LEFT", x, 0)
		button:SetText(config.label)
		button:SetScript("OnClick", function()
			Panel:Run(config.kind)
		end)
		x = x + 102
	end

	local copy = CreateFrame("Button", nil, buttonRow, "UIPanelButtonTemplate")
	copy:SetSize(90, 22)
	copy:SetPoint("LEFT", buttonRow, "LEFT", x + 8, 0)
	copy:SetText("Select Report")
	copy:SetScript("OnClick", function()
		outputEdit:SetFocus()
		outputEdit:HighlightText()
	end)

	local clear = CreateFrame("Button", nil, buttonRow, "UIPanelButtonTemplate")
	clear:SetSize(70, 22)
	clear:SetPoint("LEFT", copy, "RIGHT", 8, 0)
	clear:SetText("Clear")
	clear:SetScript("OnClick", function()
		inputEdit:SetText("")
		outputEdit:SetText("")
	end)

	local sample = CreateFrame("Button", nil, buttonRow, "UIPanelButtonTemplate")
	sample:SetSize(100, 22)
	sample:SetPoint("LEFT", clear, "RIGHT", 8, 0)
	sample:SetText("Insert Sample")
	sample:SetScript("OnClick", function()
		Panel:InsertSample()
	end)

	local closeOthers = CreateFrame("Button", nil, buttonRow, "UIPanelButtonTemplate")
	closeOthers:SetSize(150, 22)
	closeOthers:SetPoint("RIGHT", buttonRow, "RIGHT", -12, 0)
	closeOthers:SetText("Close other windows")
	closeOthers:SetScript("OnClick", function()
		if ApiVault.CloseOtherWindows then ApiVault:CloseOtherWindows(frame) end
	end)

	frame:SetScript("OnSizeChanged", function()
		local width = math.max(420, inputHolder:GetWidth() - 40)
		inputEdit:SetWidth(width)
		outputEdit:SetWidth(math.max(420, outputHolder:GetWidth() - 40))
	end)
end

function Panel:InsertSample()
	if not self.inputEdit then return end
	self.inputEdit:SetText([[## Interface: 120007
## Title: SampleAudit
## SavedVariables: SampleAuditDB

local f = CreateFrame("Button", "SampleAuditButton", UIParent, "SecureActionButtonTemplate")
f:SetAttribute("type", "item")
f:RegisterEvent("BAG_UPDATE")
f:SetScript("OnUpdate", function(self, elapsed)
    local item = C_Container.GetContainerItemInfo(0, 1)
end)]])
end

function Panel:Run(kind)
	if not ApiVault.AddonAudit or not ApiVault.AddonAudit.ScanText then
		self.outputEdit:SetText("AddonAudit rules unavailable.")
		return
	end
	local text = self.inputEdit and self.inputEdit:GetText() or ""
	if text == "" then
		self.outputEdit:SetText("No input. Paste Lua/XML/TOC text or click Insert Sample.")
		return
	end
	local report = ApiVault.AddonAudit:ScanText(text, kind or "auto", "ApiVault paste audit")
	self.outputEdit:SetText(ApiVault.AddonAudit:FormatReport(report))
	self.outputEdit:SetCursorPosition(0)
end

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

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