local use_font = system.IsWindows() and "Tahoma" or "Verdana"
surface.CreateFont("MG_Trunk_Interface", {font = use_font, size = 16, weight = 1000, blursize = 0, scanlines = 0})
surface.CreateFont("MG_Trunk_CloseButton", {font = use_font, size = 13, weight = 1000, blursize = 0, scanlines = 0, antialias = true})

local Frame
local local_ply, tr, ent

local black = Color(0, 0, 0, 255)
local white = Color(255, 255, 255, 200)
local red = Color(128, 30, 30, 255)
local function DrawTrunkHUD()
	local_ply = local_ply or LocalPlayer()
	tr = local_ply:GetEyeTrace()
	ent = tr.Entity
	if IsValid(ent) and !local_ply:InVehicle() then
		local class = ent:GetClass()
		if class == "prop_vehicle_jeep" or class == "prop_vehicle_jeep_old" or class == "prop_vehicle_airboat" then
			local veh_class = ent:GetVehicleClass()
			if MG_Trunk.CustomTrunkSizes[veh_class] != 0 then
				local check = MG_Trunk.CustomTrunkPositionChecks[veh_class]
				if check and check(local_ply, ent, tr) or !check and local_ply:EyePos():DistToSqr(tr.HitPos) <= MG_Trunk.MaxPlayerDistance and tr.HitPos:DistToSqr(ent:LocalToWorld(ent:GetTrunkPosition())) <= MG_Trunk.MaxHitPosDistance then
					if IsValid(Frame) then return end
					local open = ent:GetNW2Bool("Trunk_Open")
					local txt = "Kofferraum"
					local txt2 = open and "Drücke "..((input.LookupBinding(MG_Trunk.UseBind) or "[UNBEKANNT]"):upper()).." um den Kofferraum zu öffnen." or "Schließe den Kofferraum mit den Schlüsseln auf."
					draw.DrawNonParsedText(txt, "Roboto20", ScrW() / 2, ScrH() / 2 - 60 + 1, black, 1)
					draw.DrawNonParsedText(txt, "Roboto20", ScrW() / 2, ScrH() / 2 - 60, open and white or red, 1)
					draw.DrawNonParsedText(txt2, "Roboto20", ScrW() / 2, ScrH() / 2 - 40 + 1, black, 1)
					draw.DrawNonParsedText(txt2, "Roboto20", ScrW() / 2, ScrH() / 2 - 40, open and white or red, 1)
				end
			end
		else
			if ent:IsPlayer() or ent:IsRagdoll() or ent:IsNPC() then return end
			if ent.CPPICanPickup and !ent:CPPICanPickup(local_ply) then return end
			local check = isfunction(MG_Trunk.PickupBlacklist[class]) and MG_Trunk.PickupBlacklist[class](ent, local_ply) or !isfunction(MG_Trunk.PickupBlacklist[class]) and MG_Trunk.PickupBlacklist[class]
			if check or string.find(class, "func_") then return end
			if local_ply:EyePos():DistToSqr(ent:GetPos()) > MG_Trunk.MaxControllerDistance then return end
			local found
			local nearest = math.huge
			for _, v in ipairs(ents.FindInSphere(tr.HitPos, 100)) do
				if v:IsVehicle() then
					local cls = v:GetClass()
					if cls == "prop_vehicle_jeep" or cls == "prop_vehicle_jeep_old" or cls == "prop_vehicle_airboat" then
						if MG_Trunk.CustomTrunkSizes[v:GetVehicleClass()] == 0 or !v:GetNW2Bool("Trunk_Open") then continue end
						local trunk_pos = v:LocalToWorld(v:GetTrunkPosition())
						local ent_pos = ent:GetPos()
						local dist = trunk_pos:DistToSqr(ent_pos)
						if dist > MG_Trunk.MaxEntityDistance then continue end
						local tr2 = util.TraceLine({start = trunk_pos, endpos = ent_pos, filter = {v, ent}})
						if !tr2.Hit and dist < nearest then
							nearest = dist
							found = v
						end
					end
				end
			end
			if found then
				local txt = "Drücke "..((input.LookupBinding(MG_Trunk.StoreBind) or "[UNBEKANNT]"):upper()).." um diesen Gegenstand in den Kofferraum zu legen."
				draw.DrawNonParsedText(txt, "Roboto20", ScrW() / 2, ScrH() / 2 - 80 + 1, black, 1)
				draw.DrawNonParsedText(txt, "Roboto20", ScrW() / 2, ScrH() / 2 - 80, white, 1)
			end
		end
	end
end
hook.Add("HUDPaint", "MG_Trunk_DrawHUD", DrawTrunkHUD)

hook.Add("PlayerBindPress", "MG_Trunk_OpenMenu", function(ply, bind, pressed)
	if !pressed then return end
	local tr = ply:GetEyeTrace()
	local ent = tr.Entity
	if IsValid(ent) and !ply:InVehicle() then
		local class = ent:GetClass()
		if bind == MG_Trunk.UseBind and class == "prop_vehicle_jeep" or class == "prop_vehicle_jeep_old" or class == "prop_vehicle_airboat" then
			local veh_class = ent:GetVehicleClass()
			if MG_Trunk.CustomTrunkSizes[veh_class] != 0 then
				local check = MG_Trunk.CustomTrunkPositionChecks[veh_class]
				if check and check(ply, ent, tr) or !check and ply:EyePos():DistToSqr(tr.HitPos) <= MG_Trunk.MaxPlayerDistance and tr.HitPos:DistToSqr(ent:LocalToWorld(ent:GetTrunkPosition())) <= MG_Trunk.MaxHitPosDistance then
					net.Start("MG_Trunk_OpenMenu")
					net.SendToServer()
					return true
				end
			end
		elseif bind == MG_Trunk.StoreBind then
			if ent:IsPlayer() or ent:IsRagdoll() or ent:IsNPC() then return end
			local check = isfunction(MG_Trunk.PickupBlacklist[class]) and MG_Trunk.PickupBlacklist[class](ent, ply) or !isfunction(MG_Trunk.PickupBlacklist[class]) and MG_Trunk.PickupBlacklist[class]
			if check or string.find(class, "func_") then return end
			local ent_pos = ent:GetPos()
			if ply:EyePos():DistToSqr(ent_pos) > MG_Trunk.MaxControllerDistance then return end
			local found
			local nearest = math.huge
			for _, v in ipairs(ents.FindInSphere(tr.HitPos, 100)) do
				if v:IsVehicle() then
					local cls = v:GetClass()
					if cls == "prop_vehicle_jeep" or cls == "prop_vehicle_jeep_old" or cls == "prop_vehicle_airboat" then
						if MG_Trunk.CustomTrunkSizes[v:GetVehicleClass()] == 0 or !v:GetNW2Bool("Trunk_Open") then continue end
						local trunk_pos = v:LocalToWorld(v:GetTrunkPosition())
						local dist = trunk_pos:DistToSqr(ent_pos)
						if dist > MG_Trunk.MaxEntityDistance then continue end
						local tr2 = util.TraceLine({start = trunk_pos, endpos = ent_pos, filter = {v, ent}})
						if !tr2.Hit and dist < nearest then
							nearest = dist
							found = v
						end
					end
				end
			end
			if found then
				RunConsoleCommand("trunk_store")
				return true
			end
		end
	end
end)

hook.Add("HUDDrawDoorData", "MG_Trunk_HideDoorInfo", function()
	if IsValid(Frame) then
		return true
	end
end)

local Mat = Material("icon16/car.png")
net.Receive("MG_Trunk_OpenMenu", function()
	local ent = net.ReadEntity()
	if !IsValid(ent) or IsValid(Frame) then return end
	local size = ent.TrunkSize
	if !size then return end
	local ents = net.ReadTable()
	local ents_cnt = #ents
	Frame = vgui.Create("DFrame")
	Frame:SetSize(math.max(64 * ents_cnt, 128), 88)
	Frame:Center()
	Frame:ShowCloseButton(false)
	Frame:SetTitle("")
	Frame:MakePopup()
	Frame:ParentToHUD()
	Frame.Paint = function(self, w, h)
		draw.RoundedBoxEx(4, 0, 0, w, h, Color(0, 0, 0, 224), false, false, true, true)
		surface.SetDrawColor(Color(0, 0, 0, 224))
		surface.DrawRect(0, 0, w, 24)
		surface.SetDrawColor(Color(52, 152, 219))
		surface.DrawRect(0, 0, w, 24)
		surface.SetMaterial(Mat)
		surface.SetDrawColor(color_white)
		surface.DrawTexturedRect(4, 4, 16, 16)
		draw.DrawText(ents_cnt.." / "..size, "MG_Trunk_Interface", 30, 4, color_white, TEXT_ALIGN_LEFT)
		if ents_cnt == 0 then
			draw.DrawText("Leer...", "MG_Trunk_Interface", w / 2 - 20, h / 2, color_white, TEXT_ALIGN_LEFT)
		end
	end
	local ply = LocalPlayer()
	Frame.Think = function()
		local tr = ply:GetEyeTrace()
		local veh = tr.Entity
		if !IsValid(ent) or !IsValid(veh) or veh != ent then Frame:Remove() return end
		local check = MG_Trunk.CustomTrunkPositionChecks[ent:GetVehicleClass()]
		if !ply:Alive() or check and !check(ply, ent, tr) or !check and ply:EyePos():DistToSqr(tr.HitPos) > MG_Trunk.MaxPlayerDistance or !check and tr.HitPos:DistToSqr(ent:LocalToWorld(ent:GetTrunkPosition())) > MG_Trunk.MaxHitPosDistance then
			Frame:Remove()
		end
	end
	local Close = vgui.Create("DButton", Frame)
	Close:SetSize(50, 25)
	Close:SetPos(Frame:GetWide() - 49, 0)
	Close:SetText("X")
	Close:SetFont("MG_Trunk_CloseButton")
	Close:SetTextColor(color_white)
	Close.Paint = function(self, w, h)
		local col
		if self:IsHovered() then
			col = Color(255, 50, 50)
		else
			col = Color(200, 50, 50)
		end
		draw.RoundedBoxEx(0, 1, 0, w - 2, h - 1, col, false, false, true, true)
	end
	Close.DoClick = function()
		Frame:Remove()
	end
	Frame.Scroll = vgui.Create("DScrollPanel", Frame)
	Frame.Scroll:SetSize(math.max(64 * ents_cnt, 128), 72)
	Frame.Scroll:SetPos(0, 24)
	Frame.List = vgui.Create("DIconLayout", Frame.Scroll)
	Frame.List:SetSize(Frame.Scroll:GetWide(), Frame.Scroll:GetTall())
	Frame.List:SetSpaceX(0)
	Frame.List:SetSpaceY(0)
	for k, v in ipairs(ents) do
		if !IsValid(v) then continue end
		local Icon = Frame.List:Add("SpawnIcon")
		Icon:SetSize(64, 64)
		Icon:SetModel(v:GetModel() or "models/error.mdl")
		Icon:SetTooltip(v.PrintName or v:GetClass() or "FEHLER")
		Icon.DoClick = function()
			if IsValid(ent) then
				net.Start("MG_Trunk_TakeOut")
					net.WriteEntity(ent)
					net.WriteUInt(k, 16)
				net.SendToServer()
			end
			Frame:Remove()
		end
	end
end)