script.lua2

Pasted Nov 12, 2026, 5:47 PM1 file2,484 lines

Scan to open on your phone

Point a camera at the QR code - it opens this exact paste, no app needed.

https://codepastes.com/zzgs6pa6jzhbd6qt
script.lua2
--//========================================================
--// NX 3D SCI-FI ROBLOX BUBBLE CHAT DISPLAY
--// V16.0 - ZYNOVA SYNTAX FIXED
--// Based on the V16.0 source supplied in chat.
--// Only HTML-escaped comparison operators were decoded:
--// Encoded comparison operators have been converted to standard Luau symbols.
--//========================================================

-- SERVICES
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local TweenService = game:GetService("TweenService")
local TextChatService = game:GetService("TextChatService")
local UserInputService = game:GetService("UserInputService")
local TextService = game:GetService("TextService")
local Workspace = game:GetService("Workspace")
local VoiceChatService = game:GetService("VoiceChatService")

-- LOCAL PLAYER
local LocalPlayer = Players.LocalPlayer
if not LocalPlayer then return end
local PlayerGui = LocalPlayer:WaitForChild("PlayerGui")

-- CONFIG
local CONFIG = {
    Distance = 5.8,
    ScreenX = 0.34,
    ScreenY = 0.58,
    PanelWidth = 7.8,
    PanelHeight = 4.25,
    CanvasX = 1000,
    CanvasY = 590,
    MaxChatMessages = 35,
    MaxEvents = 35,
    MaxStatusPlayers = 50,
    MessageTextSize = 27,
    PlayerNameTextSize = 20,
    UsernameTextSize = 18,
    EventTitleTextSize = 10,
    EventPlayerTextSize = 20,
    StatusNameTextSize = 17,
    StatusUsernameTextSize = 9,
    StatusHPTextSize = 15,
    StatusInfoTextSize = 8,
    StatusCardHeight = 90,
    StatusUpdateRate = 0.15,
    VoiceCheckInterval = 2.0,
    VoiceInputWait = 1.0,
    VoiceActivityThresholdPeak = 0.055,
    VoiceActivityThresholdRMS = 0.018,
    VoiceHoldTime = 0.20,
    VoiceAnalyzerUpdateRate = 0.08,
    CategoryHeight = 25,
    CategoryGap = 5,
    FollowSpeed = 16,
    WorldYaw = math.rad(10),
    WorldPitch = math.rad(-3.5),
    WorldRoll = math.rad(0.8),
    CameraSway = true,
    MovementSway = true,
    MaxPitch = math.rad(1.8),
    MaxYaw = math.rad(2.5),
    MaxRoll = math.rad(2.2),
    MessageTweenTime = 0.28,
    TypeSpeed = 0.012,
    OpenTime = 0.32,
    CloseTime = 0.24,
    HideButtonWidth = 55,
    HideButtonHeight = 32,
    ButtonWidth = 124,
    ButtonHeight = 42,
    ButtonBottomOffset = 185,
    ButtonLeftOffset = 20,
    DragHoldTime = 0.10,
    DragMoveThreshold = 3,
    DuplicateTime = 0.85,
    SpectateEnabled = true,
    SpectateCameraType = Enum.CameraType.Follow,
    SpectateStreamTimeout = 2.0,
    SpectateStreamRefresh = 0.90,
    SpectateStreamMoveThreshold = 65,
    SpectateButtonWidth = 88,
    SpectateButtonHeight = 12,
    MainColor = Color3.fromRGB(70, 215, 255),
    SecondaryColor = Color3.fromRGB(135, 235, 255),
    LightBlue = Color3.fromRGB(175, 240, 255),
    VeryLightBlue = Color3.fromRGB(215, 250, 255),
    White = Color3.fromRGB(235, 250, 255),
    JoinColor = Color3.fromRGB(248, 250, 255),
    LeaveColor = Color3.fromRGB(255, 205, 208),
    LeaveAccent = Color3.fromRGB(255, 105, 115),
    HealthGood = Color3.fromRGB(125, 245, 255),
    HealthMedium = Color3.fromRGB(255, 222, 135),
    HealthLow = Color3.fromRGB(255, 125, 135),
    NoCharacter = Color3.fromRGB(130, 190, 205),
    VoiceReady = Color3.fromRGB(145, 240, 255),
    VoiceSpeaking = Color3.fromRGB(225, 255, 255),
    VoiceMuted = Color3.fromRGB(170, 185, 195),
    VoiceNotExposed = Color3.fromRGB(110, 160, 175),
    VoiceOff = Color3.fromRGB(90, 105, 112),
    ChatDark = Color3.fromRGB(5, 17, 24),
    EventJoinDark = Color3.fromRGB(8, 18, 24),
    EventLeaveDark = Color3.fromRGB(28, 12, 16),
    StatusDark = Color3.fromRGB(4, 17, 24),
    StatusPanelDark = Color3.fromRGB(5, 20, 28),
    ButtonBase = Color3.fromRGB(5, 22, 30),
    ButtonGradientDark = Color3.fromRGB(2, 11, 18),
    ButtonGradientMid = Color3.fromRGB(45, 145, 175),
    ButtonGradientLight = Color3.fromRGB(220, 250, 255),
    ButtonGradientCyan = Color3.fromRGB(70, 215, 255),
    BackgroundTransparency = 0.11,
    CardTransparency = 0.20,
}

-- SAFE DESTROY
local function DestroySafe(Object)
    if not Object then return end
    pcall(function() Object:Destroy() end)
end

-- CLEAN OLD
DestroySafe(Workspace:FindFirstChild("NX_3D_SciFiChat"))
DestroySafe(Workspace:FindFirstChild("NX_3D_SciFiChat_VoiceMonitor"))
DestroySafe(PlayerGui:FindFirstChild("NX_3D_SciFiChat_Control"))
DestroySafe(PlayerGui:FindFirstChild("SciFiChatSurface"))

-- WORLD FOLDER
local Folder = Instance.new("Folder")
Folder.Name = "NX_3D_SciFiChat"
Folder.Parent = Workspace

-- VOICE MONITOR FOLDER
local VoiceMonitorFolder = Instance.new("Folder")
VoiceMonitorFolder.Name = "NX_3D_SciFiChat_VoiceMonitor"
VoiceMonitorFolder.Parent = Workspace

-- PANEL
local Panel = Instance.new("Part")
Panel.Name = "ChatDisplay3D"
Panel.Size = Vector3.new(CONFIG.PanelWidth, CONFIG.PanelHeight, 0.08)
Panel.Anchored = true
Panel.CanCollide = false
Panel.CanTouch = false
Panel.CanQuery = true
Panel.CastShadow = false
Panel.Transparency = 1
Panel.Parent = Folder

-- SURFACE
local Surface = Instance.new("SurfaceGui")
Surface.Name = "SciFiChatSurface"
Surface.Adornee = Panel
Surface.Face = Enum.NormalId.Back
Surface.AlwaysOnTop = true
Surface.LightInfluence = 0
Surface.Active = true
Surface.ZIndexBehavior = Enum.ZIndexBehavior.Sibling
Surface.SizingMode = Enum.SurfaceGuiSizingMode.FixedSize
Surface.CanvasSize = Vector2.new(CONFIG.CanvasX, CONFIG.CanvasY)
Surface.Enabled = true
Surface.Parent = PlayerGui

-- ROOT
local Root = Instance.new("CanvasGroup")
Root.Name = "Root"
Root.Size = UDim2.fromScale(1, 1)
Root.BackgroundTransparency = 1
Root.GroupTransparency = 0
Root.Parent = Surface

-- BACKGROUND
local Background = Instance.new("Frame")
Background.Name = "Background"
Background.Size = UDim2.fromScale(1, 1)
Background.BackgroundColor3 = Color3.fromRGB(3, 10, 16)
Background.BackgroundTransparency = CONFIG.BackgroundTransparency
Background.BorderSizePixel = 0
Background.Parent = Root
local BackgroundCorner = Instance.new("UICorner")
BackgroundCorner.CornerRadius = UDim.new(0, 15)
BackgroundCorner.Parent = Background
local BackgroundStroke = Instance.new("UIStroke")
BackgroundStroke.Color = CONFIG.MainColor
BackgroundStroke.Thickness = 1.8
BackgroundStroke.Transparency = 0.20
BackgroundStroke.Parent = Background

-- BACKGROUND GRADIENT
local Gradient = Instance.new("UIGradient")
Gradient.Rotation = 90
Gradient.Color = ColorSequence.new({
    ColorSequenceKeypoint.new(0, Color3.fromRGB(8, 25, 34)),
    ColorSequenceKeypoint.new(0.5, Color3.fromRGB(2, 9, 15)),
    ColorSequenceKeypoint.new(1, Color3.fromRGB(5, 18, 24)),
})
Gradient.Parent = Background

-- HEADER
local Header = Instance.new("Frame")
Header.Position = UDim2.new(0, 14, 0, 10)
Header.Size = UDim2.new(1, -28, 0, 48)
Header.BackgroundTransparency = 1
Header.Parent = Root

-- TITLE
local Title = Instance.new("TextLabel")
Title.Size = UDim2.new(0.60, 0, 0, 24)
Title.BackgroundTransparency = 1
Title.Text = "NX // COMMUNICATION"
Title.TextColor3 = CONFIG.White
Title.TextSize = 17
Title.Font = Enum.Font.GothamBold
Title.TextXAlignment = Enum.TextXAlignment.Left
Title.Parent = Header

-- SUBTITLE
local Subtitle = Instance.new("TextLabel")
Subtitle.Position = UDim2.new(0, 1, 0, 25)
Subtitle.Size = UDim2.new(0.65, 0, 0, 14)
Subtitle.BackgroundTransparency = 1
Subtitle.Text = "ROBLOX BUBBLE CHAT // LIVE"
Subtitle.TextColor3 = CONFIG.SecondaryColor
Subtitle.TextTransparency = 0.12
Subtitle.TextSize = 8
Subtitle.Font = Enum.Font.GothamMedium
Subtitle.TextXAlignment = Enum.TextXAlignment.Left
Subtitle.Parent = Header

-- ONLINE STATUS
local Status = Instance.new("Frame")
Status.AnchorPoint = Vector2.new(1, 0.5)
Status.Position = UDim2.new(1, -62, 0.5, 0)
Status.Size = UDim2.new(0, 190, 0, 20)
Status.BackgroundTransparency = 1
Status.Parent = Header
local StatusDot = Instance.new("Frame")
StatusDot.Position = UDim2.new(0, 0, 0.5, -3)
StatusDot.Size = UDim2.new(0, 6, 0, 6)
StatusDot.BackgroundColor3 = CONFIG.MainColor
StatusDot.BorderSizePixel = 0
StatusDot.Parent = Status
local DotCorner = Instance.new("UICorner")
DotCorner.CornerRadius = UDim.new(1, 0)
DotCorner.Parent = StatusDot
local StatusText = Instance.new("TextLabel")
StatusText.Position = UDim2.new(0, 11, 0, 0)
StatusText.Size = UDim2.new(1, -11, 1, 0)
StatusText.BackgroundTransparency = 1
StatusText.Text = "ONLINE // 0 // VOICE OFF"
StatusText.TextColor3 = CONFIG.SecondaryColor
StatusText.TextSize = 8
StatusText.Font = Enum.Font.GothamBold
StatusText.TextXAlignment = Enum.TextXAlignment.Left
StatusText.Parent = Status

-- HEADER LINE
local HeaderLine = Instance.new("Frame")
HeaderLine.Position = UDim2.new(0, 0, 1, -1)
HeaderLine.Size = UDim2.new(1, 0, 0, 1)
HeaderLine.BackgroundColor3 = CONFIG.MainColor
HeaderLine.BackgroundTransparency = 0.35
HeaderLine.BorderSizePixel = 0
HeaderLine.Parent = Header

-- HIDE BUTTON
local HideButton = Instance.new("TextButton")
HideButton.Name = "HideWindowButton"
HideButton.Active = true
HideButton.Selectable = true
HideButton.AutoButtonColor = false
HideButton.AnchorPoint = Vector2.new(1, 0)
HideButton.Position = UDim2.new(1, -12, 0, 9)
HideButton.Size = UDim2.new(0, CONFIG.HideButtonWidth, 0, CONFIG.HideButtonHeight)
HideButton.BackgroundColor3 = Color3.fromRGB(5, 19, 27)
HideButton.BackgroundTransparency = 0.05
HideButton.BorderSizePixel = 0
HideButton.Text = ""
HideButton.ZIndex = 100
HideButton.Parent = Root
local HideCorner = Instance.new("UICorner")
HideCorner.CornerRadius = UDim.new(0, 8)
HideCorner.Parent = HideButton
local HideStroke = Instance.new("UIStroke")
HideStroke.Color = CONFIG.MainColor
HideStroke.Thickness = 1.5
HideStroke.Transparency = 0.15
HideStroke.Parent = HideButton
local HideIcon = Instance.new("TextLabel")
HideIcon.Size = UDim2.fromScale(1, 1)
HideIcon.BackgroundTransparency = 1
HideIcon.Text = "−"
HideIcon.TextColor3 = CONFIG.MainColor
HideIcon.TextSize = 21
HideIcon.Font = Enum.Font.GothamBold
HideIcon.TextXAlignment = Enum.TextXAlignment.Center
HideIcon.TextYAlignment = Enum.TextYAlignment.Center
HideIcon.ZIndex = 101
HideIcon.Parent = HideButton

local function PressHideVisual()
    TweenService:Create(HideButton, TweenInfo.new(0.08, Enum.EasingStyle.Quad, Enum.EasingDirection.Out), {
        Size = UDim2.new(0, 50, 0, 29), BackgroundTransparency = 0,
    }):Play()
    TweenService:Create(HideIcon, TweenInfo.new(0.08, Enum.EasingStyle.Quad, Enum.EasingDirection.Out), {
        TextColor3 = CONFIG.White,
    }):Play()
end

local function ReleaseHideVisual()
    TweenService:Create(HideButton, TweenInfo.new(0.14, Enum.EasingStyle.Back, Enum.EasingDirection.Out), {
        Size = UDim2.new(0, CONFIG.HideButtonWidth, 0, CONFIG.HideButtonHeight),
        BackgroundTransparency = 0.05,
    }):Play()
    TweenService:Create(HideIcon, TweenInfo.new(0.12, Enum.EasingStyle.Quad, Enum.EasingDirection.Out), {
        TextColor3 = CONFIG.MainColor,
    }):Play()
end

HideButton.InputBegan:Connect(function(Input)
    if Input.UserInputType == Enum.UserInputType.Touch or Input.UserInputType == Enum.UserInputType.MouseButton1 then
        PressHideVisual()
    end
end)
HideButton.InputEnded:Connect(function(Input)
    if Input.UserInputType == Enum.UserInputType.Touch or Input.UserInputType == Enum.UserInputType.MouseButton1 then
        ReleaseHideVisual()
    end
end)

-- SCAN LINE
local Scan = Instance.new("Frame")
Scan.Name = "ScanLine"
Scan.Position = UDim2.new(-0.02, 0, 0, 8)
Scan.Size = UDim2.new(0, 1, 1, -16)
Scan.BackgroundColor3 = CONFIG.MainColor
Scan.BackgroundTransparency = 0.78
Scan.BorderSizePixel = 0
Scan.ZIndex = 20
Scan.Parent = Root

task.spawn(function()
    while Scan.Parent do
        Scan.Position = UDim2.new(-0.02, 0, 0, 8)
        local T = TweenService:Create(Scan, TweenInfo.new(2, Enum.EasingStyle.Sine, Enum.EasingDirection.InOut), {
            Position = UDim2.new(1.02, 0, 0, 8),
        })
        T:Play()
        T.Completed:Wait()
        task.wait(0.22)
    end
end)

-- TITLES
local LeftTitle = Instance.new("TextLabel")
LeftTitle.Position = UDim2.new(0, 18, 0, 66)
LeftTitle.Size = UDim2.new(0.62, -20, 0, 22)
LeftTitle.BackgroundTransparency = 1
LeftTitle.Text = "ROBLOX CHAT"
LeftTitle.TextColor3 = CONFIG.MainColor
LeftTitle.TextSize = 10
LeftTitle.Font = Enum.Font.GothamBold
LeftTitle.TextXAlignment = Enum.TextXAlignment.Left
LeftTitle.Parent = Root

local RightTitle = Instance.new("TextLabel")
RightTitle.Position = UDim2.new(0.63, 8, 0, 61)
RightTitle.Size = UDim2.new(0.22, 0, 0, 22)
RightTitle.BackgroundTransparency = 1
RightTitle.Text = "PLAYER EVENTS"
RightTitle.TextColor3 = CONFIG.MainColor
RightTitle.TextSize = 10
RightTitle.Font = Enum.Font.GothamBold
RightTitle.TextXAlignment = Enum.TextXAlignment.Left
RightTitle.Parent = Root

local RightCount = Instance.new("TextLabel")
RightCount.AnchorPoint = Vector2.new(1, 0)
RightCount.Position = UDim2.new(1, -19, 0, 61)
RightCount.Size = UDim2.new(0, 130, 0, 22)
RightCount.BackgroundTransparency = 1
RightCount.Text = "0 / 0 PLAYERS"
RightCount.TextColor3 = CONFIG.LightBlue
RightCount.TextSize = 8
RightCount.Font = Enum.Font.GothamBold
RightCount.TextXAlignment = Enum.TextXAlignment.Right
RightCount.Parent = Root

-- CATEGORY BAR
local CategoryBar = Instance.new("Frame")
CategoryBar.Position = UDim2.new(0.625, 8, 0, 88)
CategoryBar.Size = UDim2.new(0.375, -21, 0, CONFIG.CategoryHeight)
CategoryBar.BackgroundTransparency = 1
CategoryBar.ZIndex = 25
CategoryBar.Parent = Root

-- CATEGORY 1
local Category1Button = Instance.new("TextButton")
Category1Button.Name = "Category1Events"
Category1Button.Position = UDim2.new(0, 0, 0, 0)
Category1Button.Size = UDim2.new(0.5, -2, 1, 0)
Category1Button.BackgroundColor3 = CONFIG.MainColor
Category1Button.BackgroundTransparency = 0.12
Category1Button.BorderSizePixel = 0
Category1Button.AutoButtonColor = false
Category1Button.Active = true
Category1Button.Selectable = true
Category1Button.Text = "01 // EVENTS"
Category1Button.TextColor3 = CONFIG.White
Category1Button.TextSize = 8
Category1Button.Font = Enum.Font.GothamBold
Category1Button.ZIndex = 26
Category1Button.Parent = CategoryBar
local Category1Corner = Instance.new("UICorner")
Category1Corner.CornerRadius = UDim.new(0, 6)
Category1Corner.Parent = Category1Button
local Category1Stroke = Instance.new("UIStroke")
Category1Stroke.Color = CONFIG.MainColor
Category1Stroke.Thickness = 1
Category1Stroke.Transparency = 0
Category1Stroke.Parent = Category1Button

-- CATEGORY 2
local Category2Button = Instance.new("TextButton")
Category2Button.Name = "Category2Status"
Category2Button.Position = UDim2.new(0.5, 3, 0, 0)
Category2Button.Size = UDim2.new(0.5, -3, 1, 0)
Category2Button.BackgroundColor3 = Color3.fromRGB(6, 22, 29)
Category2Button.BackgroundTransparency = 0.22
Category2Button.BorderSizePixel = 0
Category2Button.AutoButtonColor = false
Category2Button.Active = true
Category2Button.Selectable = true
Category2Button.Text = "02 // STATUS"
Category2Button.TextColor3 = CONFIG.SecondaryColor
Category2Button.TextSize = 8
Category2Button.Font = Enum.Font.GothamBold
Category2Button.ZIndex = 26
Category2Button.Parent = CategoryBar
local Category2Corner = Instance.new("UICorner")
Category2Corner.CornerRadius = UDim.new(0, 6)
Category2Corner.Parent = Category2Button
local Category2Stroke = Instance.new("UIStroke")
Category2Stroke.Color = CONFIG.MainColor
Category2Stroke.Thickness = 1
Category2Stroke.Transparency = 0.55
Category2Stroke.Parent = Category2Button

-- DIVIDER
local Divider = Instance.new("Frame")
Divider.Position = UDim2.new(0.625, 0, 0, 90)
Divider.Size = UDim2.new(0, 1, 1, -102)
Divider.BackgroundColor3 = CONFIG.MainColor
Divider.BackgroundTransparency = 0.55
Divider.BorderSizePixel = 0
Divider.Parent = Root

-- CHAT AREA
local ChatArea = Instance.new("ScrollingFrame")
ChatArea.Name = "RobloxBubbleChatHistory"
ChatArea.Position = UDim2.new(0, 13, 0, 91)
ChatArea.Size = UDim2.new(0.625, -19, 1, -101)
ChatArea.BackgroundTransparency = 1
ChatArea.BorderSizePixel = 0
ChatArea.ScrollBarThickness = 3
ChatArea.ScrollBarImageColor3 = CONFIG.MainColor
ChatArea.ScrollingDirection = Enum.ScrollingDirection.Y
ChatArea.AutomaticCanvasSize = Enum.AutomaticSize.Y
ChatArea.CanvasSize = UDim2.new(0, 0, 0, 0)
ChatArea.ElasticBehavior = Enum.ElasticBehavior.WhenScrollable
ChatArea.Active = true
ChatArea.Parent = Root

-- EVENT AREA
local EventArea = Instance.new("ScrollingFrame")
EventArea.Name = "PlayerEventHistory"
EventArea.Position = UDim2.new(0.625, 8, 0, 118)
EventArea.Size = UDim2.new(0.375, -21, 1, -128)
EventArea.BackgroundTransparency = 1
EventArea.BorderSizePixel = 0
EventArea.ScrollBarThickness = 3
EventArea.ScrollBarImageColor3 = CONFIG.MainColor
EventArea.ScrollingDirection = Enum.ScrollingDirection.Y
EventArea.AutomaticCanvasSize = Enum.AutomaticSize.Y
EventArea.CanvasSize = UDim2.new(0, 0, 0, 0)
EventArea.ElasticBehavior = Enum.ElasticBehavior.WhenScrollable
EventArea.Active = true
EventArea.Visible = true
EventArea.Parent = Root

-- PLAYER STATUS AREA
local PlayerStatusArea = Instance.new("ScrollingFrame")
PlayerStatusArea.Name = "PlayerStatusHistory"
PlayerStatusArea.Position = UDim2.new(0.625, 8, 0, 118)
PlayerStatusArea.Size = UDim2.new(0.375, -21, 1, -128)
PlayerStatusArea.BackgroundTransparency = 1
PlayerStatusArea.BorderSizePixel = 0
PlayerStatusArea.ScrollBarThickness = 3
PlayerStatusArea.ScrollBarImageColor3 = CONFIG.MainColor
PlayerStatusArea.ScrollingDirection = Enum.ScrollingDirection.Y
PlayerStatusArea.AutomaticCanvasSize = Enum.AutomaticSize.Y
PlayerStatusArea.CanvasSize = UDim2.new(0, 0, 0, 0)
PlayerStatusArea.ElasticBehavior = Enum.ElasticBehavior.WhenScrollable
PlayerStatusArea.Active = true
PlayerStatusArea.Visible = false
PlayerStatusArea.Parent = Root

-- PADDING
local ChatPadding = Instance.new("UIPadding")
ChatPadding.PaddingTop = UDim.new(0, 3)
ChatPadding.PaddingBottom = UDim.new(0, 6)
ChatPadding.PaddingLeft = UDim.new(0, 2)
ChatPadding.PaddingRight = UDim.new(0, 4)
ChatPadding.Parent = ChatArea
local EventPadding = Instance.new("UIPadding")
EventPadding.PaddingTop = UDim.new(0, 3)
EventPadding.PaddingBottom = UDim.new(0, 6)
EventPadding.PaddingLeft = UDim.new(0, 2)
EventPadding.PaddingRight = UDim.new(0, 3)
EventPadding.Parent = EventArea
local StatusPadding = Instance.new("UIPadding")
StatusPadding.PaddingTop = UDim.new(0, 3)
StatusPadding.PaddingBottom = UDim.new(0, 6)
StatusPadding.PaddingLeft = UDim.new(0, 2)
StatusPadding.PaddingRight = UDim.new(0, 3)
StatusPadding.Parent = PlayerStatusArea

-- LIST LAYOUT
local ChatLayout = Instance.new("UIListLayout")
ChatLayout.Padding = UDim.new(0, 7)
ChatLayout.SortOrder = Enum.SortOrder.LayoutOrder
ChatLayout.HorizontalAlignment = Enum.HorizontalAlignment.Center
ChatLayout.Parent = ChatArea
local EventLayout = Instance.new("UIListLayout")
EventLayout.Padding = UDim.new(0, 6)
EventLayout.SortOrder = Enum.SortOrder.LayoutOrder
EventLayout.HorizontalAlignment = Enum.HorizontalAlignment.Center
EventLayout.Parent = EventArea
local StatusLayout = Instance.new("UIListLayout")
StatusLayout.Padding = UDim.new(0, 6)
StatusLayout.SortOrder = Enum.SortOrder.LayoutOrder
StatusLayout.HorizontalAlignment = Enum.HorizontalAlignment.Center
StatusLayout.Parent = PlayerStatusArea

-- UTF8
local function Utf8Take(Text, Count)
    local Index = utf8.offset(Text, Count + 1)
    if Index then return string.sub(Text, 1, Index - 1) end
    return Text
end

-- CLEAN TEXT
local function CleanText(Text)
    if typeof(Text) ~= "string" then return "" end
    Text = Text:gsub("^%s+", ""):gsub("%s+$", "")
    return Text
end

-- AVATAR
local function GetAvatar(UserId)
    local Success, Image = pcall(function()
        return Players:GetUserThumbnailAsync(UserId, Enum.ThumbnailType.HeadShot, Enum.ThumbnailSize.Size100x100)
    end)
    if Success then return Image end
    return ""
end

-- STORAGE
local ChatObjects = {}
local EventObjects = {}
local PlayerStatusObjects = {}
local PlayerStatusHealthConnections = {}
local PlayerStatusCharacterConnections = {}
local VoiceMonitors = {}
local VoicePlayerConnections = {}
local DuplicateGuard = {}

-- PLAYER CAMERA STORAGE
local SpectateState = {
    Active = false,
    Target = nil,
    SavedCameraType = nil,
    SavedCameraSubject = nil,
    SavedCameraCFrame = nil,
    SavedFieldOfView = nil,
    LastStreamRequest = 0,
    LastStreamPosition = nil,
}

-- Created later with the 2D ControlGui. Kept separate from the 3D panel
-- so the user can always leave spectate mode even while the target moves.
local SpectateExitButton = nil

local LocalVoiceEnabled = false
local LastVoiceCheck = false

-- Forward declaration for references made before the function body.
local UpdatePlayerStatusCard

-- LOCAL VOICE CHECK
local function CheckLocalVoiceStatus()
    local Success, Enabled = pcall(function()
        return VoiceChatService:IsVoiceEnabledForUserIdAsync(LocalPlayer.UserId)
    end)
    if Success then
        LocalVoiceEnabled = Enabled == true
    else
        LocalVoiceEnabled = false
    end
    return LocalVoiceEnabled
end

-- FIND AUDIO DEVICE INPUT
local function FindAudioDeviceInput(Player)
    if not Player then return nil end
    local Input = Player:FindFirstChildWhichIsA("AudioDeviceInput")
    if Input then return Input end
    Input = Player:FindFirstChild("AudioDeviceInput")
    if Input and Input:IsA("AudioDeviceInput") then return Input end
    local Success, Result = pcall(function()
        for _, Descendant in ipairs(Player:GetDescendants()) do
            if Descendant:IsA("AudioDeviceInput") then return Descendant end
        end
        return nil
    end)
    if Success and Result then return Result end
    return nil
end

-- DESTROY VOICE MONITOR
local function DestroyVoiceMonitor(Player)
    local Data = VoiceMonitors[Player]
    if not Data then return end
    if Data.Wire then DestroySafe(Data.Wire) end
    if Data.Analyzer then DestroySafe(Data.Analyzer) end
    VoiceMonitors[Player] = nil
end

-- SETUP ANALYZER
local function SetupVoiceMonitor(Player)
    if not Player then return false end
    local Input = FindAudioDeviceInput(Player)
    if not Input then
        DestroyVoiceMonitor(Player)
        return false
    end
    local Existing = VoiceMonitors[Player]
    if Existing and Existing.Input == Input then return true end
    DestroyVoiceMonitor(Player)
    local Success, Data = pcall(function()
        local Analyzer = Instance.new("AudioAnalyzer")
        Analyzer.Name = "NX_VoiceAnalyzer_" .. tostring(Player.UserId)
        Analyzer.SpectrumEnabled = false
        Analyzer.Parent = VoiceMonitorFolder
        local Wire = Instance.new("Wire")
        Wire.Name = "NX_VoiceWire_" .. tostring(Player.UserId)
        Wire.SourceInstance = Input
        Wire.SourceName = "Output"
        Wire.TargetInstance = Analyzer
        Wire.TargetName = "Input"
        Wire.Parent = VoiceMonitorFolder
        return {
            Input = Input,
            Analyzer = Analyzer,
            Wire = Wire,
            SpeakingUntil = 0,
            LastPeak = 0,
            LastRMS = 0,
            AnalyzerWorking = true,
        }
    end)
    if not Success then
        VoiceMonitors[Player] = {
            Input = Input,
            Analyzer = nil,
            Wire = nil,
            SpeakingUntil = 0,
            LastPeak = 0,
            LastRMS = 0,
            AnalyzerWorking = false,
        }
        return false
    end
    VoiceMonitors[Player] = Data
    return true
end

-- BIND VOICE PLAYER
local function BindVoicePlayer(Player)
    if not Player then return end
    local Old = VoicePlayerConnections[Player]
    if Old then pcall(function() Old:Disconnect() end) end
    VoicePlayerConnections[Player] = nil
    task.defer(function() SetupVoiceMonitor(Player) end)
    VoicePlayerConnections[Player] = Player.ChildAdded:Connect(function(Child)
        if Child:IsA("AudioDeviceInput") or Child.Name == "AudioDeviceInput" then
            task.defer(function()
                SetupVoiceMonitor(Player)
                if UpdatePlayerStatusCard then UpdatePlayerStatusCard(Player) end
            end)
        end
    end)
end

-- VOICE DATA
local function GetVoiceData(Player)
    if Player == LocalPlayer and not LocalVoiceEnabled then
        return {
            State = "VOICE // OFF", Color = CONFIG.VoiceOff,
            Active = false, Ready = false, Linked = false,
            AnalyzerAvailable = false,
        }
    end
    local Input = FindAudioDeviceInput(Player)
    if Input then
        if not VoiceMonitors[Player] then SetupVoiceMonitor(Player) end
    else
        if Player == LocalPlayer then
            return {
                State = "MIC // LINKED", Color = CONFIG.VoiceReady,
                Active = false, Ready = true, Linked = true,
                AnalyzerAvailable = false,
            }
        end
        return {
            State = "MIC // NOT EXPOSED", Color = CONFIG.VoiceNotExposed,
            Active = false, Ready = false, Linked = false,
            AnalyzerAvailable = false,
        }
    end
    local Monitor = VoiceMonitors[Player]
    if not Monitor then
        if Player == LocalPlayer then
            return {
                State = "MIC // LINKED", Color = CONFIG.VoiceReady,
                Active = false, Ready = true, Linked = true,
                AnalyzerAvailable = false,
            }
        end
        return {
            State = "MIC // READY", Color = CONFIG.VoiceReady,
            Active = false, Ready = true, Linked = false,
            AnalyzerAvailable = false,
        }
    end
    local Muted = false
    pcall(function() Muted = Input.Muted == true end)
    local Peak = 0
    local RMS = 0
    local AnalyzerAvailable = false
    if Monitor.Analyzer and Monitor.Analyzer.Parent then
        AnalyzerAvailable = true
        pcall(function()
            Peak = Monitor.Analyzer.PeakLevel
            RMS = Monitor.Analyzer.RmsLevel
        end)
    end
    Monitor.LastPeak = Peak
    Monitor.LastRMS = RMS
    local Now = os.clock()
    if not Muted and AnalyzerAvailable and (
        Peak >= CONFIG.VoiceActivityThresholdPeak
        or RMS >= CONFIG.VoiceActivityThresholdRMS
    ) then
        Monitor.SpeakingUntil = Now + CONFIG.VoiceHoldTime
    end
    if not Muted and Monitor.SpeakingUntil and Now <= Monitor.SpeakingUntil then
        return {
            State = "MIC // SPEAKING", Color = CONFIG.VoiceSpeaking,
            Active = true, Ready = true,
            Linked = Player == LocalPlayer,
            AnalyzerAvailable = AnalyzerAvailable,
        }
    end
    if Muted then
        return {
            State = "MIC // MUTED", Color = CONFIG.VoiceMuted,
            Active = false, Ready = true,
            Linked = Player == LocalPlayer,
            AnalyzerAvailable = AnalyzerAvailable,
        }
    end
    if Player == LocalPlayer then
        return {
            State = "MIC // LINKED", Color = CONFIG.VoiceReady,
            Active = false, Ready = true, Linked = true,
            AnalyzerAvailable = AnalyzerAvailable,
        }
    end
    return {
        State = "MIC // READY", Color = CONFIG.VoiceReady,
        Active = false, Ready = true, Linked = false,
        AnalyzerAvailable = AnalyzerAvailable,
    }
end

-- VOICE HEADER
local function UpdateVoiceHeader()
    local Count = #Players:GetPlayers()
    if LocalVoiceEnabled then
        StatusText.Text = "ONLINE // " .. tostring(Count) .. " // VOICE LINKED"
        StatusText.TextColor3 = CONFIG.VoiceReady
        StatusDot.BackgroundColor3 = CONFIG.VoiceReady
        Subtitle.Text = "ROBLOX BUBBLE CHAT // VOICE LINKED"
    else
        StatusText.Text = "ONLINE // " .. tostring(Count) .. " // VOICE OFF"
        StatusText.TextColor3 = CONFIG.SecondaryColor
        StatusDot.BackgroundColor3 = CONFIG.MainColor
        Subtitle.Text = "ROBLOX BUBBLE CHAT // VOICE NOT LINKED"
    end
end

-- REFRESH VOICE
local function RefreshVoiceMonitors()
    for _, Player in ipairs(Players:GetPlayers()) do BindVoicePlayer(Player) end
    UpdateVoiceHeader()
end

-- DUPLICATE GUARD
local function AcceptBubbleMessage(Player, Text)
    if not Player then return false end
    Text = CleanText(Text)
    if Text == "" then return false end
    local Key = tostring(Player.UserId) .. "|" .. Text
    local Now = os.clock()
    local Last = DuplicateGuard[Key]
    if Last and Now - Last < CONFIG.DuplicateTime then return false end
    DuplicateGuard[Key] = Now
    return true
end

-- WIDTH
local function GetChatTextWidth()
    return math.max(260, math.floor(CONFIG.CanvasX * 0.625) - 90)
end
local function GetEventTextWidth()
    return math.max(150, math.floor(CONFIG.CanvasX * 0.375) - 55)
end

-- TEXT HEIGHT
local function GetTextHeight(Text, Width, Size)
    Text = Text or ""
    if Text == "" then return 22 end
    local Success, Bounds = pcall(function()
        return TextService:GetTextSize(Text, Size, Enum.Font.Gotham, Vector2.new(Width, 10000))
    end)
    if Success and Bounds then return math.max(22, Bounds.Y) end
    return 22
end

-- SCROLL
local function ScrollToBottom(Area)
    task.defer(function()
        if not Area or not Area.Parent then return end
        pcall(function()
            Area.CanvasPosition = Vector2.new(0, math.max(0, Area.AbsoluteCanvasSize.Y - Area.AbsoluteWindowSize.Y))
        end)
    end)
end

-- SWEEP
local function CreateSweep(Card, Accent, Duration)
    local Sweep = Instance.new("Frame")
    Sweep.Position = UDim2.new(-0.35, 0, 0, 0)
    Sweep.Size = UDim2.new(0, 55, 1, 0)
    Sweep.BackgroundColor3 = Accent
    Sweep.BackgroundTransparency = 0.86
    Sweep.BorderSizePixel = 0
    Sweep.Rotation = 12
    Sweep.ZIndex = 8
    Sweep.Parent = Card
    task.spawn(function()
        local T = TweenService:Create(Sweep, TweenInfo.new(Duration or 0.65, Enum.EasingStyle.Quint, Enum.EasingDirection.Out), {
            Position = UDim2.new(1.15, 0, 0, 0),
        })
        T:Play()
        T.Completed:Wait()
        DestroySafe(Sweep)
    end)
end

-- TRIM CHAT
local function TrimChatHistory()
    while #ChatObjects > CONFIG.MaxChatMessages do
        local Old = table.remove(ChatObjects, 1)
        DestroySafe(Old)
    end
end

-- TRIM EVENTS
local function TrimEventHistory()
    while #EventObjects > CONFIG.MaxEvents do
        local Old = table.remove(EventObjects, 1)
        DestroySafe(Old)
    end
end

-- HEALTH
local function GetPlayerHealthData(Player)
    local Character = Player.Character
    if not Character then
        return {
            Health = 0, MaxHealth = 0, Ratio = 0, Percent = 0,
            Color = CONFIG.NoCharacter, Status = "NO CHARACTER",
        }
    end
    local Humanoid = Character:FindFirstChildOfClass("Humanoid")
    if not Humanoid then
        return {
            Health = 0, MaxHealth = 0, Ratio = 0, Percent = 0,
            Color = CONFIG.NoCharacter, Status = "NO HUMANOID",
        }
    end
    local MaxHealth = math.max(Humanoid.MaxHealth, 1)
    local Health = math.clamp(Humanoid.Health, 0, MaxHealth)
    local Ratio = math.clamp(Health / MaxHealth, 0, 1)
    local Percent = math.floor(Ratio * 100 + 0.5)
    local HealthColor = CONFIG.HealthGood
    local HealthStatus = "STABLE"
    if Ratio <= 0 then
        HealthColor = CONFIG.HealthLow
        HealthStatus = "DOWN"
    elseif Ratio <= 0.30 then
        HealthColor = CONFIG.HealthLow
        HealthStatus = "CRITICAL"
    elseif Ratio <= 0.65 then
        HealthColor = CONFIG.HealthMedium
        HealthStatus = "WARNING"
    end
    return {
        Health = Health, MaxHealth = MaxHealth, Ratio = Ratio,
        Percent = Percent, Color = HealthColor, Status = HealthStatus,
    }
end

-- TEAM
local function GetPlayerTeamColor(Player)
    local Success, Result = pcall(function()
        if Player.Team then return Player.TeamColor.Color end
        return CONFIG.MainColor
    end)
    if Success and Result then return Result end
    return CONFIG.MainColor
end

-- COUNT
local function UpdatePlayerCount()
    local Count = #Players:GetPlayers()
    local MaxPlayers = 0
    pcall(function() MaxPlayers = Players.MaxPlayers end)
    if not MaxPlayers or MaxPlayers <= 0 then MaxPlayers = Count end
    RightCount.Text = tostring(Count) .. " / " .. tostring(MaxPlayers) .. " PLAYERS"
    UpdateVoiceHeader()
end

-- TARGET HUMANOID
local function GetPlayerHumanoid(Player)
    if not Player then return nil end
    local Character = Player.Character
    if not Character then return nil end
    return Character:FindFirstChildOfClass("Humanoid")
end

-- TARGET ROOT
local function GetPlayerRoot(Player)
    if not Player then return nil end
    local Character = Player.Character
    if not Character then return nil end
    return Character:FindFirstChild("HumanoidRootPart")
end

-- TARGET STREAM REQUEST
local function RequestTargetStreaming(Player, Force)
    if not SpectateState.Active then return end
    if SpectateState.Target ~= Player then return end
    if not Player or not Player.Parent then return end
    local RootPart = GetPlayerRoot(Player)
    if not RootPart then return end
    local Position = RootPart.Position
    local Now = os.clock()
    local LastPosition = SpectateState.LastStreamPosition
    local PositionChanged = true
    if LastPosition then
        PositionChanged = (LastPosition - Position).Magnitude >= CONFIG.SpectateStreamMoveThreshold
    end
    if not Force then
        if Now - SpectateState.LastStreamRequest < CONFIG.SpectateStreamRefresh then
            if not PositionChanged then return end
        end
    end
    SpectateState.LastStreamRequest = Now
    SpectateState.LastStreamPosition = Position
    if not Workspace.StreamingEnabled then return end
    task.spawn(function()
        pcall(function()
            LocalPlayer:RequestStreamAroundAsync(Position, CONFIG.SpectateStreamTimeout)
        end)
    end)
end

-- ATTACH CAMERA
local function AttachSpectateCamera(Player)
    if not SpectateState.Active then return false end
    if SpectateState.Target ~= Player then return false end
    local Camera = Workspace.CurrentCamera
    if not Camera then return false end
    local Humanoid = GetPlayerHumanoid(Player)
    if not Humanoid then return false end
    pcall(function()
        Camera.CameraType = CONFIG.SpectateCameraType
        Camera.CameraSubject = Humanoid
    end)
    return true
end

-- REFRESH SPECTATE BUTTONS
local function RefreshSpectateButtons()
    for Player, Data in pairs(PlayerStatusObjects) do
        if Data and Data.CameraButton and Data.CameraButton.Parent then
            local Active = SpectateState.Active and SpectateState.Target == Player
            if Player == LocalPlayer then
                Data.CameraButton.Text = "CAM // SELF"
                Data.CameraButton.Active = false
                Data.CameraButton.TextColor3 = CONFIG.NoCharacter
                Data.CameraStroke.Color = CONFIG.NoCharacter
                Data.CameraStroke.Transparency = 0.65
            elseif Active then
                Data.CameraButton.Text = "CAM // ACTIVE"
                Data.CameraButton.Active = true
                Data.CameraButton.TextColor3 = CONFIG.White
                Data.CameraStroke.Color = CONFIG.MainColor
                Data.CameraStroke.Transparency = 0
            else
                Data.CameraButton.Text = "CAM // VIEW"
                Data.CameraButton.Active = true
                Data.CameraButton.TextColor3 = CONFIG.SecondaryColor
                Data.CameraStroke.Color = CONFIG.MainColor
                Data.CameraStroke.Transparency = 0.45
            end
        end
    end
end

-- STOP SPECTATING
local function StopSpectating()
    local Camera = Workspace.CurrentCamera
    SpectateState.Active = false
    SpectateState.Target = nil
    SpectateState.LastStreamRequest = 0
    SpectateState.LastStreamPosition = nil
    if Camera then
        pcall(function()
            if SpectateState.SavedCameraType then
                Camera.CameraType = SpectateState.SavedCameraType
            end
            if SpectateState.SavedCameraSubject and SpectateState.SavedCameraSubject.Parent then
                Camera.CameraSubject = SpectateState.SavedCameraSubject
            else
                local Character = LocalPlayer.Character
                local Humanoid = Character and Character:FindFirstChildOfClass("Humanoid")
                if Humanoid then Camera.CameraSubject = Humanoid end
            end
            if SpectateState.SavedFieldOfView then
                Camera.FieldOfView = SpectateState.SavedFieldOfView
            end
            if SpectateState.SavedCameraCFrame then
                Camera.CFrame = SpectateState.SavedCameraCFrame
            end
        end)
    end
    SpectateState.SavedCameraType = nil
    SpectateState.SavedCameraSubject = nil
    SpectateState.SavedCameraCFrame = nil
    SpectateState.SavedFieldOfView = nil

    if SpectateExitButton and SpectateExitButton.Parent then
        SpectateExitButton.Visible = false
        SpectateExitButton.Text = "EXIT SPECTATE"
    end

    RefreshSpectateButtons()
end

-- START SPECTATING
local function StartSpectating(Player)
    if not CONFIG.SpectateEnabled then return end
    if not Player or Player == LocalPlayer or not Player.Parent then return end
    if SpectateState.Active and SpectateState.Target == Player then
        StopSpectating()
        return
    end
    if SpectateState.Active then StopSpectating() end
    local Camera = Workspace.CurrentCamera
    if not Camera then return end
    SpectateState.SavedCameraType = Camera.CameraType
    SpectateState.SavedCameraSubject = Camera.CameraSubject
    SpectateState.SavedCameraCFrame = Camera.CFrame
    SpectateState.SavedFieldOfView = Camera.FieldOfView
    SpectateState.Active = true
    SpectateState.Target = Player
    SpectateState.LastStreamRequest = 0
    SpectateState.LastStreamPosition = nil

    if SpectateExitButton and SpectateExitButton.Parent then
        local TargetLabel = Player.DisplayName or Player.Name
        SpectateExitButton.Text = "EXIT SPECTATE  //  " .. TargetLabel
        SpectateExitButton.Visible = true
    end

    RequestTargetStreaming(Player, true)
    AttachSpectateCamera(Player)
    task.spawn(function()
        for Index = 1, 20 do
            if not SpectateState.Active or SpectateState.Target ~= Player then return end
            if AttachSpectateCamera(Player) then return end
            task.wait(0.10)
        end
    end)
    RefreshSpectateButtons()
end

-- SPECTATE STREAM LOOP
task.spawn(function()
    while Root.Parent do
        task.wait(CONFIG.SpectateStreamRefresh)
        if SpectateState.Active and SpectateState.Target then
            local Player = SpectateState.Target
            if Player.Parent ~= Players then
                StopSpectating()
            else
                RequestTargetStreaming(Player, false)
                AttachSpectateCamera(Player)
            end
        end
    end
end)

-- STATUS CARD UPDATE
UpdatePlayerStatusCard = function(Player)
    local Data = PlayerStatusObjects[Player]
    if not Data or not Data.Card or not Data.Card.Parent then return end
    local Health = GetPlayerHealthData(Player)
    local TeamColor = GetPlayerTeamColor(Player)
    local Voice = GetVoiceData(Player)
    Data.Name.Text = Player.DisplayName or Player.Name
    Data.Username.Text = "@" .. Player.Name
    if Player.Team then
        Data.TeamText.Text = "TEAM // " .. Player.Team.Name
    else
        Data.TeamText.Text = "TEAM // DEFAULT"
    end
    Data.TeamDot.BackgroundColor3 = TeamColor
    Data.TeamStroke.Color = TeamColor
    Data.HealthText.Text = string.format("HP %d / %d", math.floor(Health.Health + 0.5), math.floor(Health.MaxHealth + 0.5))
    Data.PercentText.Text = tostring(Health.Percent) .. "% // " .. Health.Status
    Data.PercentText.TextColor3 = Health.Color
    Data.HealthDot.BackgroundColor3 = Health.Color
    Data.HealthStroke.Color = Health.Color
    Data.HealthFill.BackgroundColor3 = Health.Color
    Data.HealthFill.Size = UDim2.new(Health.Ratio, 0, 1, 0)
    Data.MicText.Text = Voice.State
    Data.MicText.TextColor3 = Voice.Color
    Data.MicDot.BackgroundColor3 = Voice.Color
    Data.MicStroke.Color = Voice.Color
    if Voice.Active then
        Data.MicDot.Size = UDim2.new(0, 10, 0, 10)
        Data.MicDot.Position = UDim2.new(0, 59, 0, 61)
    else
        Data.MicDot.Size = UDim2.new(0, 7, 0, 7)
        Data.MicDot.Position = UDim2.new(0, 61, 0, 63)
    end
    if Data.CameraButton then
        if Player == LocalPlayer then
            Data.CameraButton.Text = "CAM // SELF"
            Data.CameraButton.Active = false
            Data.CameraButton.TextColor3 = CONFIG.NoCharacter
            Data.CameraStroke.Color = CONFIG.NoCharacter
            Data.CameraStroke.Transparency = 0.65
        elseif SpectateState.Active and SpectateState.Target == Player then
            Data.CameraButton.Text = "CAM // ACTIVE"
            Data.CameraButton.Active = true
            Data.CameraButton.TextColor3 = CONFIG.White
            Data.CameraStroke.Color = CONFIG.MainColor
            Data.CameraStroke.Transparency = 0
        else
            Data.CameraButton.Text = "CAM // VIEW"
            Data.CameraButton.Active = true
            Data.CameraButton.TextColor3 = CONFIG.SecondaryColor
            Data.CameraStroke.Color = CONFIG.MainColor
            Data.CameraStroke.Transparency = 0.45
        end
    end
end

-- BIND HEALTH
local function BindPlayerHealth(Player)
    local Old = PlayerStatusHealthConnections[Player]
    if Old then pcall(function() Old:Disconnect() end) end
    PlayerStatusHealthConnections[Player] = nil
    local Character = Player.Character
    if not Character then
        if UpdatePlayerStatusCard then UpdatePlayerStatusCard(Player) end
        return
    end
    local Humanoid = Character:FindFirstChildOfClass("Humanoid")
    if not Humanoid then
        if UpdatePlayerStatusCard then UpdatePlayerStatusCard(Player) end
        return
    end
    local Connection = Humanoid.HealthChanged:Connect(function()
        if UpdatePlayerStatusCard then UpdatePlayerStatusCard(Player) end
    end)
    PlayerStatusHealthConnections[Player] = Connection
    if UpdatePlayerStatusCard then UpdatePlayerStatusCard(Player) end
end

-- CREATE STATUS CARD
local function CreatePlayerStatusCard(Player)
    if not Player then return end
    if PlayerStatusObjects[Player] then
        if UpdatePlayerStatusCard then UpdatePlayerStatusCard(Player) end
        return
    end
    local Card = Instance.new("Frame")
    Card.Name = "PlayerStatus"
    Card.Size = UDim2.new(1, -4, 0, CONFIG.StatusCardHeight)
    Card.BackgroundColor3 = CONFIG.StatusDark
    Card.BackgroundTransparency = 0.17
    Card.BorderSizePixel = 0
    Card.ClipsDescendants = true
    Card.LayoutOrder = Player.UserId
    Card.Parent = PlayerStatusArea
    local Corner = Instance.new("UICorner")
    Corner.CornerRadius = UDim.new(0, 9)
    Corner.Parent = Card
    local Stroke = Instance.new("UIStroke")
    Stroke.Color = CONFIG.MainColor
    Stroke.Thickness = 1
    Stroke.Transparency = 0.28
    Stroke.Parent = Card
    local Side = Instance.new("Frame")
    Side.Position = UDim2.new(0, 0, 0, 7)
    Side.Size = UDim2.new(0, 2, 1, -14)
    Side.BackgroundColor3 = CONFIG.MainColor
    Side.BackgroundTransparency = 0.04
    Side.BorderSizePixel = 0
    Side.Parent = Card
    local Avatar = Instance.new("ImageLabel")
    Avatar.Position = UDim2.new(0, 7, 0.5, -24)
    Avatar.Size = UDim2.new(0, 48, 0, 48)
    Avatar.BackgroundColor3 = Color3.fromRGB(8, 28, 35)
    Avatar.BackgroundTransparency = 0.10
    Avatar.BorderSizePixel = 0
    Avatar.Image = ""
    Avatar.Parent = Card
    local AvatarCorner = Instance.new("UICorner")
    AvatarCorner.CornerRadius = UDim.new(1, 0)
    AvatarCorner.Parent = Avatar
    local AvatarStroke = Instance.new("UIStroke")
    AvatarStroke.Color = CONFIG.LightBlue
    AvatarStroke.Thickness = 1
    AvatarStroke.Transparency = 0.12
    AvatarStroke.Parent = Avatar
    task.spawn(function()
        local Image = GetAvatar(Player.UserId)
        if Avatar.Parent then Avatar.Image = Image end
    end)
    local Name = Instance.new("TextLabel")
    Name.Position = UDim2.new(0, 61, 0, 7)
    Name.Size = UDim2.new(0.56, -20, 0, 18)
    Name.BackgroundTransparency = 1
    Name.Text = Player.DisplayName or Player.Name
    Name.TextColor3 = CONFIG.VeryLightBlue
    Name.TextSize = CONFIG.StatusNameTextSize
    Name.Font = Enum.Font.GothamBold
    Name.TextXAlignment = Enum.TextXAlignment.Left
    Name.TextTruncate = Enum.TextTruncate.AtEnd
    Name.Parent = Card
    local Username = Instance.new("TextLabel")
    Username.Position = UDim2.new(0, 61, 0, 27)
    Username.Size = UDim2.new(0.56, -20, 0, 12)
    Username.BackgroundTransparency = 1
    Username.Text = "@" .. Player.Name
    Username.TextColor3 = CONFIG.SecondaryColor
    Username.TextSize = CONFIG.StatusUsernameTextSize
    Username.Font = Enum.Font.GothamMedium
    Username.TextXAlignment = Enum.TextXAlignment.Left
    Username.TextTruncate = Enum.TextTruncate.AtEnd
    Username.Parent = Card
    local TeamDot = Instance.new("Frame")
    TeamDot.Position = UDim2.new(0, 61, 0, 48)
    TeamDot.Size = UDim2.new(0, 7, 0, 7)
    TeamDot.BackgroundColor3 = CONFIG.MainColor
    TeamDot.BorderSizePixel = 0
    TeamDot.Parent = Card
    local TeamDotCorner = Instance.new("UICorner")
    TeamDotCorner.CornerRadius = UDim.new(1, 0)
    TeamDotCorner.Parent = TeamDot
    local TeamText = Instance.new("TextLabel")
    TeamText.Position = UDim2.new(0, 73, 0, 44)
    TeamText.Size = UDim2.new(0.55, -20, 0, 15)
    TeamText.BackgroundTransparency = 1
    TeamText.Text = "TEAM // DEFAULT"
    TeamText.TextColor3 = CONFIG.LightBlue
    TeamText.TextSize = CONFIG.StatusInfoTextSize
    TeamText.Font = Enum.Font.GothamMedium
    TeamText.TextXAlignment = Enum.TextXAlignment.Left
    TeamText.TextTruncate = Enum.TextTruncate.AtEnd
    TeamText.Parent = Card
    local TeamStroke = Instance.new("UIStroke")
    TeamStroke.Color = CONFIG.MainColor
    TeamStroke.Thickness = 1
    TeamStroke.Transparency = 0.35
    TeamStroke.Parent = TeamDot
    local MicDot = Instance.new("Frame")
    MicDot.Position = UDim2.new(0, 61, 0, 63)
    MicDot.Size = UDim2.new(0, 7, 0, 7)
    MicDot.BackgroundColor3 = CONFIG.VoiceOff
    MicDot.BorderSizePixel = 0
    MicDot.Parent = Card
    local MicDotCorner = Instance.new("UICorner")
    MicDotCorner.CornerRadius = UDim.new(1, 0)
    MicDotCorner.Parent = MicDot
    local MicText = Instance.new("TextLabel")
    MicText.Position = UDim2.new(0, 73, 0, 58)
    MicText.Size = UDim2.new(0.55, -20, 0, 15)
    MicText.BackgroundTransparency = 1
    MicText.Text = "VOICE // OFF"
    MicText.TextColor3 = CONFIG.VoiceOff
    MicText.TextSize = CONFIG.StatusInfoTextSize
    MicText.Font = Enum.Font.GothamBold
    MicText.TextXAlignment = Enum.TextXAlignment.Left
    MicText.TextTruncate = Enum.TextTruncate.AtEnd
    MicText.Parent = Card
    local MicStroke = Instance.new("UIStroke")
    MicStroke.Color = CONFIG.VoiceOff
    MicStroke.Thickness = 1
    MicStroke.Transparency = 0.35
    MicStroke.Parent = MicDot
    local CameraButton = Instance.new("TextButton")
    CameraButton.Name = "SpectateButton"
    CameraButton.Position = UDim2.new(0, 61, 0, 75)
    CameraButton.Size = UDim2.new(0, CONFIG.SpectateButtonWidth, 0, CONFIG.SpectateButtonHeight)
    CameraButton.BackgroundColor3 = Color3.fromRGB(6, 24, 32)
    CameraButton.BackgroundTransparency = 0.10
    CameraButton.BorderSizePixel = 0
    CameraButton.AutoButtonColor = false
    CameraButton.Active = true
    CameraButton.Selectable = true
    CameraButton.Text = "CAM // VIEW"
    CameraButton.TextColor3 = CONFIG.SecondaryColor
    CameraButton.TextSize = 7
    CameraButton.Font = Enum.Font.GothamBold
    CameraButton.TextXAlignment = Enum.TextXAlignment.Center
    CameraButton.TextYAlignment = Enum.TextYAlignment.Center
    CameraButton.ZIndex = 10
    CameraButton.Parent = Card
    local CameraCorner = Instance.new("UICorner")
    CameraCorner.CornerRadius = UDim.new(0, 5)
    CameraCorner.Parent = CameraButton
    local CameraStroke = Instance.new("UIStroke")
    CameraStroke.Color = CONFIG.MainColor
    CameraStroke.Thickness = 1
    CameraStroke.Transparency = 0.45
    CameraStroke.Parent = CameraButton
    CameraButton.InputBegan:Connect(function(Input)
        if Player == LocalPlayer then return end
        if Input.UserInputType == Enum.UserInputType.Touch or Input.UserInputType == Enum.UserInputType.MouseButton1 then
            TweenService:Create(CameraButton, TweenInfo.new(0.08, Enum.EasingStyle.Quad, Enum.EasingDirection.Out), {
                BackgroundTransparency = 0,
            }):Play()
            TweenService:Create(CameraStroke, TweenInfo.new(0.08, Enum.EasingStyle.Quad, Enum.EasingDirection.Out), {
                Transparency = 0,
            }):Play()
        end
    end)
    CameraButton.InputEnded:Connect(function(Input)
        if Input.UserInputType == Enum.UserInputType.Touch or Input.UserInputType == Enum.UserInputType.MouseButton1 then
            TweenService:Create(CameraButton, TweenInfo.new(0.12, Enum.EasingStyle.Quad, Enum.EasingDirection.Out), {
                BackgroundTransparency = 0.10,
            }):Play()
        end
    end)
    local HPPanel = Instance.new("Frame")
    HPPanel.AnchorPoint = Vector2.new(1, 0.5)
    HPPanel.Position = UDim2.new(1, -8, 0.5, 0)
    HPPanel.Size = UDim2.new(0.39, -3, 0, 60)
    HPPanel.BackgroundColor3 = CONFIG.StatusPanelDark
    HPPanel.BackgroundTransparency = 0.10
    HPPanel.BorderSizePixel = 0
    HPPanel.Parent = Card
    local HPPanelCorner = Instance.new("UICorner")
    HPPanelCorner.CornerRadius = UDim.new(0, 8)
    HPPanelCorner.Parent = HPPanel
    local HealthStroke = Instance.new("UIStroke")
    HealthStroke.Color = CONFIG.HealthGood
    HealthStroke.Thickness = 1
    HealthStroke.Transparency = 0.20
    HealthStroke.Parent = HPPanel
    local HealthDot = Instance.new("Frame")
    HealthDot.Position = UDim2.new(0, 8, 0, 8)
    HealthDot.Size = UDim2.new(0, 7, 0, 7)
    HealthDot.BackgroundColor3 = CONFIG.HealthGood
    HealthDot.BorderSizePixel = 0
    HealthDot.Parent = HPPanel
    local HealthDotCorner = Instance.new("UICorner")
    HealthDotCorner.CornerRadius = UDim.new(1, 0)
    HealthDotCorner.Parent = HealthDot
    local HealthText = Instance.new("TextLabel")
    HealthText.Position = UDim2.new(0, 21, 0, 3)
    HealthText.Size = UDim2.new(0.65, -15, 0, 18)
    HealthText.BackgroundTransparency = 1
    HealthText.Text = "HP 0 / 0"
    HealthText.TextColor3 = CONFIG.VeryLightBlue
    HealthText.TextSize = CONFIG.StatusHPTextSize
    HealthText.Font = Enum.Font.GothamBold
    HealthText.TextXAlignment = Enum.TextXAlignment.Left
    HealthText.Parent = HPPanel
    local PercentText = Instance.new("TextLabel")
    PercentText.AnchorPoint = Vector2.new(1, 0)
    PercentText.Position = UDim2.new(1, -8, 0, 6)
    PercentText.Size = UDim2.new(0, 75, 0, 16)
    PercentText.BackgroundTransparency = 1
    PercentText.Text = "0% // NO CHARACTER"
    PercentText.TextColor3 = CONFIG.HealthGood
    PercentText.TextSize = CONFIG.StatusInfoTextSize
    PercentText.Font = Enum.Font.GothamBold
    PercentText.TextXAlignment = Enum.TextXAlignment.Right
    PercentText.TextTruncate = Enum.TextTruncate.AtEnd
    PercentText.Parent = HPPanel
    local HealthBack = Instance.new("Frame")
    HealthBack.Position = UDim2.new(0, 8, 1, -15)
    HealthBack.Size = UDim2.new(1, -16, 0, 6)
    HealthBack.BackgroundColor3 = Color3.fromRGB(10, 40, 48)
    HealthBack.BackgroundTransparency = 0.20
    HealthBack.BorderSizePixel = 0
    HealthBack.ClipsDescendants = true
    HealthBack.Parent = HPPanel
    local HealthBackCorner = Instance.new("UICorner")
    HealthBackCorner.CornerRadius = UDim.new(1, 0)
    HealthBackCorner.Parent = HealthBack
    local HealthFill = Instance.new("Frame")
    HealthFill.Size = UDim2.new(1, 0, 1, 0)
    HealthFill.BackgroundColor3 = CONFIG.HealthGood
    HealthFill.BorderSizePixel = 0
    HealthFill.Parent = HealthBack
    local HealthFillCorner = Instance.new("UICorner")
    HealthFillCorner.CornerRadius = UDim.new(1, 0)
    HealthFillCorner.Parent = HealthFill
    PlayerStatusObjects[Player] = {
        Card = Card, Avatar = Avatar, Name = Name, Username = Username,
        TeamDot = TeamDot, TeamText = TeamText, TeamStroke = TeamStroke,
        MicDot = MicDot, MicText = MicText, MicStroke = MicStroke,
        CameraButton = CameraButton, CameraStroke = CameraStroke,
        HealthText = HealthText, PercentText = PercentText,
        HealthDot = HealthDot, HealthStroke = HealthStroke, HealthFill = HealthFill,
    }
    CameraButton.Activated:Connect(function()
        if Player == LocalPlayer then return end
        if SpectateState.Active and SpectateState.Target == Player then
            StopSpectating()
        else
            StartSpectating(Player)
        end
    end)
    BindPlayerHealth(Player)
    local OldCharacterConnection = PlayerStatusCharacterConnections[Player]
    if OldCharacterConnection then pcall(function() OldCharacterConnection:Disconnect() end) end
    PlayerStatusCharacterConnections[Player] = Player.CharacterAdded:Connect(function()
        task.wait(0.15)
        if SpectateState.Active and SpectateState.Target == Player then
            task.defer(function()
                RequestTargetStreaming(Player, true)
                AttachSpectateCamera(Player)
            end)
        end
        if not PlayerStatusObjects[Player] then return end
        BindPlayerHealth(Player)
        if UpdatePlayerStatusCard then UpdatePlayerStatusCard(Player) end
    end)
    BindVoicePlayer(Player)
    CreateSweep(Card, CONFIG.LightBlue, 0.72)
    Card.Position = UDim2.new(0, 18, 0, 0)
    Card.BackgroundTransparency = 1
    Stroke.Transparency = 1
    Avatar.ImageTransparency = 1
    Name.TextTransparency = 1
    Username.TextTransparency = 1
    TeamText.TextTransparency = 1
    MicText.TextTransparency = 1
    CameraButton.TextTransparency = 1
    HealthText.TextTransparency = 1
    PercentText.TextTransparency = 1
    TweenService:Create(Card, TweenInfo.new(0.28, Enum.EasingStyle.Quint, Enum.EasingDirection.Out), {
        Position = UDim2.new(0, 0, 0, 0), BackgroundTransparency = 0.17,
    }):Play()
    TweenService:Create(Stroke, TweenInfo.new(0.28, Enum.EasingStyle.Quint, Enum.EasingDirection.Out), {
        Transparency = 0.28,
    }):Play()
    TweenService:Create(Avatar, TweenInfo.new(0.28, Enum.EasingStyle.Quint, Enum.EasingDirection.Out), {
        ImageTransparency = 0,
    }):Play()
    TweenService:Create(Name, TweenInfo.new(0.25, Enum.EasingStyle.Quint, Enum.EasingDirection.Out), {
        TextTransparency = 0,
    }):Play()
    TweenService:Create(Username, TweenInfo.new(0.28, Enum.EasingStyle.Quint, Enum.EasingDirection.Out), {
        TextTransparency = 0.10,
    }):Play()
    TweenService:Create(TeamText, TweenInfo.new(0.30, Enum.EasingStyle.Quint, Enum.EasingDirection.Out), {
        TextTransparency = 0,
    }):Play()
    TweenService:Create(MicText, TweenInfo.new(0.30, Enum.EasingStyle.Quint, Enum.EasingDirection.Out), {
        TextTransparency = 0,
    }):Play()
    TweenService:Create(CameraButton, TweenInfo.new(0.30, Enum.EasingStyle.Quint, Enum.EasingDirection.Out), {
        TextTransparency = 0,
    }):Play()
    TweenService:Create(HealthText, TweenInfo.new(0.30, Enum.EasingStyle.Quint, Enum.EasingDirection.Out), {
        TextTransparency = 0,
    }):Play()
    TweenService:Create(PercentText, TweenInfo.new(0.30, Enum.EasingStyle.Quint, Enum.EasingDirection.Out), {
        TextTransparency = 0,
    }):Play()
    if UpdatePlayerStatusCard then UpdatePlayerStatusCard(Player) end
end

-- REMOVE STATUS
local function RemovePlayerStatusCard(Player)
    if not Player then return end
    local HealthConnection = PlayerStatusHealthConnections[Player]
    if HealthConnection then pcall(function() HealthConnection:Disconnect() end) end
    PlayerStatusHealthConnections[Player] = nil
    local CharacterConnection = PlayerStatusCharacterConnections[Player]
    if CharacterConnection then pcall(function() CharacterConnection:Disconnect() end) end
    PlayerStatusCharacterConnections[Player] = nil
    local VoiceConnection = VoicePlayerConnections[Player]
    if VoiceConnection then pcall(function() VoiceConnection:Disconnect() end) end
    VoicePlayerConnections[Player] = nil
    DestroyVoiceMonitor(Player)
    local Data = PlayerStatusObjects[Player]
    if Data then DestroySafe(Data.Card) end
    PlayerStatusObjects[Player] = nil
    RefreshSpectateButtons()
end

-- REFRESH STATUS LIST
local function RefreshPlayerStatusList()
    local CurrentPlayers = {}
    for _, Player in ipairs(Players:GetPlayers()) do
        CurrentPlayers[Player] = true
        if not PlayerStatusObjects[Player] then CreatePlayerStatusCard(Player) end
    end
    for Player in pairs(PlayerStatusObjects) do
        if not CurrentPlayers[Player] then RemovePlayerStatusCard(Player) end
    end
    local PlayersList = Players:GetPlayers()
    table.sort(PlayersList, function(A, B)
        local AName = string.lower(A.DisplayName or A.Name)
        local BName = string.lower(B.DisplayName or B.Name)
        return AName < BName
    end)
    for Index, Player in ipairs(PlayersList) do
        local Data = PlayerStatusObjects[Player]
        if Data and Data.Card then
            Data.Card.LayoutOrder = Index
            if UpdatePlayerStatusCard then UpdatePlayerStatusCard(Player) end
        end
    end
    UpdatePlayerCount()
    RefreshSpectateButtons()
    ScrollToBottom(PlayerStatusArea)
end

-- CREATE CHAT CARD
local function CreateChatCard(Player, MessageText)
    if not Player then return end
    MessageText = CleanText(MessageText)
    if MessageText == "" then return end
    if not AcceptBubbleMessage(Player, MessageText) then return end
    local Card = Instance.new("Frame")
    Card.Name = "RobloxBubbleMessage"
    Card.Size = UDim2.new(1, -5, 0, 76)
    Card.BackgroundColor3 = CONFIG.ChatDark
    Card.BackgroundTransparency = 1
    Card.BorderSizePixel = 0
    Card.ClipsDescendants = true
    Card.LayoutOrder = math.floor(os.clock() * 1000)
    Card.Parent = ChatArea
    table.insert(ChatObjects, Card)
    local Corner = Instance.new("UICorner")
    Corner.CornerRadius = UDim.new(0, 9)
    Corner.Parent = Card
    local Stroke = Instance.new("UIStroke")
    Stroke.Color = CONFIG.MainColor
    Stroke.Thickness = 1
    Stroke.Transparency = 1
    Stroke.Parent = Card
    local Side = Instance.new("Frame")
    Side.Position = UDim2.new(0, 0, 0, 7)
    Side.Size = UDim2.new(0, 2, 1, -14)
    Side.BackgroundColor3 = CONFIG.MainColor
    Side.BackgroundTransparency = 0.10
    Side.BorderSizePixel = 0
    Side.Parent = Card
    local Avatar = Instance.new("ImageLabel")
    Avatar.Position = UDim2.new(0, 7, 0.5, -21)
    Avatar.Size = UDim2.new(0, 42, 0, 42)
    Avatar.BackgroundColor3 = Color3.fromRGB(8, 28, 35)
    Avatar.BackgroundTransparency = 0.12
    Avatar.BorderSizePixel = 0
    Avatar.Image = ""
    Avatar.ImageTransparency = 1
    Avatar.Parent = Card
    local AvatarCorner = Instance.new("UICorner")
    AvatarCorner.CornerRadius = UDim.new(1, 0)
    AvatarCorner.Parent = Avatar
    local AvatarStroke = Instance.new("UIStroke")
    AvatarStroke.Color = CONFIG.MainColor
    AvatarStroke.Thickness = 1
    AvatarStroke.Transparency = 0.20
    AvatarStroke.Parent = Avatar
    task.spawn(function()
        local Image = GetAvatar(Player.UserId)
        if Avatar.Parent then Avatar.Image = Image end
    end)
    local Name = Instance.new("TextLabel")
    Name.Position = UDim2.new(0, 57, 0, 6)
    Name.Size = UDim2.new(1, -63, 0, 19)
    Name.BackgroundTransparency = 1
    Name.Text = Player.DisplayName or Player.Name
    Name.TextColor3 = CONFIG.White
    Name.TextSize = CONFIG.PlayerNameTextSize
    Name.Font = Enum.Font.GothamBold
    Name.TextXAlignment = Enum.TextXAlignment.Left
    Name.TextTruncate = Enum.TextTruncate.AtEnd
    Name.TextTransparency = 1
    Name.ZIndex = 4
    Name.Parent = Card
    local Username = Instance.new("TextLabel")
    Username.Position = UDim2.new(0, 57, 0, 23)
    Username.Size = UDim2.new(1, -63, 0, 13)
    Username.BackgroundTransparency = 1
    Username.Text = "@" .. Player.Name
    Username.TextColor3 = CONFIG.SecondaryColor
    Username.TextSize = CONFIG.UsernameTextSize
    Username.Font = Enum.Font.GothamMedium
    Username.TextXAlignment = Enum.TextXAlignment.Left
    Username.TextTransparency = 1
    Username.ZIndex = 4
    Username.Parent = Card
    local Message = Instance.new("TextLabel")
    Message.Position = UDim2.new(0, 57, 0, 41)
    Message.Size = UDim2.new(1, -63, 0, 22)
    Message.BackgroundTransparency = 1
    Message.Text = ""
    Message.TextColor3 = CONFIG.White
    Message.TextSize = CONFIG.MessageTextSize
    Message.Font = Enum.Font.Gotham
    Message.TextXAlignment = Enum.TextXAlignment.Left
    Message.TextYAlignment = Enum.TextYAlignment.Top
    Message.TextWrapped = true
    Message.TextTruncate = Enum.TextTruncate.None
    Message.ZIndex = 4
    Message.Parent = Card
    local InitialHeight = GetTextHeight(MessageText, GetChatTextWidth(), CONFIG.MessageTextSize)
    Card.Size = UDim2.new(1, -5, 0, math.max(76, 49 + InitialHeight + 9))
    CreateSweep(Card, CONFIG.MainColor, 0.65)
    Card.Position = UDim2.new(0, 26, 0, 0)
    local Intro = TweenInfo.new(CONFIG.MessageTweenTime, Enum.EasingStyle.Quint, Enum.EasingDirection.Out)
    TweenService:Create(Card, Intro, {
        Position = UDim2.new(0, 0, 0, 0), BackgroundTransparency = CONFIG.CardTransparency,
    }):Play()
    TweenService:Create(Stroke, Intro, { Transparency = 0.30 }):Play()
    TweenService:Create(Avatar, Intro, { ImageTransparency = 0 }):Play()
    TweenService:Create(Name, Intro, { TextTransparency = 0 }):Play()
    TweenService:Create(Username, Intro, { TextTransparency = 0.12 }):Play()
    task.spawn(function()
        local Length = utf8.len(MessageText)
        if not Length then Length = #MessageText end
        for Index = 1, Length do
            if not Message.Parent then return end
            Message.Text = Utf8Take(MessageText, Index)
            task.wait(CONFIG.TypeSpeed)
        end
        if Message.Parent then Message.Text = MessageText end
    end)
    TrimChatHistory()
    ScrollToBottom(ChatArea)
end

-- EVENT CARD
local function CreateEventCard(Player, EventType)
    if not Player then return end
    local IsJoin = EventType == "JOIN"
    local Accent = IsJoin and CONFIG.JoinColor or CONFIG.LeaveAccent
    local TextColor = IsJoin and CONFIG.JoinColor or CONFIG.LeaveColor
    local BackgroundColor = IsJoin and CONFIG.EventJoinDark or CONFIG.EventLeaveDark
    local Card = Instance.new("Frame")
    Card.Name = "PlayerEvent"
    Card.Size = UDim2.new(1, -4, 0, 78)
    Card.BackgroundColor3 = BackgroundColor
    Card.BackgroundTransparency = 1
    Card.BorderSizePixel = 0
    Card.ClipsDescendants = true
    Card.LayoutOrder = math.floor(os.clock() * 1000)
    Card.Parent = EventArea
    table.insert(EventObjects, Card)
    local Corner = Instance.new("UICorner")
    Corner.CornerRadius = UDim.new(0, 9)
    Corner.Parent = Card
    local Stroke = Instance.new("UIStroke")
    Stroke.Color = Accent
    Stroke.Thickness = 1
    Stroke.Transparency = 1
    Stroke.Parent = Card
    local Side = Instance.new("Frame")
    Side.Position = UDim2.new(0, 0, 0, 7)
    Side.Size = UDim2.new(0, 2, 1, -14)
    Side.BackgroundColor3 = Accent
    Side.BackgroundTransparency = 0.05
    Side.BorderSizePixel = 0
    Side.Parent = Card
    local Icon = Instance.new("TextLabel")
    Icon.Position = UDim2.new(0, 7, 0, 7)
    Icon.Size = UDim2.new(0, 23, 0, 23)
    Icon.BackgroundTransparency = 1
    Icon.Text = IsJoin and "+" or "×"
    Icon.TextColor3 = Accent
    Icon.TextSize = 16
    Icon.Font = Enum.Font.GothamBold
    Icon.TextXAlignment = Enum.TextXAlignment.Center
    Icon.ZIndex = 5
    Icon.Parent = Card
    local EventTitle = Instance.new("TextLabel")
    EventTitle.Position = UDim2.new(0, 33, 0, 6)
    EventTitle.Size = UDim2.new(1, -39, 0, 17)
    EventTitle.BackgroundTransparency = 1
    EventTitle.Text = IsJoin and "PLAYER JOINED" or "PLAYER LEFT"
    EventTitle.TextColor3 = Accent
    EventTitle.TextSize = CONFIG.EventTitleTextSize
    EventTitle.Font = Enum.Font.GothamBold
    EventTitle.TextXAlignment = Enum.TextXAlignment.Left
    EventTitle.ZIndex = 5
    EventTitle.Parent = Card
    local Name = Instance.new("TextLabel")
    Name.Position = UDim2.new(0, 33, 0, 25)
    Name.Size = UDim2.new(1, -39, 0, 19)
    Name.BackgroundTransparency = 1
    Name.Text = Player.DisplayName or Player.Name
    Name.TextColor3 = TextColor
    Name.TextSize = CONFIG.EventPlayerTextSize
    Name.Font = Enum.Font.GothamBold
    Name.TextXAlignment = Enum.TextXAlignment.Left
    Name.TextTruncate = Enum.TextTruncate.AtEnd
    Name.ZIndex = 5
    Name.Parent = Card
    local Username = Instance.new("TextLabel")
    Username.Position = UDim2.new(0, 33, 0, 44)
    Username.Size = UDim2.new(1, -39, 0, 14)
    Username.BackgroundTransparency = 1
    Username.Text = "@" .. Player.Name
    Username.TextColor3 = IsJoin and CONFIG.SecondaryColor or Color3.fromRGB(255, 170, 175)
    Username.TextSize = 8
    Username.Font = Enum.Font.GothamMedium
    Username.TextXAlignment = Enum.TextXAlignment.Left
    Username.ZIndex = 5
    Username.Parent = Card
    local Avatar = Instance.new("ImageLabel")
    Avatar.AnchorPoint = Vector2.new(1, 0.5)
    Avatar.Position = UDim2.new(1, -7, 0.5, 0)
    Avatar.Size = UDim2.new(0, 36, 0, 36)
    Avatar.BackgroundColor3 = Color3.fromRGB(8, 25, 30)
    Avatar.BackgroundTransparency = 0.15
    Avatar.BorderSizePixel = 0
    Avatar.Image = ""
    Avatar.ImageTransparency = 1
    Avatar.ZIndex = 4
    Avatar.Parent = Card
    local AvatarCorner = Instance.new("UICorner")
    AvatarCorner.CornerRadius = UDim.new(1, 0)
    AvatarCorner.Parent = Avatar
    local AvatarStroke = Instance.new("UIStroke")
    AvatarStroke.Color = Accent
    AvatarStroke.Thickness = 1
    AvatarStroke.Transparency = 0.15
    AvatarStroke.Parent = Avatar
    task.spawn(function()
        local Image = GetAvatar(Player.UserId)
        if Avatar.Parent then Avatar.Image = Image end
    end)
    CreateSweep(Card, Accent, 0.75)
    Card.Position = UDim2.new(0, 22, 0, 0)
    local Intro = TweenInfo.new(0.30, Enum.EasingStyle.Quint, Enum.EasingDirection.Out)
    TweenService:Create(Card, Intro, {
        Position = UDim2.new(0, 0, 0, 0), BackgroundTransparency = 0.18,
    }):Play()
    TweenService:Create(Stroke, Intro, { Transparency = 0.25 }):Play()
    TweenService:Create(Avatar, Intro, { ImageTransparency = 0 }):Play()
    Icon.TextTransparency = 1
    Icon.Rotation = IsJoin and -90 or 90
    TweenService:Create(Icon, TweenInfo.new(0.42, Enum.EasingStyle.Back, Enum.EasingDirection.Out), {
        TextTransparency = 0, Rotation = 0,
    }):Play()
    TrimEventHistory()
    ScrollToBottom(EventArea)
end

-- CATEGORY STATE
local RightMode = 1

-- CATEGORY VISUAL
local function UpdateCategoryVisual()
    if RightMode == 1 then
        Category1Button.BackgroundColor3 = CONFIG.MainColor
        Category1Button.BackgroundTransparency = 0.12
        Category1Button.TextColor3 = CONFIG.White
        Category1Stroke.Transparency = 0
        Category2Button.BackgroundColor3 = Color3.fromRGB(6, 22, 29)
        Category2Button.BackgroundTransparency = 0.22
        Category2Button.TextColor3 = CONFIG.SecondaryColor
        Category2Stroke.Transparency = 0.55
        RightTitle.Text = "PLAYER EVENTS"
        EventArea.Visible = true
        PlayerStatusArea.Visible = false
    else
        Category2Button.BackgroundColor3 = CONFIG.MainColor
        Category2Button.BackgroundTransparency = 0.12
        Category2Button.TextColor3 = CONFIG.White
        Category2Stroke.Transparency = 0
        Category1Button.BackgroundColor3 = Color3.fromRGB(6, 22, 29)
        Category1Button.BackgroundTransparency = 0.22
        Category1Button.TextColor3 = CONFIG.SecondaryColor
        Category1Stroke.Transparency = 0.55
        RightTitle.Text = "PLAYER STATUS"
        EventArea.Visible = false
        PlayerStatusArea.Visible = true
        RefreshPlayerStatusList()
    end
end

-- CATEGORY INPUT
Category1Button.Activated:Connect(function()
    RightMode = 1
    UpdateCategoryVisual()
end)
Category2Button.Activated:Connect(function()
    RightMode = 2
    UpdateCategoryVisual()
end)

-- CATEGORY PRESS FX
local function PressCategoryButton(Button)
    TweenService:Create(Button, TweenInfo.new(0.08, Enum.EasingStyle.Quad, Enum.EasingDirection.Out), {
        BackgroundTransparency = 0,
    }):Play()
end
Category1Button.InputBegan:Connect(function(Input)
    if Input.UserInputType == Enum.UserInputType.Touch or Input.UserInputType == Enum.UserInputType.MouseButton1 then
        PressCategoryButton(Category1Button)
    end
end)
Category2Button.InputBegan:Connect(function(Input)
    if Input.UserInputType == Enum.UserInputType.Touch or Input.UserInputType == Enum.UserInputType.MouseButton1 then
        PressCategoryButton(Category2Button)
    end
end)

-- PLAYER JOIN
Players.PlayerAdded:Connect(function(Player)
    CreateEventCard(Player, "JOIN")
    task.defer(function()
        CreatePlayerStatusCard(Player)
        BindVoicePlayer(Player)
        RefreshPlayerStatusList()
    end)
end)

-- PLAYER LEAVE
Players.PlayerRemoving:Connect(function(Player)
    if SpectateState.Active and SpectateState.Target == Player then StopSpectating() end
    CreateEventCard(Player, "LEFT")
    RemovePlayerStatusCard(Player)
    task.defer(RefreshPlayerStatusList)
end)

-- EXISTING PLAYERS
task.defer(function()
    for _, Player in ipairs(Players:GetPlayers()) do
        CreatePlayerStatusCard(Player)
        BindVoicePlayer(Player)
    end
    RefreshPlayerStatusList()
end)

-- VOICE INITIAL CHECK
task.spawn(function()
    local Enabled = CheckLocalVoiceStatus()
    LastVoiceCheck = Enabled
    RefreshVoiceMonitors()
    UpdateVoiceHeader()
    RefreshPlayerStatusList()
end)

-- VOICE CHECK LOOP
task.spawn(function()
    while Root.Parent do
        task.wait(CONFIG.VoiceCheckInterval)
        local Enabled = CheckLocalVoiceStatus()
        if Enabled ~= LastVoiceCheck then
            LastVoiceCheck = Enabled
            RefreshVoiceMonitors()
        end
        UpdateVoiceHeader()
    end
end)

-- AUDIO DEVICE RECOVERY
task.spawn(function()
    while Root.Parent do
        task.wait(CONFIG.VoiceInputWait)
        for _, Player in ipairs(Players:GetPlayers()) do
            if not VoiceMonitors[Player] then SetupVoiceMonitor(Player) end
        end
    end
end)

-- VOICE ACTIVITY
task.spawn(function()
    while Root.Parent do
        task.wait(CONFIG.VoiceAnalyzerUpdateRate)
        for _, Player in ipairs(Players:GetPlayers()) do
            local Monitor = VoiceMonitors[Player]
            if Monitor and Monitor.Analyzer and Monitor.Analyzer.Parent then
                pcall(function()
                    Monitor.LastPeak = Monitor.Analyzer.PeakLevel
                    Monitor.LastRMS = Monitor.Analyzer.RmsLevel
                end)
            end
        end
    end
end)

-- LIVE STATUS
task.spawn(function()
    while Root.Parent do
        task.wait(CONFIG.StatusUpdateRate)
        UpdatePlayerCount()
        for Player in pairs(PlayerStatusObjects) do
            if Player.Parent == Players and UpdatePlayerStatusCard then
                UpdatePlayerStatusCard(Player)
            end
        end
        if SpectateState.Active then RefreshSpectateButtons() end
    end
end)

-- REAL ROBLOX BUBBLE CHAT
local ExistingBubbleCallback = nil
pcall(function() ExistingBubbleCallback = TextChatService.OnBubbleAdded end)

local function HandleRobloxBubble(Message, Adornee)
    if not Message then return end
    local TextSource = Message.TextSource
    if not TextSource then return end
    local Player = Players:GetPlayerByUserId(TextSource.UserId)
    if not Player then return end
    local Text = Message.Text
    if typeof(Text) ~= "string" then return end
    Text = CleanText(Text)
    if Text == "" then return end
    CreateChatCard(Player, Text)
end

pcall(function()
    TextChatService.OnBubbleAdded = function(Message, Adornee)
        HandleRobloxBubble(Message, Adornee)
        if typeof(ExistingBubbleCallback) == "function" then
            local Success, Result = pcall(ExistingBubbleCallback, Message, Adornee)
            if Success and Result then return Result end
        end
        return nil
    end
end)

-- ONLINE PULSE
task.spawn(function()
    while StatusDot.Parent do
        local A = TweenService:Create(StatusDot, TweenInfo.new(0.7, Enum.EasingStyle.Sine, Enum.EasingDirection.InOut), {
            BackgroundTransparency = 0.65,
        })
        A:Play()
        A.Completed:Wait()
        if not StatusDot.Parent then break end
        local B = TweenService:Create(StatusDot, TweenInfo.new(0.7, Enum.EasingStyle.Sine, Enum.EasingDirection.InOut), {
            BackgroundTransparency = 0,
        })
        B:Play()
        B.Completed:Wait()
    end
end)

-- 2D CONTROL GUI
local ControlGui = Instance.new("ScreenGui")
ControlGui.Name = "NX_3D_SciFiChat_Control"
ControlGui.ResetOnSpawn = false
ControlGui.IgnoreGuiInset = true
ControlGui.DisplayOrder = 999999
ControlGui.ZIndexBehavior = Enum.ZIndexBehavior.Sibling
ControlGui.Parent = PlayerGui

-- SPECTATE EXIT BUTTON
-- Screen-space control stays fixed while the 3D chat panel follows the camera.
SpectateExitButton = Instance.new("TextButton")
SpectateExitButton.Name = "SpectateExitButton"
SpectateExitButton.AnchorPoint = Vector2.new(0.5, 0)
SpectateExitButton.Position = UDim2.new(0.5, 0, 0, 48)
SpectateExitButton.Size = UDim2.fromOffset(220, 38)
SpectateExitButton.BackgroundColor3 = Color3.fromRGB(18, 24, 32)
SpectateExitButton.BackgroundTransparency = 0.06
SpectateExitButton.BorderSizePixel = 0
SpectateExitButton.AutoButtonColor = false
SpectateExitButton.Active = true
SpectateExitButton.Selectable = true
SpectateExitButton.Text = "EXIT SPECTATE"
SpectateExitButton.TextColor3 = Color3.fromRGB(225, 248, 255)
SpectateExitButton.TextSize = 11
SpectateExitButton.Font = Enum.Font.GothamBold
SpectateExitButton.Visible = false
SpectateExitButton.ZIndex = 100
SpectateExitButton.Parent = ControlGui

local SpectateExitCorner = Instance.new("UICorner")
SpectateExitCorner.CornerRadius = UDim.new(0, 9)
SpectateExitCorner.Parent = SpectateExitButton

local SpectateExitStroke = Instance.new("UIStroke")
SpectateExitStroke.Color = Color3.fromRGB(255, 125, 135)
SpectateExitStroke.Thickness = 1.5
SpectateExitStroke.Transparency = 0.12
SpectateExitStroke.Parent = SpectateExitButton

SpectateExitButton.Activated:Connect(function()
    StopSpectating()
end)

-- OPEN BUTTON
local OpenButton = Instance.new("TextButton")
OpenButton.Name = "OpenChatButton"
OpenButton.Active = true
OpenButton.Selectable = true
OpenButton.AutoButtonColor = false
OpenButton.AnchorPoint = Vector2.new(0, 0)
OpenButton.Position = UDim2.fromOffset(CONFIG.ButtonLeftOffset, 300)
OpenButton.Size = UDim2.fromOffset(CONFIG.ButtonWidth, CONFIG.ButtonHeight)
OpenButton.BackgroundColor3 = CONFIG.ButtonBase
OpenButton.BackgroundTransparency = 0.02
OpenButton.BorderSizePixel = 0
OpenButton.Text = ""
OpenButton.Visible = false
OpenButton.ClipsDescendants = true
OpenButton.ZIndex = 10
OpenButton.Parent = ControlGui
local OpenCorner = Instance.new("UICorner")
OpenCorner.CornerRadius = UDim.new(0, 11)
OpenCorner.Parent = OpenButton
local OpenGradient = Instance.new("UIGradient")
OpenGradient.Name = "OpenButtonGradient"
OpenGradient.Rotation = 0
OpenGradient.Offset = Vector2.new(-0.9, 0)
OpenGradient.Color = ColorSequence.new({
    ColorSequenceKeypoint.new(0, CONFIG.ButtonGradientDark),
    ColorSequenceKeypoint.new(0.20, CONFIG.ButtonGradientMid),
    ColorSequenceKeypoint.new(0.38, CONFIG.ButtonGradientCyan),
    ColorSequenceKeypoint.new(0.50, CONFIG.ButtonGradientLight),
    ColorSequenceKeypoint.new(0.62, CONFIG.ButtonGradientCyan),
    ColorSequenceKeypoint.new(0.80, CONFIG.ButtonGradientMid),
    ColorSequenceKeypoint.new(1, CONFIG.ButtonGradientDark),
})
OpenGradient.Transparency = NumberSequence.new({
    NumberSequenceKeypoint.new(0, 0.15),
    NumberSequenceKeypoint.new(0.25, 0.05),
    NumberSequenceKeypoint.new(0.50, 0),
    NumberSequenceKeypoint.new(0.75, 0.05),
    NumberSequenceKeypoint.new(1, 0.15),
})
OpenGradient.Parent = OpenButton
local OpenStroke = Instance.new("UIStroke")
OpenStroke.Color = CONFIG.MainColor
OpenStroke.Thickness = 1.5
OpenStroke.Transparency = 0.18
OpenStroke.Parent = OpenButton
local OpenIcon = Instance.new("TextLabel")
OpenIcon.Position = UDim2.new(0, 10, 0.5, -10)
OpenIcon.Size = UDim2.new(0, 20, 0, 20)
OpenIcon.BackgroundTransparency = 1
OpenIcon.Text = "◈"
OpenIcon.TextColor3 = CONFIG.MainColor
OpenIcon.TextSize = 16
OpenIcon.Font = Enum.Font.GothamBold
OpenIcon.TextXAlignment = Enum.TextXAlignment.Center
OpenIcon.TextYAlignment = Enum.TextYAlignment.Center
OpenIcon.ZIndex = 14
OpenIcon.Parent = OpenButton
local OpenText = Instance.new("TextLabel")
OpenText.Position = UDim2.new(0, 34, 0, 0)
OpenText.Size = UDim2.new(1, -42, 1, 0)
OpenText.BackgroundTransparency = 1
OpenText.Text = "OPEN CHAT"
OpenText.TextColor3 = CONFIG.White
OpenText.TextSize = 11
OpenText.Font = Enum.Font.GothamBold
OpenText.TextXAlignment = Enum.TextXAlignment.Left
OpenText.TextYAlignment = Enum.TextYAlignment.Center
OpenText.ZIndex = 14
OpenText.Parent = OpenButton

-- OPEN GRADIENT LOOP
task.spawn(function()
    while OpenButton.Parent do
        OpenGradient.Offset = Vector2.new(-0.9, 0)
        local Tween = TweenService:Create(OpenGradient, TweenInfo.new(1.65, Enum.EasingStyle.Sine, Enum.EasingDirection.InOut), {
            Offset = Vector2.new(0.9, 0),
        })
        Tween:Play()
        Tween.Completed:Wait()
        if not OpenButton.Parent then break end
        task.wait(0.25)
    end
end)

-- OPEN PULSE
task.spawn(function()
    while OpenButton.Parent do
        local A = TweenService:Create(OpenStroke, TweenInfo.new(0.8, Enum.EasingStyle.Sine, Enum.EasingDirection.InOut), {
            Transparency = 0.52,
        })
        A:Play()
        A.Completed:Wait()
        if not OpenStroke.Parent then break end
        local B = TweenService:Create(OpenStroke, TweenInfo.new(0.8, Enum.EasingStyle.Sine, Enum.EasingDirection.InOut), {
            Transparency = 0.16,
        })
        B:Play()
        B.Completed:Wait()
    end
end)

-- OPEN VISUAL
local function PressOpenVisual()
    TweenService:Create(OpenButton, TweenInfo.new(0.08, Enum.EasingStyle.Quad, Enum.EasingDirection.Out), {
        Size = UDim2.fromOffset(118, 39),
    }):Play()
    TweenService:Create(OpenStroke, TweenInfo.new(0.08, Enum.EasingStyle.Quad, Enum.EasingDirection.Out), {
        Transparency = 0,
    }):Play()
end

local function ReleaseOpenVisual()
    TweenService:Create(OpenButton, TweenInfo.new(0.12, Enum.EasingStyle.Back, Enum.EasingDirection.Out), {
        Size = UDim2.fromOffset(CONFIG.ButtonWidth, CONFIG.ButtonHeight),
    }):Play()
    TweenService:Create(OpenStroke, TweenInfo.new(0.12, Enum.EasingStyle.Quad, Enum.EasingDirection.Out), {
        Transparency = 0.18,
    }):Play()
end

-- WINDOW
local WindowVisible = true
local Transitioning = false

-- DRAG
local Pressing = false
local Dragging = false
local PressToken = 0
local ActiveInput = nil
local DragStart = nil
local StartButtonPosition = nil

-- VIEWPORT
local function GetViewport()
    local Camera = Workspace.CurrentCamera
    if not Camera then return Vector2.new(1280, 720) end
    return Camera.ViewportSize
end

-- DEFAULT BUTTON
local ButtonHasCustomPosition = false
local function GetDefaultButtonPosition()
    local Viewport = GetViewport()
    local Width = OpenButton.AbsoluteSize.X
    local Height = OpenButton.AbsoluteSize.Y
    local X = CONFIG.ButtonLeftOffset
    local Y = Viewport.Y - CONFIG.ButtonBottomOffset - Height
    return UDim2.fromOffset(math.max(5, X), math.max(5, Y))
end

local function ClampButtonPosition(X, Y)
    local Viewport = GetViewport()
    local Width = OpenButton.AbsoluteSize.X
    local Height = OpenButton.AbsoluteSize.Y
    local MaxX = math.max(5, Viewport.X - Width - 5)
    local MaxY = math.max(5, Viewport.Y - Height - 5)
    X = math.clamp(X, 5, MaxX)
    Y = math.clamp(Y, 5, MaxY)
    return UDim2.fromOffset(math.floor(X), math.floor(Y))
end

local function SetDefaultButtonPosition()
    if ButtonHasCustomPosition then return end
    OpenButton.Position = GetDefaultButtonPosition()
end
task.defer(SetDefaultButtonPosition)

local function ReClampOpenButton()
    local Position = OpenButton.Position
    OpenButton.Position = ClampButtonPosition(Position.X.Offset, Position.Y.Offset)
end

-- SHOW WINDOW
local function ShowWindow()
    if Transitioning or WindowVisible then return end
    Transitioning = true
    OpenButton.Visible = false
    Surface.Enabled = true
    HideButton.Active = true
    Root.GroupTransparency = 1
    local Fade = TweenService:Create(Root, TweenInfo.new(CONFIG.OpenTime, Enum.EasingStyle.Quint, Enum.EasingDirection.Out), {
        GroupTransparency = 0,
    })
    Fade:Play()
    Fade.Completed:Wait()
    WindowVisible = true
    Transitioning = false
end

-- HIDE WINDOW
local function HideWindow()
    if Transitioning or not WindowVisible then return end
    Transitioning = true
    local Fade = TweenService:Create(Root, TweenInfo.new(CONFIG.CloseTime, Enum.EasingStyle.Quint, Enum.EasingDirection.In), {
        GroupTransparency = 1,
    })
    Fade:Play()
    Fade.Completed:Wait()
    HideButton.Active = false
    Surface.Enabled = false
    WindowVisible = false
    OpenButton.Visible = true
    ReClampOpenButton()
    local CurrentX = OpenButton.Position.X.Offset
    local CurrentY = OpenButton.Position.Y.Offset
    OpenButton.Position = UDim2.fromOffset(CurrentX - 20, CurrentY)
    TweenService:Create(OpenButton, TweenInfo.new(0.28, Enum.EasingStyle.Quint, Enum.EasingDirection.Out), {
        Position = UDim2.fromOffset(CurrentX, CurrentY),
    }):Play()
    Transitioning = false
end
HideButton.Activated:Connect(HideWindow)

-- OPEN BUTTON DRAG
local function BeginPress(Input)
    if Pressing then return end
    Pressing = true
    Dragging = false
    ActiveInput = Input
    DragStart = Input.Position
    StartButtonPosition = OpenButton.Position
    PressToken += 1
    local Token = PressToken
    PressOpenVisual()
    task.delay(CONFIG.DragHoldTime, function()
        if Pressing and ActiveInput == Input and PressToken == Token then
            Dragging = true
        end
    end)
end

local function EndPress()
    if not Pressing then return end
    local WasDragging = Dragging
    Pressing = false
    Dragging = false
    ActiveInput = nil
    DragStart = nil
    StartButtonPosition = nil
    PressToken += 1
    ReleaseOpenVisual()
    if not WasDragging then ShowWindow() end
end

OpenButton.InputBegan:Connect(function(Input)
    if Input.UserInputType == Enum.UserInputType.Touch or Input.UserInputType == Enum.UserInputType.MouseButton1 then
        BeginPress(Input)
    end
end)
OpenButton.InputEnded:Connect(function(Input)
    if Input == ActiveInput then EndPress() end
end)
UserInputService.InputChanged:Connect(function(Input)
    if not Pressing or not Dragging or not ActiveInput or not DragStart or not StartButtonPosition then return end
    local IsMoveInput = Input.UserInputType == Enum.UserInputType.Touch or Input.UserInputType == Enum.UserInputType.MouseMovement
    if not IsMoveInput then return end
    local Delta = Input.Position - DragStart
    local NewX = StartButtonPosition.X.Offset + Delta.X
    local NewY = StartButtonPosition.Y.Offset + Delta.Y
    OpenButton.Position = ClampButtonPosition(NewX, NewY)
    ButtonHasCustomPosition = true
end)
UserInputService.InputEnded:Connect(function(Input)
    if Input == ActiveInput then EndPress() end
end)

-- RESIZE SAFETY
task.spawn(function()
    while ControlGui.Parent do
        task.wait(0.5)
        if OpenButton.Visible and not WindowVisible then ReClampOpenButton() end
    end
end)

-- CAMERA
local Camera = Workspace.CurrentCamera
local LastCameraCF = Camera and Camera.CFrame
local CurrentSway = Vector3.zero

-- WORLD POSITION
local function GetScreenWorldPosition()
    Camera = Workspace.CurrentCamera
    if not Camera then return nil end
    local Viewport = Camera.ViewportSize
    local Aspect = Viewport.X / math.max(Viewport.Y, 1)
    local FOV = math.rad(Camera.FieldOfView)
    local HalfHeight = math.tan(FOV / 2) * CONFIG.Distance
    local HalfWidth = HalfHeight * Aspect
    local X = (CONFIG.ScreenX - 0.5) * 2 * HalfWidth
    local Y = (0.5 - CONFIG.ScreenY) * 2 * HalfHeight
    return Camera.CFrame.Position
        + Camera.CFrame.LookVector * CONFIG.Distance
        + Camera.CFrame.RightVector * X
        + Camera.CFrame.UpVector * Y
end

-- CAMERA FOLLOW
RunService.RenderStepped:Connect(function(dt)
    Camera = Workspace.CurrentCamera
    if not Camera or not Panel or not Panel.Parent then return end
    if not LastCameraCF then LastCameraCF = Camera.CFrame end
    local Character = LocalPlayer.Character
    local RootPart = Character and Character:FindFirstChild("HumanoidRootPart")
    local Delta = LastCameraCF:ToObjectSpace(Camera.CFrame)
    local PitchDelta, YawDelta, RollDelta = Delta:ToOrientation()
    local LocalVelocity = Vector3.zero
    if RootPart then
        LocalVelocity = RootPart.CFrame:VectorToObjectSpace(RootPart.AssemblyLinearVelocity)
    end
    local TargetPitch = 0
    local TargetYaw = 0
    local TargetRoll = 0

    -- While spectating, target movement is also moving the local camera.
    -- Suppress camera/movement sway so the panel does not swing away from input.
    if SpectateState.Active then
        CurrentSway = Vector3.zero
    else
        if CONFIG.CameraSway then
            TargetPitch += math.clamp(PitchDelta * 0.7, -CONFIG.MaxPitch, CONFIG.MaxPitch)
            TargetYaw += math.clamp(-YawDelta * 0.5, -CONFIG.MaxYaw, CONFIG.MaxYaw)
            TargetRoll += math.clamp(-YawDelta * 0.55, -CONFIG.MaxRoll, CONFIG.MaxRoll)
        end
        if CONFIG.MovementSway then
            TargetPitch += math.clamp(-LocalVelocity.Z * 0.0009, -math.rad(1.3), math.rad(1.3))
            TargetYaw += math.clamp(-LocalVelocity.X * 0.0010, -math.rad(1.7), math.rad(1.7))
            TargetRoll += math.clamp(-LocalVelocity.X * 0.0010, -math.rad(1.5), math.rad(1.5))
        end
        CurrentSway = CurrentSway:Lerp(Vector3.new(TargetPitch, TargetYaw, TargetRoll), math.clamp(dt * 9, 0, 1))
    end
    local Position = GetScreenWorldPosition()
    if not Position then return end
    local TargetCF = CFrame.lookAt(Position, Position + Camera.CFrame.LookVector, Camera.CFrame.UpVector)
    TargetCF = TargetCF * CFrame.Angles(
        CONFIG.WorldPitch + CurrentSway.X,
        CONFIG.WorldYaw + CurrentSway.Y,
        CONFIG.WorldRoll + CurrentSway.Z
    )
    local DistanceFromTarget = (Panel.Position - TargetCF.Position).Magnitude
    if SpectateState.Active then
        -- Keep the clickable 3D surface locked to the current camera while spectating.
        Panel.CFrame = TargetCF
    elseif DistanceFromTarget > 20 then
        Panel.CFrame = TargetCF
    else
        Panel.CFrame = Panel.CFrame:Lerp(TargetCF, math.clamp(dt * CONFIG.FollowSpeed, 0, 1))
    end
    LastCameraCF = Camera.CFrame
end)

-- INITIAL PANEL POSITION
local StartPosition = GetScreenWorldPosition()
Camera = Workspace.CurrentCamera
if StartPosition and Camera then
    local StartCF = CFrame.lookAt(StartPosition, StartPosition + Camera.CFrame.LookVector, Camera.CFrame.UpVector)
    StartCF = StartCF * CFrame.Angles(CONFIG.WorldPitch, CONFIG.WorldYaw, CONFIG.WorldRoll)
    Panel.CFrame = StartCF
    LastCameraCF = Camera.CFrame
end

-- INITIAL CATEGORY
RightMode = 1
UpdateCategoryVisual()

-- INITIAL VOICE
CheckLocalVoiceStatus()
LastVoiceCheck = LocalVoiceEnabled
UpdateVoiceHeader()

-- FINAL STATE
WindowVisible = true
Transitioning = false
Root.GroupTransparency = 0
Surface.Enabled = true
HideButton.Active = true
OpenButton.Visible = false
RefreshSpectateButtons()

-- CLEAN CAMERA ON CHARACTER RESPAWN
LocalPlayer.CharacterAdded:Connect(function()
    task.wait(0.20)
    if not SpectateState.Active then return end
    local CameraNow = Workspace.CurrentCamera
    if not CameraNow then return end
    pcall(function()
        if SpectateState.Target and SpectateState.Target.Parent == Players then
            AttachSpectateCamera(SpectateState.Target)
        end
    end)
end)

-- FINAL CAMERA RECOVERY
task.spawn(function()
    while Root.Parent do
        task.wait(0.25)
        if SpectateState.Active and SpectateState.Target then
            local Target = SpectateState.Target
            if not Target.Parent or Target == LocalPlayer then
                StopSpectating()
            end
        end
    end
end)

-- DEBUG
print("================================================")
print("NX 3D SCI-FI ROBLOX BUBBLE CHAT DISPLAY V16.0")
print("REAL ROBLOX BUBBLE CHAT ONLY : ON")
print("JOIN / LEAVE : ON")
print("RIGHT CATEGORY SWITCH : ON")
print("CATEGORY 1 EVENTS : ON")
print("CATEGORY 2 PLAYER STATUS : ON")
print("PLAYER COUNT : ON")
print("PLAYER HP / MAX HP : ON")
print("PLAYER HP COLOR : ON")
print("TEAM COLOR : ON")
print("LIVE HEALTH UPDATE : ON")
print("LOCAL VOICE LINK : ON")
print("LOCAL VOICE ENABLED : " .. tostring(LocalVoiceEnabled))
print("AUDIODEVICEINPUT MULTI SEARCH : ON")
print("AUDIODEVICEINPUT CHILD MONITOR : ON")
print("ANALYZER OPTIONAL : ON")
print("MIC UNKNOWN FALLBACK : REMOVED FOR LOCAL PLAYER")
print("MIC LINKED STATUS : ON")
print("MIC READY STATUS : ON")
print("MIC MUTED STATUS : ON")
print("MIC SPEAKING STATUS : ON")
print("VOICE RECORDING : OFF")
print("SPEECH TO TEXT : OFF")
print("PLAYER CAMERA / SPECTATE : ON")
print("CAM // VIEW : ON")
print("CAM // ACTIVE : ON")
print("TARGET STREAM PREFETCH : ON")
print("TARGET RESPAWN RECOVERY : ON")
print("TARGET LEAVE RECOVERY : ON")
print("LOCAL CAMERA RESTORE : ON")
print("MOBILE TOUCH : ON")
print("MOBILE DRAG : ON")
print("================================================")

90,322 chars · codepastes.com