--[[
    SocietixM Plugin - User Interface
    Provides UI components and management for the SocietixM plugin
]]

local SocietixMPlugin = script.Parent.Parent
local Core = require(SocietixMPlugin.Core)

local UI = {}
UI.__index = UI

-- UI state
local activeWindows = {}
local defaultTheme = {
    PrimaryColor = Color3.fromRGB(0, 120, 215),
    SecondaryColor = Color3.fromRGB(107, 107, 107),
    BackgroundColor = Color3.fromRGB(30, 30, 30),
    TextColor = Color3.fromRGB(255, 255, 255),
    BorderColor = Color3.fromRGB(100, 100, 100),
    SuccessColor = Color3.fromRGB(0, 200, 0),
    ErrorColor = Color3.fromRGB(200, 0, 0),
    WarningColor = Color3.fromRGB(255, 165, 0)
}

function UI:Initialize()
    print("[SocietixM] Initializing UI...")
    
    -- Create main plugin GUI
    self:CreateMainGUI()
    
    print("[SocietixM] UI initialized")
end

function UI:CreateMainGUI()
    local Players = game:GetService("Players")
    local TweenService = game:GetService("TweenService")
    
    -- Create main screen GUI
    local screenGui = Instance.new("ScreenGui")
    screenGui.Name = "SocietixMPlugin"
    screenGui.ResetOnSpawn = false
    screenGui.Parent = Players.LocalPlayer:WaitForChild("PlayerGui")
    
    -- Create main frame
    local mainFrame = Instance.new("Frame")
    mainFrame.Name = "MainFrame"
    mainFrame.Size = UDim2.new(0, 400, 0, 300)
    mainFrame.Position = UDim2.new(0, 10, 0, 10)
    mainFrame.BackgroundColor3 = defaultTheme.BackgroundColor
    mainFrame.BorderSizePixel = 0
    mainFrame.Visible = false
    mainFrame.Parent = screenGui
    
    -- Add rounded corners
    local corner = Instance.new("UICorner")
    corner.CornerRadius = UDim.new(0, 8)
    corner.Parent = mainFrame
    
    -- Add drop shadow
    local shadow = Instance.new("ImageLabel")
    shadow.Name = "Shadow"
    shadow.Size = UDim2.new(1, 10, 1, 10)
    shadow.Position = UDim2.new(0, -5, 0, -5)
    shadow.BackgroundTransparency = 1
    shadow.Image = "rbxasset://textures/ui/GuiImagePlaceholder.png"
    shadow.ImageColor3 = Color3.new(0, 0, 0)
    shadow.ImageTransparency = 0.5
    shadow.ZIndex = mainFrame.ZIndex - 1
    shadow.Parent = mainFrame
    
    -- Create title bar
    self:CreateTitleBar(mainFrame)
    
    -- Create content area
    self:CreateContentArea(mainFrame)
    
    -- Create toolbar button
    self:CreateToolbarButton(screenGui, mainFrame)
    
    -- Store reference
    activeWindows["MainWindow"] = {
        Frame = mainFrame,
        ScreenGui = screenGui
    }
end

function UI:CreateTitleBar(parent)
    local titleBar = Instance.new("Frame")
    titleBar.Name = "TitleBar"
    titleBar.Size = UDim2.new(1, 0, 0, 30)
    titleBar.Position = UDim2.new(0, 0, 0, 0)
    titleBar.BackgroundColor3 = defaultTheme.PrimaryColor
    titleBar.BorderSizePixel = 0
    titleBar.Parent = parent
    
    -- Add rounded corners to top
    local corner = Instance.new("UICorner")
    corner.CornerRadius = UDim.new(0, 8)
    corner.Parent = titleBar
    
    -- Title label
    local titleLabel = Instance.new("TextLabel")
    titleLabel.Name = "TitleLabel"
    titleLabel.Size = UDim2.new(1, -60, 1, 0)
    titleLabel.Position = UDim2.new(0, 10, 0, 0)
    titleLabel.BackgroundTransparency = 1
    titleLabel.Text = "SocietixM Plugin"
    titleLabel.TextColor3 = defaultTheme.TextColor
    titleLabel.TextScaled = true
    titleLabel.Font = Enum.Font.GothamBold
    titleLabel.TextXAlignment = Enum.TextXAlignment.Left
    titleLabel.Parent = titleBar
    
    -- Close button
    local closeButton = Instance.new("TextButton")
    closeButton.Name = "CloseButton"
    closeButton.Size = UDim2.new(0, 30, 0, 30)
    closeButton.Position = UDim2.new(1, -30, 0, 0)
    closeButton.BackgroundTransparency = 1
    closeButton.Text = "×"
    closeButton.TextColor3 = defaultTheme.TextColor
    closeButton.TextScaled = true
    closeButton.Font = Enum.Font.GothamBold
    closeButton.Parent = titleBar
    
    -- Close button functionality
    closeButton.MouseButton1Click:Connect(function()
        parent.Visible = false
    end)
    
    -- Make title bar draggable
    local dragging = false
    local dragStart = nil
    local startPos = nil
    
    titleBar.InputBegan:Connect(function(input)
        if input.UserInputType == Enum.UserInputType.MouseButton1 then
            dragging = true
            dragStart = input.Position
            startPos = parent.Position
        end
    end)
    
    titleBar.InputChanged:Connect(function(input)
        if dragging and input.UserInputType == Enum.UserInputType.MouseMovement then
            local delta = input.Position - dragStart
            parent.Position = UDim2.new(0, startPos.X.Offset + delta.X, 0, startPos.Y.Offset + delta.Y)
        end
    end)
    
    titleBar.InputEnded:Connect(function(input)
        if input.UserInputType == Enum.UserInputType.MouseButton1 then
            dragging = false
        end
    end)
end

function UI:CreateContentArea(parent)
    local contentFrame = Instance.new("Frame")
    contentFrame.Name = "ContentFrame"
    contentFrame.Size = UDim2.new(1, -20, 1, -40)
    contentFrame.Position = UDim2.new(0, 10, 0, 35)
    contentFrame.BackgroundTransparency = 1
    contentFrame.Parent = parent
    
    -- Create tab system
    local tabFrame = Instance.new("Frame")
    tabFrame.Name = "TabFrame"
    tabFrame.Size = UDim2.new(1, 0, 0, 30)
    tabFrame.Position = UDim2.new(0, 0, 0, 0)
    tabFrame.BackgroundTransparency = 1
    tabFrame.Parent = contentFrame
    
    -- Server tab
    local serverTab = self:CreateTab(tabFrame, "Server", 0, 0)
    -- Browser tab
    local browserTab = self:CreateTab(tabFrame, "Browser", 1, 0)
    -- Settings tab
    local settingsTab = self:CreateTab(tabFrame, "Settings", 2, 0)
    
    -- Create tab content
    local tabContent = Instance.new("Frame")
    tabContent.Name = "TabContent"
    tabContent.Size = UDim2.new(1, 0, 1, -35)
    tabContent.Position = UDim2.new(0, 0, 0, 35)
    tabContent.BackgroundTransparency = 1
    tabContent.Parent = contentFrame
    
    -- Server tab content
    self:CreateServerTabContent(tabContent, serverTab)
    -- Browser tab content
    self:CreateBrowserTabContent(tabContent, browserTab)
    -- Settings tab content
    self:CreateSettingsTabContent(tabContent, settingsTab)
end

function UI:CreateTab(parent, text, index, totalTabs)
    local tab = Instance.new("TextButton")
    tab.Name = text .. "Tab"
    tab.Size = UDim2.new(1 / totalTabs, 0, 1, 0)
    tab.Position = UDim2.new(index / totalTabs, 0, 0, 0)
    tab.BackgroundColor3 = defaultTheme.SecondaryColor
    tab.BorderSizePixel = 0
    tab.Text = text
    tab.TextColor3 = defaultTheme.TextColor
    tab.TextScaled = true
    tab.Font = Enum.Font.Gotham
    tab.Parent = parent
    
    -- Tab click functionality
    tab.MouseButton1Click:Connect(function()
        self:SwitchTab(text)
    end)
    
    return tab
end

function UI:CreateServerTabContent(parent, tab)
    local serverContent = Instance.new("Frame")
    serverContent.Name = "ServerContent"
    serverContent.Size = UDim2.new(1, 0, 1, 0)
    serverContent.Position = UDim2.new(0, 0, 0, 0)
    serverContent.BackgroundTransparency = 1
    serverContent.Visible = true
    serverContent.Parent = parent
    
    -- Server status
    local statusLabel = Instance.new("TextLabel")
    statusLabel.Name = "StatusLabel"
    statusLabel.Size = UDim2.new(1, 0, 0, 20)
    statusLabel.Position = UDim2.new(0, 0, 0, 0)
    statusLabel.BackgroundTransparency = 1
    statusLabel.Text = "Server Status: Not Running"
    statusLabel.TextColor3 = defaultTheme.ErrorColor
    statusLabel.TextScaled = true
    statusLabel.Font = Enum.Font.Gotham
    statusLabel.TextXAlignment = Enum.TextXAlignment.Left
    statusLabel.Parent = serverContent
    
    -- Server controls
    local startButton = Instance.new("TextButton")
    startButton.Name = "StartButton"
    startButton.Size = UDim2.new(0, 100, 0, 30)
    startButton.Position = UDim2.new(0, 0, 0, 30)
    startButton.BackgroundColor3 = defaultTheme.SuccessColor
    startButton.BorderSizePixel = 0
    startButton.Text = "Start Server"
    startButton.TextColor3 = defaultTheme.TextColor
    startButton.TextScaled = true
    startButton.Font = Enum.Font.Gotham
    startButton.Parent = serverContent
    
    local stopButton = Instance.new("TextButton")
    stopButton.Name = "StopButton"
    stopButton.Size = UDim2.new(0, 100, 0, 30)
    stopButton.Position = UDim2.new(0, 110, 0, 30)
    stopButton.BackgroundColor3 = defaultTheme.ErrorColor
    stopButton.BorderSizePixel = 0
    stopButton.Text = "Stop Server"
    stopButton.TextColor3 = defaultTheme.TextColor
    stopButton.TextScaled = true
    stopButton.Font = Enum.Font.Gotham
    stopButton.Parent = serverContent
    
    -- Server info
    local infoLabel = Instance.new("TextLabel")
    infoLabel.Name = "InfoLabel"
    infoLabel.Size = UDim2.new(1, 0, 0, 100)
    infoLabel.Position = UDim2.new(0, 0, 0, 70)
    infoLabel.BackgroundTransparency = 1
    infoLabel.Text = "Server ID: None\nSocietix ID: None\nPlayers: 0/20"
    infoLabel.TextColor3 = defaultTheme.TextColor
    infoLabel.TextScaled = true
    infoLabel.Font = Enum.Font.Gotham
    infoLabel.TextXAlignment = Enum.TextXAlignment.Left
    infoLabel.TextYAlignment = Enum.TextYAlignment.Top
    infoLabel.Parent = serverContent
end

function UI:CreateBrowserTabContent(parent, tab)
    local browserContent = Instance.new("Frame")
    browserContent.Name = "BrowserContent"
    browserContent.Size = UDim2.new(1, 0, 1, 0)
    browserContent.Position = UDim2.new(0, 0, 0, 0)
    browserContent.BackgroundTransparency = 1
    browserContent.Visible = false
    browserContent.Parent = parent
    
    -- Search box
    local searchBox = Instance.new("TextBox")
    searchBox.Name = "SearchBox"
    searchBox.Size = UDim2.new(1, -100, 0, 25)
    searchBox.Position = UDim2.new(0, 0, 0, 0)
    searchBox.BackgroundColor3 = defaultTheme.BackgroundColor
    searchBox.BorderColor3 = defaultTheme.BorderColor
    searchBox.Text = "Search servers..."
    searchBox.TextColor3 = defaultTheme.TextColor
    searchBox.TextScaled = true
    searchBox.Font = Enum.Font.Gotham
    searchBox.PlaceholderText = "Search servers..."
    searchBox.Parent = browserContent
    
    -- Refresh button
    local refreshButton = Instance.new("TextButton")
    refreshButton.Name = "RefreshButton"
    refreshButton.Size = UDim2.new(0, 80, 0, 25)
    refreshButton.Position = UDim2.new(1, -80, 0, 0)
    refreshButton.BackgroundColor3 = defaultTheme.PrimaryColor
    refreshButton.BorderSizePixel = 0
    refreshButton.Text = "Refresh"
    refreshButton.TextColor3 = defaultTheme.TextColor
    refreshButton.TextScaled = true
    refreshButton.Font = Enum.Font.Gotham
    refreshButton.Parent = browserContent
    
    -- Server list
    local serverList = Instance.new("ScrollingFrame")
    serverList.Name = "ServerList"
    serverList.Size = UDim2.new(1, 0, 1, -35)
    serverList.Position = UDim2.new(0, 0, 0, 35)
    serverList.BackgroundColor3 = defaultTheme.BackgroundColor
    serverList.BorderColor3 = defaultTheme.BorderColor
    serverList.ScrollBarThickness = 8
    serverList.Parent = browserContent
    
    -- Add server list content
    local listLayout = Instance.new("UIListLayout")
    listLayout.SortOrder = Enum.SortOrder.LayoutOrder
    listLayout.Padding = UDim.new(0, 2)
    listLayout.Parent = serverList
end

function UI:CreateSettingsTabContent(parent, tab)
    local settingsContent = Instance.new("Frame")
    settingsContent.Name = "SettingsContent"
    settingsContent.Size = UDim2.new(1, 0, 1, 0)
    settingsContent.Position = UDim2.new(0, 0, 0, 0)
    settingsContent.BackgroundTransparency = 1
    settingsContent.Visible = false
    settingsContent.Parent = parent
    
    local settingsLabel = Instance.new("TextLabel")
    settingsLabel.Name = "SettingsLabel"
    settingsLabel.Size = UDim2.new(1, 0, 1, 0)
    settingsLabel.Position = UDim2.new(0, 0, 0, 0)
    settingsLabel.BackgroundTransparency = 1
    settingsLabel.Text = "Settings\n\nComing Soon!"
    settingsLabel.TextColor3 = defaultTheme.TextColor
    settingsLabel.TextScaled = true
    settingsLabel.Font = Enum.Font.Gotham
    settingsLabel.TextXAlignment = Enum.TextXAlignment.Center
    settingsLabel.TextYAlignment = Enum.TextYAlignment.Center
    settingsLabel.Parent = settingsContent
end

function UI:CreateToolbarButton(screenGui, mainFrame)
    local Players = game:GetService("Players")
    local TweenService = game:GetService("TweenService")
    
    -- Create toolbar button
    local toolbarButton = Instance.new("TextButton")
    toolbarButton.Name = "ToolbarButton"
    toolbarButton.Size = UDim2.new(0, 50, 0, 50)
    toolbarButton.Position = UDim2.new(0, 10, 0, 10)
    toolbarButton.BackgroundColor3 = defaultTheme.PrimaryColor
    toolbarButton.BorderSizePixel = 0
    toolbarButton.Text = "SM"
    toolbarButton.TextColor3 = defaultTheme.TextColor
    toolbarButton.TextScaled = true
    toolbarButton.Font = Enum.Font.GothamBold
    toolbarButton.Parent = screenGui
    
    -- Add rounded corners
    local corner = Instance.new("UICorner")
    corner.CornerRadius = UDim.new(0, 8)
    corner.Parent = toolbarButton
    
    -- Button click functionality
    toolbarButton.MouseButton1Click:Connect(function()
        mainFrame.Visible = not mainFrame.Visible
    end)
    
    -- Hover effects
    toolbarButton.MouseEnter:Connect(function()
        local tween = TweenService:Create(toolbarButton, TweenInfo.new(0.2), {
            BackgroundColor3 = Color3.fromRGB(0, 100, 180)
        })
        tween:Play()
    end)
    
    toolbarButton.MouseLeave:Connect(function()
        local tween = TweenService:Create(toolbarButton, TweenInfo.new(0.2), {
            BackgroundColor3 = defaultTheme.PrimaryColor
        })
        tween:Play()
    end)
end

function UI:SwitchTab(tabName)
    local mainWindow = activeWindows["MainWindow"]
    if not mainWindow then return end
    
    local contentFrame = mainWindow.Frame:FindFirstChild("ContentFrame")
    if not contentFrame then return end
    
    local tabContent = contentFrame:FindFirstChild("TabContent")
    if not tabContent then return end
    
    -- Hide all tab content
    for _, child in pairs(tabContent:GetChildren()) do
        if child:IsA("Frame") and child.Name:find("Content") then
            child.Visible = false
        end
    end
    
    -- Show selected tab content
    local selectedContent = tabContent:FindFirstChild(tabName .. "Content")
    if selectedContent then
        selectedContent.Visible = true
    end
    
    -- Update tab appearance
    local tabFrame = contentFrame:FindFirstChild("TabFrame")
    if tabFrame then
        for _, child in pairs(tabFrame:GetChildren()) do
            if child:IsA("TextButton") then
                if child.Name == tabName .. "Tab" then
                    child.BackgroundColor3 = defaultTheme.PrimaryColor
                else
                    child.BackgroundColor3 = defaultTheme.SecondaryColor
                end
            end
        end
    end
end

function UI:ShowNotification(title, message, type)
    type = type or "info"
    
    local Players = game:GetService("Players")
    local TweenService = game:GetService("TweenService")
    
    -- Create notification GUI
    local notificationGui = Instance.new("ScreenGui")
    notificationGui.Name = "SocietixMNotification"
    notificationGui.Parent = Players.LocalPlayer:WaitForChild("PlayerGui")
    
    local notificationFrame = Instance.new("Frame")
    notificationFrame.Name = "NotificationFrame"
    notificationFrame.Size = UDim2.new(0, 300, 0, 80)
    notificationFrame.Position = UDim2.new(1, -320, 0, 10)
    notificationFrame.BackgroundColor3 = defaultTheme.BackgroundColor
    notificationFrame.BorderSizePixel = 0
    notificationFrame.Parent = notificationGui
    
    -- Add rounded corners
    local corner = Instance.new("UICorner")
    corner.CornerRadius = UDim.new(0, 8)
    corner.Parent = notificationFrame
    
    -- Title
    local titleLabel = Instance.new("TextLabel")
    titleLabel.Name = "TitleLabel"
    titleLabel.Size = UDim2.new(1, -10, 0, 20)
    titleLabel.Position = UDim2.new(0, 10, 0, 5)
    titleLabel.BackgroundTransparency = 1
    titleLabel.Text = title
    titleLabel.TextColor3 = defaultTheme.TextColor
    titleLabel.TextScaled = true
    titleLabel.Font = Enum.Font.GothamBold
    titleLabel.TextXAlignment = Enum.TextXAlignment.Left
    titleLabel.Parent = notificationFrame
    
    -- Message
    local messageLabel = Instance.new("TextLabel")
    messageLabel.Name = "MessageLabel"
    messageLabel.Size = UDim2.new(1, -10, 1, -30)
    messageLabel.Position = UDim2.new(0, 10, 0, 25)
    messageLabel.BackgroundTransparency = 1
    messageLabel.Text = message
    messageLabel.TextColor3 = defaultTheme.TextColor
    messageLabel.TextScaled = true
    messageLabel.Font = Enum.Font.Gotham
    messageLabel.TextXAlignment = Enum.TextXAlignment.Left
    messageLabel.TextYAlignment = Enum.TextYAlignment.Top
    messageLabel.Parent = notificationFrame
    
    -- Set color based on type
    local color = defaultTheme.PrimaryColor
    if type == "error" then
        color = defaultTheme.ErrorColor
    elseif type == "warning" then
        color = defaultTheme.WarningColor
    elseif type == "success" then
        color = defaultTheme.SuccessColor
    end
    
    -- Add colored border
    local border = Instance.new("Frame")
    border.Name = "Border"
    border.Size = UDim2.new(0, 4, 1, 0)
    border.Position = UDim2.new(0, 0, 0, 0)
    border.BackgroundColor3 = color
    border.BorderSizePixel = 0
    border.Parent = notificationFrame
    
    -- Animate in
    local tween = TweenService:Create(notificationFrame, TweenInfo.new(0.3, Enum.EasingStyle.Back), {
        Position = UDim2.new(1, -310, 0, 10)
    })
    tween:Play()
    
    -- Auto remove after 5 seconds
    game:GetService("Debris"):AddItem(notificationGui, 5)
end

function UI:UpdateServerStatus(isRunning, serverInfo)
    local mainWindow = activeWindows["MainWindow"]
    if not mainWindow then return end
    
    local serverContent = mainWindow.Frame:FindFirstChild("ContentFrame"):FindFirstChild("TabContent"):FindFirstChild("ServerContent")
    if not serverContent then return end
    
    local statusLabel = serverContent:FindFirstChild("StatusLabel")
    if statusLabel then
        statusLabel.Text = "Server Status: " .. (isRunning and "Running" or "Not Running")
        statusLabel.TextColor3 = isRunning and defaultTheme.SuccessColor or defaultTheme.ErrorColor
    end
    
    local infoLabel = serverContent:FindFirstChild("InfoLabel")
    if infoLabel and serverInfo then
        infoLabel.Text = string.format("Server ID: %s\nSocietix ID: %s\nPlayers: %d/%d", 
            serverInfo.Id or "None",
            serverInfo.SocietixId or "None",
            serverInfo.PlayerCount or 0,
            serverInfo.MaxPlayers or 20
        )
    end
end

function UI:Cleanup()
    for name, window in pairs(activeWindows) do
        if window.ScreenGui then
            window.ScreenGui:Destroy()
        end
    end
    activeWindows = {}
end

return UI
