local _, ns = ...
local SlickUI = ns.SlickUI

local Cinematics = {}
SlickUI.Cinematics = Cinematics

local function IsScenario()
	local _, instanceType = IsInInstance()
	return instanceType == "scenario"
end

function Cinematics:IsEnabled()
	return SlickUI.DB and SlickUI.DB.cinematics and SlickUI.DB.cinematics.skipPreviouslySeen == true
end

function Cinematics:HandleMovie(movieID)
	if not self:IsEnabled() or movieID == nil then return end
	local key = tostring(movieID)
	local seen = SlickUI.DB.cinematics.seenMovies
	if seen[key] then
		if MovieFrame and MovieFrame.Hide then MovieFrame:Hide() end
		SlickUI:Print("Skipped a previously seen movie.")
	else
		seen[key] = true
	end
end

function Cinematics:GetCinematicKey()
	if IsScenario() then return nil end
	local mapID = C_Map and C_Map.GetBestMapForUnit and C_Map.GetBestMapForUnit("player")
	if type(mapID) ~= "number" then return nil end
	return tostring(mapID) .. "\031" .. tostring(GetSubZoneText() or "")
end

function Cinematics:HandleCinematic()
	if not self:IsEnabled() then return end
	local key = self:GetCinematicKey()
	if not key then return end
	local seen = SlickUI.DB.cinematics.seenCinematics
	if seen[key] then
		if type(CinematicFrame_CancelCinematic) == "function" then
			CinematicFrame_CancelCinematic()
			SlickUI:Print("Skipped a previously seen cutscene.")
		end
	else
		seen[key] = true
	end
end

function Cinematics:ResetHistory()
	wipe(SlickUI.DB.cinematics.seenMovies)
	wipe(SlickUI.DB.cinematics.seenCinematics)
	SlickUI:Print("Cutscene viewing history has been reset.")
end

function Cinematics:Initialize()
	self.EventFrame = CreateFrame("Frame")
	self.EventFrame:RegisterEvent("PLAY_MOVIE")
	self.EventFrame:RegisterEvent("CINEMATIC_START")
	self.EventFrame:SetScript("OnEvent", function(_, event, ...)
		if event == "PLAY_MOVIE" then
			Cinematics:HandleMovie(...)
		elseif event == "CINEMATIC_START" then
			Cinematics:HandleCinematic()
		end
	end)
end

SlickUI:RegisterModule("Cinematics", Cinematics)
