-- Replay Recorder v0.21 Lite — passive local-file test adapter.
-- Optional sparse protectionEvents and soundEvents extensions; v2 replay format unchanged.
-- Sound recording observes permitted in-game Sound instances; no microphone, voice chat or audio bytes.
-- For authorized sessions only. No protection manipulation, console dependency or extra action logging.
-- Replicated flags are observations, not proof of server enforcement or ability attribution.
-- Use only in an experience or test session where the developer permits recording this way.
-- Passive OnClientEvent listeners only; no remote firing/invocation, hooks, automation or network upload.
-- Records visible match actors, ball, camera, scoreboard and replicated match-stat changes for all active players.
-- Reads replicated Stunned rising edges and Sliding state for offline tackle animation.
-- No shot/steal-attempt/dribble events. A stun does not prove an ankle break.
-- Reads replicated style at 5 Hz; writes changes and chunk baselines.
-- Records assigned positions from known player/character fields and match UI.
-- Retains the last observed position for the same active player/team when UI is closed.
-- Records observed ability-slot names and cooldown changes, not raw network traffic.
-- Awakening: -1 unknown, 0 unavailable, 1 candidate ready, 2 active.
-- No live ability overlay. Data is for authorized post-match replay only.
-- Names are in-game usernames of match participants; obtain permission before recording or sharing.
-- No user IDs are written to disk.
-- F6 starts, F7 stops; on-screen button is a fallback.
local Players = game:GetService("Players")
local RS = game:GetService("ReplicatedStorage")
local RunService = game:GetService("RunService")
local HttpService = game:GetService("HttpService")
local UserInputService = game:GetService("UserInputService")
local SoundService = game:GetService("SoundService")
local me = Players.LocalPlayer
local ROOT = "ReplayRecordings"
assert(type(writefile)=="function" and type(makefolder)=="function" and type(isfolder)=="function", "Local filesystem API unavailable")
if not isfolder(ROOT) then makefolder(ROOT) end
local pg = me:WaitForChild("PlayerGui")
local old = pg:FindFirstChild("ReplayRecorder06")
if old then warn("[Replay] Recorder already running"); return end
local gui = Instance.new("ScreenGui")
gui.Name = "ReplayRecorder06"
gui.ResetOnSpawn = false
gui.Parent = pg
local panel = Instance.new("Frame")
panel.Size = UDim2.fromOffset(260, 83)
panel.Position = UDim2.new(1,-275,0,15)
panel.BackgroundColor3 = Color3.fromRGB(22,29,39)
panel.Parent = gui
local button = Instance.new("TextButton")
button.Size = UDim2.new(1,-12,0,37)
button.Position = UDim2.fromOffset(6,6)
button.Text = "● Record"
button.BackgroundColor3 = Color3.fromRGB(58,105,157)
button.TextColor3 = Color3.new(1,1,1)
button.TextSize = 17
button.Parent = panel
local status = Instance.new("TextLabel")
status.Size = UDim2.new(1,-12,0,29)
status.Position = UDim2.fromOffset(6,47)
status.BackgroundTransparency = 1
status.TextColor3 = Color3.fromRGB(207,218,232)
status.TextSize = 13
status.Text = "Lite · ready"
status.Parent = panel
-- Set RATE to 60 if smoother POV playback is more important than file size.
local RATE, STATS_RATE, CHUNK_SECONDS = 30, 5, 5
local BOARD_RATE = 1 -- one scoreboard snapshot check per second
local MAX_FRAMES = RATE * 60 * 30 -- 30-minute recording guard
local counterNames = {"AnkleBreakers","Assists","FilteredPasses","Goals","Points","Saves","Steals","Ping"}
local playerStatNames = {"Style","Flow"}
local counterEvents = {AnkleBreakers="ankle_break",Assists="assist",FilteredPasses="pass_count",Goals="goal_credit",Saves="save",Steals="steal"}
local session, accumulator, busy = nil, 0, false
local function round(x) return math.round(x*1000)/1000 end
local function cf(c)
    local a,b,d = c:ToOrientation()
    return {round(c.X),round(c.Y),round(c.Z),round(a),round(b),round(d)}
end
local function saveValue(folder,name,data)
    writefile(folder .. "/" .. name, HttpService:JSONEncode(data))
end
local function path(root,...)
    for _,name in ipairs({...}) do
        if not root then return nil end
        root=root:FindFirstChild(name)
    end
    return root
end
local function part(obj) return obj and obj:IsA("BasePart") and obj or nil end
local function label(obj) return obj and obj:IsA("TextLabel") and obj.Text or nil end
local function team(p) return p.Team and p.Team.Name or "" end
local function idFor(s,p)
    if s.ids[p] then return s.ids[p] end
    s.nextId += 1
    local id = s.nextId; s.ids[p] = id
    local info = {id = id, team = team(p), kind = "player", username = p.Name}
    s.players[tostring(id)] = info
    return id
end
local function readValue(folder,name)
    local obj=folder and folder:FindFirstChild(name)
    if obj and (obj:IsA("NumberValue") or obj:IsA("IntValue") or obj:IsA("BoolValue") or obj:IsA("StringValue")) then
        return obj.Value
    end
    return nil
end
-- Read only the known scoreboard rows, never scan the whole GUI.
-- A hidden or unpopulated GUI may have stale values; replicated counters take priority.
local boardKeys={"Points","Goals","Assists","Saves","Steals","Ping"}
-- Role codes observed in the supplied PickTeam hierarchy, plus common position codes
-- accepted only in explicitly named role fields (never from world coordinates).
local knownRoles={CF=true,CFL=true,CFR=true,CM=true,GK=true,LM=true,LW=true,RM=true,RW=true}
local extraRoles={CB=true,LB=true,RB=true,CDM=true,CAM=true,LCM=true,RCM=true,LCB=true,RCB=true,ST=true,LS=true,RS=true}
local roleKeys={"Position","Pos","Role","PlayerPosition","TeamPosition","AssignedPosition"}
local function normalizeRole(v,allowExtra)
    if type(v)~="string" or #v>24 then return nil end
    v=v:match("^%s*(.-)%s*$"):upper()
    if knownRoles[v] or (allowExtra and extraRoles[v]) then return v end
    return nil
end
local function roleText(o)
    if o and (o:IsA("TextLabel") or o:IsA("TextButton")) then return o.Text end
    return nil
end
local function isGuiVisible(o)
    while o and o~=pg do
        if o:IsA("GuiObject") and not o.Visible then return false end
        if o:IsA("LayerCollector") and not o.Enabled then return false end
        o=o.Parent
    end
    return o==pg
end
local function sameUsername(text,p)
    if type(text)~="string" then return false end
    return text:match("^%s*@?(.-)%s*$"):lower()==p.Name:lower()
end
local function scoreboardRole(ui)
    if not ui then return nil end
    -- First prefer explicitly named cells, including a nested text label.
    for _,key in ipairs(roleKeys) do
        local cell=ui:FindFirstChild(key)
        if cell then
            local v=normalizeRole(roleText(cell),true)
            if v and isGuiVisible(cell) then return v end
            local found=nil
            for _,o in ipairs(cell:GetDescendants()) do
                local r=normalizeRole(roleText(o),true)
                if r and isGuiVisible(o) then
                    if found and found~=r then return nil end
                    found=r
                end
            end
            if found then return found end
        end
    end
    -- The old probe omitted nonnumeric text. Read known role codes inside this row.
    -- Exclude the username and stat cells, and reject ambiguous matches.
    local found=nil
    for _,o in ipairs(ui:GetDescendants()) do
        local r=normalizeRole(roleText(o),false)
        if r and isGuiVisible(o) then
            local root=o
            while root.Parent and root.Parent~=ui do root=root.Parent end
            local n=root.Name
            if n~="Plr" and n~="Points" and n~="Goals" and n~="Assists" and n~="Saves" and n~="Steals" and n~="Ping" then
                if found and found~=r then return nil end
                found=r
            end
        end
    end
    return found
end
local function replicatedRole(p)
    -- These names are candidates, not confirmed BLR fields. Accept only role strings.
    local found=nil
    local function check(v)
        local role=normalizeRole(v,true)
        if role then
            if found and found~=role then return false end
            found=role
        end
        return true
    end
    for _,obj in ipairs({p,p.Character or p}) do
        for _,key in ipairs(roleKeys) do
            if not check(obj:GetAttribute(key)) or not check(readValue(obj,key)) then return nil end
        end
    end
    for _,obj in pairs({p:FindFirstChild("PlayerStats"),p:FindFirstChild("GameStats"),p.Character and p.Character:FindFirstChild("Values")}) do
        for _,key in ipairs(roleKeys) do
            if not check(obj:GetAttribute(key)) or not check(readValue(obj,key)) then return nil end
        end
    end
    return found
end
local function pickTeamRole(p,tm)
    local root=path(pg,"PickTeam",tm)
    if not root or not isGuiVisible(root) then return nil end
    local found=nil
    for _,slot in ipairs(root:GetChildren()) do
        local role=normalizeRole(slot.Name,false)
        if role then
            local name=slot:FindFirstChild("plr")
            if name and isGuiVisible(name) and sameUsername(roleText(name),p) then
                if found and found~=role then return nil end
                found=role
            end
        end
    end
    return found
end
local function snapshotBoard(s,frame)
    local rows={}
    local guiBoard=pg:FindFirstChild("Leaderbord")
    local bg=guiBoard and guiBoard:FindFirstChild("BG")
    local visible=guiBoard and guiBoard:IsA("ScreenGui") and guiBoard.Enabled and bg and bg.Visible
    local guiRows={}
    local activeRoles={}
    if visible then
        for _,tm in ipairs({"Home","Away"}) do
            local list=path(bg,"TeamsList",tm,"StatsList")
            if list then
                for _,row in ipairs(list:GetChildren()) do
                    local username=roleText(row:FindFirstChild("Plr"))
                    if username then guiRows[tm..":"..username:match("^%s*@?(.-)%s*$"):lower()]=row end
                end
            end
        end
    end
    for _,p in ipairs(Players:GetPlayers()) do
        local tm=team(p)
        if tm=="Home" or tm=="Away" then
            local id=idFor(s,p)
            local row={id=id,team=tm}
            local gameStats=p:FindFirstChild("GameStats")
            local ui=guiRows[tm..":"..p.Name:lower()]
            for _,key in ipairs(boardKeys) do
                local v=readValue(gameStats,key)
                if type(v)~="number" and ui then v=tonumber(label(ui:FindFirstChild(key))) end
                if type(v)=="number" and v==v and v>=0 and v<1e12 then row[key]=math.round(v) end
            end
            -- Prefer the visible official table, then an explicit replicated role,
            -- then the visible team-selection slot matched by exact username.
            local pos=scoreboardRole(ui)
            local source=pos and "scoreboard" or nil
            if not pos then pos=replicatedRole(p); if pos then source="replicated" end end
            if not pos then pos=pickTeamRole(p,tm); if pos then source="pickTeam" end end
            local previous=s.lastRoles[id]
            if pos then
                s.lastRoles[id]={team=tm,position=pos,source=source}
                row.position=pos
            elseif previous and previous.team==tm then
                row.position=previous.position
            else
                s.lastRoles[id]=nil
            end
            activeRoles[id]=true
            table.insert(rows,row)
        end
    end
    for id in pairs(s.lastRoles) do
        if not activeRoles[id] then s.lastRoles[id]=nil end
    end
    table.sort(rows,function(a,b) return a.id<b.id end)
    -- Stable fingerprint independent of JSON dictionary ordering.
    local bits={}
    for _,r in ipairs(rows) do
        local fields={tostring(r.id),r.team,r.position or "-"}
        for _,key in ipairs(boardKeys) do table.insert(fields,tostring(r[key] or "-")) end
        table.insert(bits,table.concat(fields,":"))
    end
    local signature=table.concat(bits,"|")
    if s.lastBoard~=signature or #s.frames==0 then
        frame.playerScoreboard=rows
        s.lastBoard=signature
    end
end
local function actorId(s,tm)
    local key="npc:"..tm
    if s.ids[key] then return s.ids[key] end
    s.nextId+=1
    local id=s.nextId; s.ids[key]=id
    s.players[tostring(id)]={id=id,team=tm,kind="npc",displayName=tm.." AI GK"}
    return id
end
local function metadata(s,complete)
    return {version=2,recorderVersion="0.21-lite",cutsceneSchema=1,soundSchema=1,droppedSoundEvents=s.droppedSoundEvents,id=s.id,createdAt=s.createdAt,
        placeId=game.PlaceId, sampleRate=RATE,rotationUnit="radians",positionUnit="studs",
        frames=s.count,chunks=s.chunks,duration=s.lastT,complete=complete,includeNames=true,statsSampleRate=STATS_RATE,scoreboardSampleRate=BOARD_RATE,extensions={"npc","localStats","events","playerStyles","playerScoreboard","abilitySlots","awakeningStates","flowStates","slideState","protectionEvents","flightVisuals","cutsceneFlag","soundEvents"},flightSchema=1,gravity=workspace.Gravity,protectionSchema=1,droppedProtectionEvents=s.droppedProtectionEvents, eventMode="match-counters-stuns-and-ability-state",abilityClock="server clock or tick (candidate; raw preserved)",awakeningReadySource="PlayerStats.Awakening (unverified)",counterScope="replicated-active-players",localPlayerId=s.localId,droppedAbilityUpdates=s.droppedAbilityUpdates}
end
local function flush(s,complete)
    if #s.frames > 0 then
        local nextChunk = s.chunks+1
        saveValue(s.folder,string.format("chunk_%06d.json",nextChunk),s.frames)
        s.chunks = nextChunk
        s.frames = {}
    end
    saveValue(s.folder,"players.json",s.players)
    saveValue(s.folder,"metadata.json",metadata(s,complete))
    s.lastFlush = os.clock()
end
-- Only the packet shape observed in the supplied ability probes is accepted.
-- User IDs are used for attribution in memory; only replay actor IDs reach disk.
local function validNumber(v)
    return type(v)=="number" and v==v and math.abs(v)<math.huge
end
local function activePlayer(p)
    return p and (team(p)=="Home" or team(p)=="Away")
end
local function slotValue(delta, key)
    local field=delta[key]
    if type(field)=="table" and field.o==0 then return field.v end
    return nil
end
local function queueEvent(s,e)
    -- Bound memory if recording is paused or a malformed source floods updates.
    if #s.pendingEvents<4096 then table.insert(s.pendingEvents,e)
    else s.droppedAbilityUpdates+=1 end
end
local function onAbilityPacket(payload)
    local s=session
    if not s or s.paused or type(payload)~="table" then return end
    local now=round(os.clock()-s.started)
    local serverNow=workspace:GetServerTimeNow()
    local localTick=tick()
    for _,packet in ipairs(payload) do
        if type(packet)=="table" and packet[1]==string.char(1) and type(packet[3])=="table" then
            for uid,slots in pairs(packet[3]) do
                local n=tonumber(uid)
                local p=n and n>0 and n%1==0 and Players:GetPlayerByUserId(n) or nil
                if activePlayer(p) and type(slots)=="table" then
                    local id=idFor(s,p)
                    local kit=s.abilityStates[id]
                    if not kit then kit={};s.abilityStates[id]=kit end
                    local updates={}
                    for i=1,3 do
                        local delta=slots[tostring(i)] or slots[i]
                        if type(delta)=="table" then
                            local name=slotValue(delta,"name")
                            local cd=slotValue(delta,"cooldown")
                            if type(name)~="string" or #name==0 or #name>128 or not utf8.len(name) then name=nil end
                            if not validNumber(cd) or cd<0 or cd>1e12 then cd=nil end
                            if name~=nil or cd~=nil then
                                local previous=kit[i] or {}
                                local changedName=name~=nil and name~=previous.name
                                local changedCD=cd~=nil and cd~=previous.rawCooldown
                                if changedName or changedCD then
                                    local e={t=now,type="ability_slot",playerId=id,slot=i,source="replicated",nameChanged=changedName,cooldownChanged=changedCD}
                                    if name~=nil then previous.name=name;previous.nameAt=now end
                                    -- An omitted name is a partial update, not a default variant.
                                    e.name=previous.name or "?"
                                    if changedCD then
                                        previous.rawCooldown=cd
                                        local remaining=cd-serverNow
                                        local tickRemaining=cd-localTick
                                        -- The timestamp's epoch has not yet been verified in a live run.
                                        -- Preserve the raw value and reference clock even if conversion fails.
                                        previous.serverAt=round(serverNow)
                                        previous.observedAt=now
                                        previous.tickAt=round(localTick)
                                        previous.cdUntil=nil;previous.clock=nil
                                        local serverPlausible=math.abs(remaining)<=600
                                        local tickPlausible=math.abs(tickRemaining)<=600
                                        if cd==0 then previous.cdUntil=now;previous.clock="zero"
                                        elseif serverPlausible and (not tickPlausible or math.abs(remaining-tickRemaining)<=2) then
                                            previous.cdUntil=round(now+math.max(0,remaining));previous.clock="server"
                                        elseif tickPlausible and not serverPlausible then
                                            previous.cdUntil=round(now+math.max(0,tickRemaining));previous.clock="tick"
                                        end
                                        e.rawCooldown=cd;e.serverAt=previous.serverAt;e.tickAt=previous.tickAt
                                        e.cdUntil=previous.cdUntil;e.clock=previous.clock
                                    end
                                    kit[i]=previous
                                    table.insert(updates,e)
                                end
                            end
                        end
                    end
                    -- A multi-slot refresh/reset is not multiple confirmed ability uses.
                    for _,e in ipairs(updates) do
                        e.batchSize=#updates
                        queueEvent(s,e)
                    end
                    if #updates>0 then s.dirtyAbility[id]=true end
                end
            end
        end
    end
end
local function copyKit(kit)
    local out={}
    for i=1,3 do
        local slot=kit and kit[i] or {}
        out[i]={slot=i,name=slot.name or "?",cdUntil=slot.cdUntil,rawCooldown=slot.rawCooldown,
            serverAt=slot.serverAt,tickAt=slot.tickAt,clock=slot.clock,observedAt=slot.observedAt}
    end
    return out
end
local function awakeningState(p)
    local stats=p:FindFirstChild("PlayerStats")
    local ready=readValue(stats,"Awakening")
    local active=readValue(stats,"InAwakening")
    if type(ready)~="boolean" then ready=nil end
    if type(active)~="boolean" then active=nil end
    if active==true then return 2,ready,active end
    if active==false and ready==true then return 1,ready,active end
    if active==false and ready==false then return 0,ready,active end
    return -1,ready,active
end
-- Invalidation prevents carrying a base ability name into a different kit.
-- Retain cooldown observations, but do not guess the new variant's name.
local function invalidateNames(s,id)
    local kit=s.abilityStates[id]
    if not kit then return end
    for _,slot in pairs(kit) do slot.name=nil;slot.nameAt=nil end
    s.dirtyAbility[id]=true
end
local watched={}
local function watchAbilityRemote(obj)
    if watched[obj] or not obj:IsA("RemoteEvent") then return end
    local parent=obj.Parent
    if obj.Name=="RemoteEvent" and parent and parent.Name=="__ReplicatorInternal" and parent.Parent==RS then
        watched[obj]=obj.OnClientEvent:Connect(function(payload)
            local ok,err=pcall(onAbilityPacket,payload)
            if not ok then warn("[Replay] Ability packet ignored: "..tostring(err)) end
        end)
    elseif obj.Name=="AwakenEveryone" and obj==path(RS,"Packages","Knit","Services","AwakeningService","RE","AwakenEveryone") then
        watched[obj]=obj.OnClientEvent:Connect(function(p)
            local s=session
            if not s or s.paused or typeof(p)~="Instance" or not p:IsA("Player") or not activePlayer(p) then return end
            local id=idFor(s,p)
            queueEvent(s,{t=round(os.clock()-s.started),type="awakening_start",playerId=id,source="replicated"})
        end)
    end
end
for _,obj in ipairs(RS:GetDescendants()) do watchAbilityRemote(obj) end
RS.DescendantAdded:Connect(watchAbilityRemote)
RS.DescendantRemoving:Connect(function(obj)
    if watched[obj] then watched[obj]:Disconnect();watched[obj]=nil end
end)

-- Sparse event capture. Existing ability-slot observations remain separate.
-- Character/ball identity changes invalidate old intervals instead of fabricating end times.
local function protectionEvent(s,e)
    if session~=s or s.paused then return end
    e.t=round(os.clock()-s.started)
    if #s.pendingProtection<1024 then table.insert(s.pendingProtection,e)
    else s.droppedProtectionEvents+=1 end
end
local function disconnectProtection(w)
    if w and w.connection then w.connection:Disconnect() end
end
local function observePlayerProtection(s,id,model)
    local w=s.protectionPlayers[id]
    if w and w.object==model then return end
    if w then
        disconnectProtection(w)
        if w.value==true then protectionEvent(s,{kind="player",playerId=id,state="unknown",reason="character_changed"}) end
    end
    w={object=model,value=model:GetAttribute("IFrames")}
    s.protectionPlayers[id]=w
    if w.value==true then protectionEvent(s,{kind="player",playerId=id,state="active",baseline=true}) end
    w.connection=model:GetAttributeChangedSignal("IFrames"):Connect(function()
        if session~=s or s.paused or s.protectionPlayers[id]~=w then return end
        local v=model:GetAttribute("IFrames")
        if v==w.value then return end
        local prior=w.value;w.value=v
        if v==true then protectionEvent(s,{kind="player",playerId=id,state="active"})
        elseif prior==true then protectionEvent(s,{kind="player",playerId=id,state=v==false and "inactive" or "unknown"}) end
    end)
end
local function observeBallProtection(s)
    local ref=RS:FindFirstChild("Football")
    local ball=ref and ref:IsA("ObjectValue") and ref.Value or nil
    local obj=ball and ball:FindFirstChild("IFrame")
    if obj and not (obj:IsA("NumberValue") or obj:IsA("IntValue")) then obj=nil end
    local w=s.protectionBall
    if w and w.object==obj then return end
    if w then disconnectProtection(w)
        if w.object then protectionEvent(s,{kind="ball",state="unknown",reason="ball_changed"}) end
    end
    w={object=obj};s.protectionBall=w
    if not obj then return end
    local function read(baseline)
        if session~=s or s.paused or s.protectionBall~=w then return end
        local v=obj.Value
        if not validNumber(v) or v==w.value then return end
        local prior=w.value;w.value=v
        local server=workspace:GetServerTimeNow()
        local localTime=tick()
        local sr,lr=v-server,v-localTime
        -- Preserve both clocks; do not silently choose the wrong epoch.
        if sr>0 and sr<600 or lr>0 and lr<600 then
            protectionEvent(s,{kind="ball",state="expiry",expiry=v,serverAt=server,tickAt=localTime,baseline=baseline or nil})
        elseif prior and not baseline then
            protectionEvent(s,{kind="ball",state="expiry",expiry=v,serverAt=server,tickAt=localTime})
        end
    end
    read(true)
    w.connection=obj:GetPropertyChangedSignal("Value"):Connect(function() read(false) end)
end
local function releaseProtection(s)
    for _,w in pairs(s.protectionPlayers) do disconnectProtection(w) end
    disconnectProtection(s.protectionBall)
    s.protectionPlayers={};s.protectionBall=nil
end

-- Only existing authorized SFX pack IDs, observed in active world/SoundService.
-- Captures metadata, not audio bytes, and does not alter sound objects.
local knownSoundIds={}
for id in string.gmatch([=[9119330018 79263878516374 120661884046560 130106659210550 112139267787721 114268289837235 9113730389 93268114291529 92163609941147 122581722207104 87071653527823 97678110602344 133521013314160 112613716597747 110327941594072 94358721070873 90172864068686 103479539146085 100214648262799 109966909546915 137204393637410 131169591307358 124085157349474 102526503754780 111319122696339 75662912409190 122454171568092 71013348459914 130160642168529 108430000262370 117145922286901 71842574264206 110738149627396 124349799538369 106067337215563 130318372476996 138346326403569 111251806354504 75202738898209 106188860216106 111388604906680 117484059047044 85597639173190 127737608651016 84241251967126 74716730496782 72370994221206 136595176737214 127957721287298 83956155866445 74957886435813 136772847051587 129947968339189 106534089156295 89748463027534 138575020338227 85597821981046 123960575409898 76582544173888 109319097869010 99603546714784 72837079861287 122026051013130 88576511056487 123558818689407 112210275773048 135807442091454 119122041632953 106941014053145 98299760463308 71980621260703 102597076019991 10066947742 122466602810942 78838552883051 72573885785070 76527561254553 97974901528313 112116221186850 123545852285640 114685791697346 71239050415797 1598682218 85109796952631 104485926442314 139448543006653 97018321811807 78133252566941 87842604810354 182006959 86041857060690 130778877089747 94820154847932 138638196479097 120828428384969 78120713657116 126622292512349 134247343431025 112950582280331 137667834498131 10066968815 136974219864642 102040873036104 115491478404401 82859064947899 130234884280898 84216236288764 87264329917091 109239991425663 110551839834810 83001895956471 128930650404494 117462367902049 115119123744098 114791460222103 76885411525189 119388074154530 71630500390900 71460385005137 119606927386407 94536638178486 108075201754434 77409401277548 79567795299825 113553259657667 80228980239257 125861161431934 118335490531351 74437661751313 97142417965279 78114975561695 111070089795524 88224788604554 78087945140636 113366827816309 139287567903973 138530637599764 115925749776939 82736532997225 124472219765103 91157849845842 110506790894628 94482749002455 110477672474338 115106320186201 98291998466374 131723445814619 126710684667438 140361772487380 103492247842245 81701471278100 123929318099062 137195927347607 81238591801808 127485350051683 136229575814652 117943275103459 131982665828880 83638569769508 94569998688213 138176643650034 135564047880427 96956571357266 126562595149269 84498304994174 132926905918474 107834577367489 76368307810248 79650547235559 128328531285002 140032269952728 307631257 111103600439352 101482510886144 95259698344445 115391780004210 97756468699107 104055854332259 71527575992804 105277278296106 115656261435707 139379034617244 88615793176422 70955122392828 136610283376574 130842167268753 96253160285277 99172754752901 104519836941244 105382441623452 98856576933091 113612302008766 87188691581489 116963187500821 103007664006754 74251251778555 94114880410510 136534391710664 97195686761666 133670968984347 93822554643168 104429476769390 118517359816985 116018029240420 113295799802784 5302239409 116858908110847 118929117261942 107212616291562 129710534812357 108724167767360 118562078110889 101552248744222 103608551037838 124938628635677 122502071281578 79710575271302 3120909354 80389848347522 92740948413438 106848162386327 124714722540875 127849703613704 85592589816092 89302345973415 117964891879796 97325692113995 87659898719454 108759607629764 83945430847034 84031024007043 129214255901629 100174094275216 114639714267596 99363966067109 133167627659084 97901587867373 93645294051336 72934735020597 125716037698038 98818389864005 122141299533721 126601453178337 99871780976361 110914552117587 106809343618166 137702041847696 91138452407505 126997363626148 99917747611694 107252614204531 122605419314648 10066931761 83932996842405 131296937142404 75300088673900 94788632306690 124350049180174 103992956890267 112506517970344 79847522632575 120680137283097 107007231517809 73370025639690 88535703434975 134489559006052 122281264426637 72947081484636 113405338589053 105360891282635 140258360346402 131624473867218 121998672703891 118531294574165 131171856523502 83773489739884 125157666181239 87934017425516 137898074597995 79087577094082 139352525643631 94452899708910 127184416691371 127676239805594 128511034452385 128146176651360 113712240324946 136752061425033 97414382476423 81083234720233 74394247410283 91395094947081 79827965121108 115386871126803 116507791177884 140157695892853 132388230417380 76119882798079 9119328220 9119325512 9119328727 130198223037907 117196191018019 79928462117385 70981014513587 95837259432401 84310205104035 121189114513178 122619811033994 83883172062770 126937128509726 85079705772361 109325054216623 122084880835820 128643780386047 127680120341605 79902636220034 70489242737427 92141505191372 108468436125376 122054416608988 94159423051039 91848259904925 80808634080268 126852796489849 91347823295203 83870774172572 84428418412261 104819772348000 117030793763722 113139602822087 140031621003383 92527014901959 136779489759319 85155550378142 108500097722640 90526962147956 115941332463107 81294132390344 115974463715809 116288198539265 118572622249338 103990698420453 106828204518733 112471164975239 98835517246116 81142151584885 84805389258644 127380695058949 72916720216026 115871015645845 75236089934377 87598080907932 119149377037086 92900060861900 15675081158 122082558554365 123840493627629 120318891319687 122141680705278 125254728581676 126853357660283 85016782787064 93099637363091 119255985267570 124703116414000 81069599311398 76044590002495 88003461953471 130769476806873 70694180166591 110873747104588 101668898208868 115024767810969 74770116748999 93531698041952 111099473486911 76709779075029 79614753419957 90496012595207 135838687885833 89125945380761 116603329134754 115059481228547 72049078891757 88151930747419 115992174888220 113267257397181 70984909853207 93296527041160 139764809632969 78700102314601 95193723481385 132021404861429 104254232420833 93483400200417 109361864285981 131332812348429 78768820615277 131975498080264 120696746517914 125649992785383 140547461944084 130514760145642 123664368870639 92890926490193 124894724739837 122418535991548 91704776522895 119055660717588 133017267838378 98098289046936 140244445719921 138276171697556 94492681795087 124115686619212 113191278066403 132783435319085 127041510518470 126142055270384 93544238246869 128865860970660 91551316973899 76446984729172 130161417591568 92927102094794 134580727342426 83843997923733 70425764183046 73642867679283 89251215789096 96987640229295 80697486848094 119590221404109 132938485884734 4590662766 92548589985662 122250871251243 83454428180536 96638696108996 84391120174427 70582458895457 129013539925971 116148296911200 101812599130334 116624987712564 140605565762138 138140817276033 85494359955827 111201993769744 126924199344567 84171130787396 126237189066813 77171323314106 113200847038248 98779609601686 83798674279089 106537185608134 106955450875636 87838758006658 101451607002530 85308040900483 86403811422215 113577258048929 125263410102264 109676580109527 132614022979699 94171168542936 84543674023131 100008868026988 124846065028949 99680425473513 121978153944949 134823533353340 91295148123852 137813880499276 84350320573636 82970596144289 109591465347114 115978996579051 77475100323158 130638461844618 124362973921554 86136417179614 74570855696351 126909989196370 79646639095680 90588474636252 140043820672381 113993977430877 88111051976223 84495785824214 98528008724751 71238403423128 128198378217029 113678758174910 127376552017462 124083498096349 97741744432145 75702981899917 104410512137503 129487507016485 85072508171989 98566009654432 135475308443413 101035928256317 133170508579529 111809757664517 97967258901913 72481786966856 135666293847432 122974840829056 117701280040640 122795034581604 134387746346615 99327003170703 119505829793787 134955833512226 85734240165197 103994893756469 102653148896431 77550552832307 100251517582155 109716469774863 117125517130263 106345827054422 88461462843337 128207252060231 119489380508688 126048480655348 74139939082261 100955949343760 120689628525134 128783819629630 78510364957482 112955200043446 137817462415705 86269833389151 117383957398803 85871106643839 119987292099960 104880707398152 125964669126663 139421971821534 135767790879669 132172103665614 132811782531392 92742396170173 117528540049392 93149475447203 117442919676155 74196433870353 91240749757962 131559323695260 96498940456849 111159821411291 137212744611839 98608656453015 120453855296121 117817113115919 71292468395146 103840488955927 70649051750155 117025362909593 75774809289032 121359760796995 106421928229046 96741038458338 137043545155721 86046223814247 124166277467052 104019964603138 100902522617165 85517129224510 75965372495046 110380361367193 137928877899747 75324192304111 124350489260057 115140505300095 124484900260123 111492363647746 123338095986788 140544097255524 9085319375 123129741680163 120428322798388 91616529441627 107395571053470 71675067880662 75596132862621 87994107643550 115824487258988 9120299506 9119720940 112232833785347 109104058175305 95732969910223 124582674025379 119990536825115 8627570021 124469002502416 76994001210719 115424073160933 140197636750976 126691689431839 128195112071770 86469900853901 134410911353980 9125966589 74526518585827 133118825545336 72645459248115 138525839976703 116748952339879 122347357361781 107777265003334 83029859382828 139117633233932 80289887803652 73971610392576 123395779232083 133239823986312 122429151245718 86475716717939 78605100123114 83004262876405 121174912242509 106548354461829 100023885481655 138865799123467 89598359979204 132245408235303 112335807593790 89225209763570 104416955158053 119747688049971 108862140081348 84960137646461 135691159747231 123331878534637 115899785091933 97067274112530 90578955594707 99246256938614 135896322708645 74286744646370 134985126964057 129132692277064 107099028680956 94544272911297 121994287869708 82850795928931 75263778269693 94696101406576 90357627997619]=],"%d+") do knownSoundIds[id]=true end
local function soundId(obj)
    local id=string.match(obj.SoundId,"^rbxassetid://(%d+)$")
    if not id then id=string.match(obj.SoundId,"[?&]id=(%d+)") end
    return id and knownSoundIds[id] and id or nil
end
local function soundPos(obj)
    local p=obj.Parent
    if p and p:IsA("Attachment") then return p.WorldPosition end
    if p and p:IsA("BasePart") then return p.Position end
    return nil
end
local function pushSound(s,e)
    if session~=s or s.paused then return end
    if #s.pendingSounds>=512 or s.soundCount>=100000 then s.droppedSoundEvents+=1;return end
    e.t=round(os.clock()-s.started)
    table.insert(s.pendingSounds,e);s.soundCount+=1
end
local function endSound(s,w)
    if not w.active then return end
    pushSound(s,{kind="stop",key=w.active})
    w.active=nil
end
local function watchSound(s,obj)
    if not obj:IsA("Sound") or s.soundWatch[obj] or not soundId(obj) then return end
    if obj:IsDescendantOf(SoundService) then
        local group=obj.SoundGroup
        local sfxRoot=SoundService:FindFirstChild("SFX")
        if not ((sfxRoot and obj:IsDescendantOf(sfxRoot)) or (group and group.Name=="SFX")) then return end
    elseif not obj:IsDescendantOf(workspace) then return end
    if s.soundWatchCount>=4096 then s.droppedSoundEvents+=1;return end
    local w={connections={},active=nil}
    s.soundWatch[obj]=w;s.soundWatchCount+=1
    local function begin()
        if session~=s or s.paused or w.active or not obj.IsPlaying then return end
        local id=soundId(obj);if not id then return end
        s.nextSoundKey+=1;w.active=s.nextSoundKey
        local p=soundPos(obj)
        pushSound(s,{kind="start",key=w.active,id=id,volume=round(obj.Volume),speed=round(obj.PlaybackSpeed),offset=round(obj.TimePosition),looped=obj.Looped,minDistance=round(obj.RollOffMinDistance),maxDistance=round(obj.RollOffMaxDistance),rolloff=obj.RollOffMode.Name,pos=p and {round(p.X),round(p.Y),round(p.Z)} or nil})
    end
    local function sync()
        if obj.IsPlaying then begin() else endSound(s,w) end
    end
    local function remove()
        endSound(s,w)
        for _,conn in ipairs(w.connections) do conn:Disconnect() end
        s.soundWatch[obj]=nil;s.soundWatchCount-=1
    end
    table.insert(w.connections,obj.Played:Connect(begin))
    table.insert(w.connections,obj:GetPropertyChangedSignal("Playing"):Connect(sync))
    table.insert(w.connections,obj.Ended:Connect(function() endSound(s,w) end))
    table.insert(w.connections,obj.Stopped:Connect(function() endSound(s,w) end))
    table.insert(w.connections,obj.Paused:Connect(function() endSound(s,w) end))
    table.insert(w.connections,obj.Resumed:Connect(begin))
    table.insert(w.connections,obj.Destroying:Connect(remove))
    begin()
end
local function startSoundWatch(s)
    for _,root in ipairs({workspace,SoundService}) do
        table.insert(s.soundRoots,root.DescendantAdded:Connect(function(obj)
            if obj:IsA("Sound") then watchSound(s,obj);task.defer(function() if session==s and not s.paused then watchSound(s,obj) end end) end
        end))
        for _,obj in ipairs(root:GetDescendants()) do if obj:IsA("Sound") then watchSound(s,obj) end end
    end
end
local function releaseSounds(s)
    for _,conn in ipairs(s.soundRoots) do conn:Disconnect() end
    for _,w in pairs(s.soundWatch) do for _,conn in ipairs(w.connections) do conn:Disconnect() end end
    s.soundRoots={};s.soundWatch={};s.soundWatchCount=0
end

-- Optional local cutscene flag.
local function readCutsceneFlag()
    local character=me.Character
    local found=false
    for _,obj in pairs({me,character,me:FindFirstChild("PlayerStats"),character and character:FindFirstChild("Values")}) do
        local attr=obj:GetAttribute("InCutscene")
        local value=readValue(obj,"InCutscene")
        if attr==true or value==true then return true end
        if type(attr)=="boolean" or type(value)=="boolean" then found=true end
    end
    if found then return false end
    return nil
end

local function sample(s)
    local frame={t=round(os.clock()-s.started),players={}}
    local cut=readCutsceneFlag()
    if cut~=nil then frame.cutscene=cut end
    local actors={}
    local events=s.pendingEvents
    s.pendingEvents={}
    if #s.pendingSounds>0 then frame.soundEvents=s.pendingSounds;s.pendingSounds={} end
    local seenStuns={}
    local seenActors={}
    local pollStyles=frame.t>=s.nextStatsAt or #s.frames==0
    local function addEvent(kind,id,source,extra)
        local e={t=frame.t,type=kind,playerId=id,source=source}
        if extra then for k,v in pairs(extra) do e[k]=v end end
        table.insert(events,e)
    end
    local function appendActor(model,id,tm,kind,player)
        if not model or not model:IsA("Model") then return end
        local root=part(model:FindFirstChild("HumanoidRootPart")) or part(model:FindFirstChild("Torso"))
        if not root or not root:IsA("BasePart") then return end
        local values=model:FindFirstChild("Values")
        -- Parked NPC keepers are not active match actors. Match the viewer's height heuristic.
        -- Never apply this filter to human players.
        if kind=="npc" and (root.Position.Y>91.17 or root.Position.Y< -23.83) then return end
        local held=readValue(values,"HasBall")
        local entry={id=id,team=tm,kind=kind,cf=cf(root.CFrame),hasBall=held==true}
        if player then
            local sliding=readValue(values,"Sliding")
            if type(sliding)=="boolean" then
                entry.sliding=sliding
            end
            seenActors[id]=true
            observePlayerProtection(s,id,model)
            -- Observe the existing boolean only, never infer the cause of a stun.
            local stunObject=values and values:FindFirstChild("Stunned")
            local prior=s.stunStates[id]
            if stunObject and stunObject:IsA("BoolValue") then
                local stunned=stunObject.Value
                seenStuns[id]=true
                if prior and prior.object==stunObject and prior.team==tm and prior.value==false and stunned then
                    addEvent("stunned",id,"state")
                end
                s.stunStates[id]={object=stunObject,team=tm,value=stunned}
            end
        end
        if player and pollStyles then
            local function validStyle(v) return type(v)=="string" and #v>0 and #v<=128 end
            local style=readValue(player:FindFirstChild("PlayerStats"),"Style")
            local source="playerStats"
            if not validStyle(style) then
                style=model:GetAttribute("Style")
                source="characterAttribute"
            end
            if validStyle(style) then
                if #s.frames==0 or s.lastStyles[id]~=style or s.lastStyleSources[id]~=source then
                    entry.style=style
                    entry.styleSource=source
                end
                local info=s.players[tostring(id)]
                if info and not info.firstObservedStyle then
                    info.firstObservedStyle=style
                    info.firstObservedStyleAt=frame.t
                    info.firstObservedStyleSource=source
                end
                if s.lastStyles[id] and s.lastStyles[id]~=style then
                    s.abilityStates[id]=nil
                    s.dirtyAbility[id]=true
                end
                s.lastStyles[id]=style
                s.lastStyleSources[id]=source
            end
        end
        if player then
            if pollStyles then
                -- Explicit replicated Flow fields only; unknown is not inactive.
                local stats=player:FindFirstChild("PlayerStats")
                local flow=readValue(stats,"Flow")
                local inFlow=readValue(stats,"InFlow")
                local flowBar=readValue(stats,"FlowBar")
                if type(flow)~="string" or #flow==0 or #flow>128 then flow=nil end
                if type(inFlow)~="boolean" then inFlow=nil end
                if type(flowBar)~="number" or flowBar~=flowBar or flowBar<0 or flowBar>100 then flowBar=nil end
                if flowBar~=nil then flowBar=round(flowBar) end
                local lastFlow=s.lastFlows[id]
                if not lastFlow or not s.actorSeen[id] or #s.frames==0 or lastFlow.name~=flow or lastFlow.active~=inFlow or lastFlow.bar~=flowBar then
                    entry.flowObserved=true
                    entry.flow=flow
                    entry.inFlow=inFlow
                    entry.flowBar=flowBar
                end
                s.lastFlows[id]={name=flow,active=inFlow,bar=flowBar}
                local awk,ready,active=awakeningState(player)
                local prior=s.lastAwakening[id]
                if prior and prior.active~=nil and active~=nil and prior.active~=active then
                    invalidateNames(s,id)
                end
                if not prior or prior.state~=awk or prior.ready~=ready or prior.active~=active or #s.frames==0 then
                    entry.awk=awk
                    -- Explicit booleans (when available) let the viewer revise ready-state interpretation.
                    entry.awkReadyFlag=ready
                    entry.inAwakening=active
                    if prior and prior.state~=awk then addEvent("awakening_state",id,"playerStats",{awk=awk,readyFlag=ready,inAwakening=active}) end
                end
                s.lastAwakening[id]={state=awk,ready=ready,active=active}
            end
            if #s.frames==0 or s.dirtyAbility[id] or not s.actorSeen[id] then
                entry.abilitySlots=copyKit(s.abilityStates[id])
                s.dirtyAbility[id]=nil
            end
        end
        table.insert(frame.players,entry)
        table.insert(actors,{model=model,id=id,held=held==true})
    end
    s.localId=idFor(s,me)
    for _,p in ipairs(Players:GetPlayers()) do
        local tm=team(p)
        if tm=="Home" or tm=="Away" then
            appendActor(p.Character,idFor(s,p),tm,"player",p)
        end
    end
    for _,tm in ipairs({"Home","Away"}) do
        local model=path(workspace,"AI",tm,"GK")
        if model and model:IsA("Model") then
            appendActor(model,actorId(s,tm),tm,"npc")
        end
    end
    for id in pairs(s.stunStates) do
        if not seenStuns[id] then s.stunStates[id]=nil end
    end
    for id in pairs(s.actorSeen) do
        if not seenActors[id] then
            s.lastAwakening[id]=nil
            s.abilityStates[id]=nil
            s.dirtyAbility[id]=nil
        end
    end
    s.actorSeen=seenActors
    for id,w in pairs(s.protectionPlayers) do
        if not seenActors[id] then
            if w.value==true then protectionEvent(s,{kind="player",playerId=id,state="unknown",reason="actor_left"}) end
            disconnectProtection(w);s.protectionPlayers[id]=nil
        end
    end
    observeBallProtection(s)
    if #s.pendingProtection>0 then
        frame.protectionEvents=s.pendingProtection;s.pendingProtection={}
    end
    frame.ball={state="unknown"}
    local balls={}
    local free=part(workspace:FindFirstChild("Football"))
    if free then table.insert(balls,{ball=free}) end
    for _,a in ipairs(actors) do
        local b=part(a.model:FindFirstChild("Football"))
        if b then table.insert(balls,{ball=b,owner=a.id}) end
    end
    -- Do not invent a ball position if replication temporarily exposes multiple copies.
    if #balls==1 then
        local b=balls[1]
        frame.ball={state=b.owner and "held" or "free",owner=b.owner,cf=cf(b.ball.CFrame)}
        -- Only airborne, free ball velocity is needed for the post-match trajectory line.
        if not b.owner and b.ball.Position.Y>9.5 then
            local v=b.ball.AssemblyLinearVelocity
            if v.Magnitude>5 then frame.ball.velocity={round(v.X),round(v.Y),round(v.Z)} end
        end
    end
    -- Capture the local client's actual displayed GK marker, not a reconstructed one.
    -- No prediction remotes or changes to the indicator; record only in authorized sessions.
    local marker=workspace:FindFirstChild("GkPredict")
    if marker and marker:IsA("BasePart") then
        local v=marker.Position
        frame.gkPrediction={round(v.X),round(v.Y),round(v.Z)}
    end
    -- Poll only named replicated match counters, at 5 Hz (not on every frame).
    -- Baseline new/rejoined players and missing/recreated counters without inventing credits.
    if pollStyles then
        s.nextStatsAt=frame.t+1/STATS_RATE
        local stats={}
        local observed={}
        for _,p in ipairs(Players:GetPlayers()) do
            local tm=team(p)
            if p==me or tm=="Home" or tm=="Away" then
                local id=idFor(s,p)
                local folder=p:FindFirstChild("GameStats")
                local prior=s.previousStats[id]
                if not prior or prior.folder~=folder or prior.team~=tm then
                    prior={folder=folder,team=tm,values={},objects={}}
                    s.previousStats[id]=prior
                end
                observed[id]=true
                for _,name in ipairs(counterNames) do
                    if p==me or counterEvents[name] then
                        local obj=folder and folder:FindFirstChild(name)
                        local v=readValue(folder,name)
                        if type(v)=="number" and v==v and v>=0 and v<1e12 then
                            if p==me then stats[name]=v end
                            local previous=prior.values[name]
                            if prior.objects[name]==obj and previous~=nil and v>previous and counterEvents[name] then
                                addEvent(counterEvents[name],id,"counter",{delta=v-previous,value=v})
                            end
                            prior.values[name]=v
                            prior.objects[name]=obj
                        else
                            prior.values[name]=nil
                            prior.objects[name]=nil
                        end
                    end
                end
            end
        end
        for id in pairs(s.previousStats) do
            if not observed[id] then s.previousStats[id]=nil end
        end
        local playerStats=me:FindFirstChild("PlayerStats")
        for _,name in ipairs(playerStatNames) do
            local v=readValue(playerStats,name)
            if type(v)=="string" and #v<=128 then stats[name]=v end
        end
        local inFlow=readValue(playerStats,"InFlow")
        local flowBar=readValue(playerStats,"FlowBar")
        if type(inFlow)=="boolean" then stats.InFlow=inFlow end
        if type(flowBar)=="number" and flowBar==flowBar and flowBar>=0 and flowBar<=100 then stats.FlowBar=round(flowBar) end
        -- Full snapshot at each chunk boundary; changed fields otherwise.
        local delta={}
        if #s.frames==0 then delta=stats else
            for k,v in pairs(stats) do
                if s.lastStats[k]~=v then delta[k]=v end
            end
        end
        if next(delta) then frame.localStats=delta end
        for k,v in pairs(stats) do s.lastStats[k]=v end
    end
    if frame.t>=s.nextBoardAt or #s.frames==0 then
        s.nextBoardAt=frame.t+1/BOARD_RATE
        snapshotBoard(s,frame)
    end
    if #events>0 then
        frame.events=events
    end
    local cam=workspace.CurrentCamera
    if cam then frame.camera={cf=cf(cam.CFrame),fov=round(cam.FieldOfView)} end
    local board=path(pg,"InGameUI","Scoreboard")
    frame.scoreboard={home=label(path(board,"Frame","Home","Score","TextLabel")),
        away=label(path(board,"Frame","Away","Score","TextLabel")),timer=label(path(board,"Timer","TextLabel"))}
    s.count+=1;s.lastT=frame.t
    table.insert(s.frames,frame)
end
local function start()
    local now=DateTime.now()
    local id=HttpService:GenerateGUID(false)
    local name=now:FormatLocalTime("YYYY-MM-DD_HH-mm-ss","en-us").."_"..id:sub(1,8)
    local folder=ROOT.."/"..name
    makefolder(folder)
    local s={id=id,createdAt=math.floor(now.UnixTimestampMillis/1000),folder=folder,started=os.clock(),
        lastFlush=os.clock(),lastT=0,frames={},players={},ids={},nextId=0,count=0,chunks=0,
        nextStatsAt=0,nextBoardAt=0,previousStats={},lastStats={},lastStyles={},lastStyleSources={},lastRoles={},stunStates={},abilityStates={},dirtyAbility={},lastAwakening={},lastFlows={},actorSeen={},pendingEvents={},droppedAbilityUpdates=0,pendingProtection={},protectionPlayers={},protectionBall=nil,droppedProtectionEvents=0,pendingSounds={},soundRoots={},soundWatch={},soundWatchCount=0,soundCount=0,nextSoundKey=0,droppedSoundEvents=0}
    flush(s,false)
    session=s; accumulator=0
    startSoundWatch(s)
    button.Text="■ Stop & Save"
    button.BackgroundColor3=Color3.fromRGB(157,62,71)
    status.Text="Recording · 0 frames"
end
local function stop()
    local s=session
    if not s then return end
    if not s.paused and (#s.pendingEvents>0 or #s.pendingProtection>0 or #s.pendingSounds>0) then
        local sampled,err=pcall(sample,s)
        if not sampled then warn("[Replay] Final sample failed: "..tostring(err)) end
    end
    s.paused=true
    releaseProtection(s)
    releaseSounds(s)
    local ok,err=pcall(flush,s,true)
    if not ok then status.Text="Save failed · click to retry";warn(err);return end
    session=nil
    button.Text="● Record"
    button.BackgroundColor3=Color3.fromRGB(58,105,157)
    status.Text=string.format("Saved %d frames · files",s.count)
    print("[Replay] Saved: "..s.folder)
end
local function toggle()
    if busy then return end
    busy=true
    local ok,err=pcall(function() if session then stop() else start() end end)
    busy=false
    if not ok then status.Text="Recorder error · see Output";warn(err) end
end
button.Activated:Connect(toggle)
UserInputService.InputBegan:Connect(function(input,processed)
    if input.KeyCode==Enum.KeyCode.F7 and session then toggle();return end
    if not processed and input.KeyCode==Enum.KeyCode.F6 and not session then toggle() end
end)
RunService:BindToRenderStep("ReplayRecorder06",Enum.RenderPriority.Camera.Value+1,function(dt)
    local s=session
    if not s or busy or s.paused then return end
    accumulator+=dt
    if accumulator>=1/RATE then
        accumulator%=1/RATE
        local ok,err=pcall(sample,s)
        if not ok then s.paused=true;status.Text="Sample failed · click to save";warn(err);return end
    end
    if s.count>=MAX_FRAMES then
        busy=true
        task.defer(function()
            local ok,err=pcall(stop)
            busy=false
            if not ok then s.paused=true;warn(err) end
        end)
        return
    end
    if os.clock()-s.lastFlush>=CHUNK_SECONDS then
        busy=true
        task.defer(function()
            local ok,err=pcall(flush,s,false)
            busy=false
            if not ok then s.paused=true;status.Text="Save failed · click to retry";warn(err);return end
            status.Text=string.format("REC %.0fs · %d frames",s.lastT,s.count)
        end)
    end
end)

print("[Replay] v0.21 Lite ready. F6 start / F7 stop. Local files only.")
