local AppName = "ViolLuaNew"
local OwnerId = "dEng9XoWgH"
local AppVersion = "1.0"
local apiBase = "https://keyauth.win/api/1.1/"
local isInitialized, sessionId, isAuthenticated = false, "", false
local keyFrame, keyEntry, statusLabel, validateButton
local rgbTime = 0
local function ParseJson(json)
    return util.JSONToTable(json)
end
local function GetRGBColor(t, alpha)
    alpha = alpha or 255
    return Color(
        math.sin(t * 2) * 127 + 128,
        math.sin(t * 2 + 2) * 127 + 128,
        math.sin(t * 2 + 4) * 127 + 128,
        alpha
    )
end
local function URLEncode(str)
    if not str then return "" end
    str = tostring(str)
    str = string.gsub(str, "\n", "\r\n")
    str = string.gsub(str, "([^%w _%%%-%.~])", function(c) return string.format("%%%02X", string.byte(c)) end)
    return string.gsub(str, " ", "+")
end
local function ShowStatusMessage(text, color)
    color = color or Color(255, 255, 255)
    if IsValid(statusLabel) then
        statusLabel:SetText(text)
        statusLabel:SetTextColor(color)
    end
    MsgC(color, text .. "\n")
end
local function LoadMainScript()
    include("main.lua")
    MsgC(Color(0, 255, 0), "[Viol.lua] Main script loaded successfully.\n")
end
local function InitializeKeyAuth(callback)
    local url = apiBase .. "?name=" .. AppName .. "&ownerid=" .. OwnerId .. "&type=init&ver=" .. AppVersion
    http.Fetch(url,
        function(body)
            local data = ParseJson(body)
            if data and data.success then
                isInitialized, sessionId = true, data.sessionid
                ShowStatusMessage("KeyAuth initialized successfully.", Color(100, 255, 100))
                if callback then callback() end
            else
                ShowStatusMessage("Initialization failed: " .. (data and data.message or "error"), Color(255, 0, 0))
            end
        end,
        function(err) ShowStatusMessage("HTTP Init Error: " .. err, Color(255, 0, 0)) end
    )
end
local function VerifyLicense(licenseKey)
    if not isInitialized then ShowStatusMessage("KeyAuth not initialized.", Color(255, 0, 0)) return end
    if licenseKey == "" then ShowStatusMessage("Enter a license key.", Color(255, 0, 0)) return end
    ShowStatusMessage("Verifying license key...", Color(255, 255, 0))
    local fullUrl = apiBase .. "?name=" .. URLEncode(AppName) .. "&ownerid=" .. URLEncode(OwnerId)
        .. "&type=license&key=" .. URLEncode(licenseKey)
        .. "&ver=" .. URLEncode(AppVersion) .. "&sessionid=" .. URLEncode(sessionId)
    http.Fetch(fullUrl,
        function(body)
            local data = ParseJson(body)
            if data and data.success then
                isAuthenticated = true
                local sub = data.info.subscriptions and data.info.subscriptions[1]
                local expiration = "N/A"
                if sub and tonumber(sub.expiry) and tonumber(sub.expiry) > os.time() then
                    local remain = tonumber(sub.expiry) - os.time()
                    expiration = math.floor(remain/86400) .. "d " .. math.floor((remain%86400)/3600) .. "h"
                end
                ShowStatusMessage("Authentication successful. Welcome " .. (data.info.username or "User") .. ". License expires in: " .. expiration, Color(0, 255, 100))
                timer.Simple(0.4, function()
                    if IsValid(keyFrame) then
                        keyFrame:Remove()
                        LoadMainScript()
                    end
                end)
            else
                ShowStatusMessage("License failed: " .. (data and data.message or "invalid key"), Color(255, 0, 0))
                validateButton:SetEnabled(true)
            end
        end,
        function(err) ShowStatusMessage("HTTP Error: " .. err, Color(255, 0, 0)); validateButton:SetEnabled(true) end
    )
end
local function CreateKeyAuthMenu()
    if isAuthenticated then return end
    keyFrame = vgui.Create("DFrame")
    keyFrame:SetSize(450, 300); keyFrame:Center(); keyFrame:SetTitle("")
    keyFrame:SetDraggable(false); keyFrame:ShowCloseButton(false)
    keyFrame:SetDeleteOnClose(false); keyFrame:MakePopup(); keyFrame:SetBackgroundBlur(true)
    keyFrame:SetAlpha(0); keyFrame:AlphaTo(255, 0.4, 0)
    keyFrame.OnClose = function() return isAuthenticated end
    keyFrame.Paint = function(self, w, h)
        rgbTime = rgbTime + FrameTime() * 2
        draw.RoundedBox(10, 0, 0, w, h, Color(25, 25, 25, 240))
        local border = GetRGBColor(rgbTime, 200)
        surface.SetDrawColor(border); surface.DrawOutlinedRect(0, 0, w, h, 2)
    end
    keyEntry = vgui.Create("DTextEntry", keyFrame)
    keyEntry:SetPos(70, 100); keyEntry:SetSize(310, 30); keyEntry:SetFont("DermaDefault")
    keyEntry:SetPlaceholderText("Enter your license key...")
    keyEntry.Paint = function(self, w, h)
        draw.RoundedBox(6, 0, 0, w, h, Color(30, 30, 30, 255))
        surface.SetDrawColor(GetRGBColor(rgbTime * 1.1, 150))
        surface.DrawOutlinedRect(0, 0, w, h, 1)
        self:DrawTextEntryText(Color(255, 255, 255), Color(200, 200, 200), Color(255, 255, 255))
    end
    keyEntry.OnEnter = function() validateButton:DoClick() end
    statusLabel = vgui.Create("DLabel", keyFrame)
    statusLabel:SetPos(50, 150); statusLabel:SetSize(350, 40)
    statusLabel:SetText("[ Waiting for input ]"); statusLabel:SetTextColor(Color(200, 200, 200))
    statusLabel:SetContentAlignment(5)
    validateButton = vgui.Create("DButton", keyFrame)
    validateButton:SetPos(70, 200); validateButton:SetSize(310, 30)
    validateButton:SetText("Validate Key"); validateButton:SetFont("DermaDefaultBold")
    validateButton.Paint = function(self, w, h)
        local col = GetRGBColor(rgbTime * 1.2, 200)
        draw.RoundedBox(4, 0, 0, w, h, Color(col.r*0.5, col.g*0.5, col.b*0.5, 220))
        surface.SetDrawColor(col); surface.DrawOutlinedRect(0, 0, w, h, 1)
    end
    validateButton.DoClick = function()
        local key = keyEntry:GetValue()
        if key=="" then ShowStatusMessage("Enter a license key.", Color(255,0,0)) return end
        validateButton:SetEnabled(false)
        ShowStatusMessage("Verifying license...", Color(255,255,0))
        VerifyLicense(key)
    end
    ShowStatusMessage("Initializing KeyAuth...", Color(100,255,100))
    InitializeKeyAuth()
end
if not isAuthenticated then CreateKeyAuthMenu() end
