--[[--------------------------------------------------------------------
  PaladinHolyPower – tracker/holy_power_log/events.lua
----------------------------------------------------------------------]]

local PHP = _G.PaladinHolyPower
if not PHP then return end

-- -------------------------------------------------------------------
-- Settings helpers
-- -------------------------------------------------------------------
local function GetSettings()
  local S = PHP.settings or {}
  return S.HPL or S
end

local function InCombat()
  return (type(InCombatLockdown)=="function" and InCombatLockdown())
      or (_G.UnitAffectingCombat and _G.UnitAffectingCombat("player"))
      or false
end

-- PREVIEW is true only if Edit Mode is ON or the HP Log subtab is active
local function PreviewOn()
  if PHP.EditModeActive then return true end
  return PHP._ActiveHPSubTab == "hplog"
end

-- -------------------------------------------------------------------
-- Apply visibility (single source of truth)
-- -------------------------------------------------------------------
local function ApplyVisibility()
  local S = GetSettings()
  if S.enabled == false then
    if PHP.DisableHPLTrackerFrame then PHP.DisableHPLTrackerFrame() end
    return
  end

  if InCombat() or PreviewOn() then
    if PHP.EnableHPLTrackerFrame then PHP.EnableHPLTrackerFrame() end
  else
    if PHP.DisableHPLTrackerFrame then PHP.DisableHPLTrackerFrame() end
  end

  if PHP.UpdateHPLTracker then PHP.UpdateHPLTracker() end
end

function PHP._HPL_ApplyVisibility()
  ApplyVisibility()
end

-- -------------------------------------------------------------------
-- Lightweight hooks (no per-frame polling)
-- -------------------------------------------------------------------
local function InstallHooksOnce()
  if PHP._HPL_HOOKS_INSTALLED then return end
  PHP._HPL_HOOKS_INSTALLED = true

  -- When the settings panel toggles, just re-apply (do NOT show just because it opened)
  if type(PHP.ShowSettingsPanel) == "function" and _G.hooksecurefunc then
    hooksecurefunc(PHP, "ShowSettingsPanel", function()
      local p = PHP.SettingsPanel
      if p and p.HookScript and not p._hpl_vis_hooked then
        p._hpl_vis_hooked = true
        p:HookScript("OnShow", function() ApplyVisibility() end)
        p:HookScript("OnHide", function() ApplyVisibility() end)
      end
      ApplyVisibility()
    end)
  end

  -- If your Edit Mode toggle is exposed, hook it so previews reflect instantly
  if type(PHP.ToggleEditMode) == "function" and _G.hooksecurefunc then
    hooksecurefunc(PHP, "ToggleEditMode", function()
      ApplyVisibility()
    end)
  end
end

-- -------------------------------------------------------------------
-- Fight summary chat print (colored) + [Log] hyperlink
-- -------------------------------------------------------------------
local lastAnnounceAt = 0
local function color(hex, text) return "|cff"..tostring(hex)..tostring(text).."|r" end

local COL_HP_NAME   = "F2E699"  -- "Holy Power" + "HP" in prefix
local COL_PREFIX_P  = "F48CBA"  -- "P" in "PHP:"
local COL_VAL_GEN   = "FFFF00"  -- Generated value
local COL_VAL_SPENT = "FFFAB8"  -- Spent value
local COL_VAL_WASTE = "E8615E"  -- Wasted value
local COL_LOG_LINK  = "66BBFF"  -- [Log] link

-- Custom hyperlink handler for [Log]
local LINK_TYPE = "phpopenlog"
if not PHP._HPL_LogLinkHooked then
  hooksecurefunc("SetItemRef", function(link, text, button, chatFrame)
    local ltype = tostring(link):match("^([^:]+)")
    if ltype == LINK_TYPE then
      if PHP.ToggleHPLog then PHP.ToggleHPLog() end
    end
  end)
  PHP._HPL_LogLinkHooked = true
end

local function BuildLogLink()
  return "|cff"..COL_LOG_LINK.."|H"..LINK_TYPE..":1|h[Log]|h|r"
end

local function AnnounceFightSummary()
  local now = (type(GetTime)=="function" and GetTime()) or 0
  if (now - lastAnnounceAt) < 1.5 then return end  -- throttle

  local S = GetSettings()
  if S.enabled == false then return end
  if type(PHP.HPLog_GetTotals) ~= "function" then return end

  local gen, spent, wasted = PHP.HPLog_GetTotals()
  gen, spent, wasted = tonumber(gen) or 0, tonumber(spent) or 0, tonumber(wasted) or 0

  local mode = (S.mode and tostring(S.mode):lower()) or "wasted"
  local verb, amount, valColor
  if mode == "generated" then
    verb, amount, valColor = "Generated", gen, COL_VAL_GEN
  elseif mode == "spent" then
    verb, amount, valColor = "Spent", spent, COL_VAL_SPENT
  else
    verb, amount, valColor = "Wasted", wasted, COL_VAL_WASTE
  end

  local prefix = color(COL_PREFIX_P, "P") .. color(COL_HP_NAME, "HP") .. ": "
  local msg = string.format(
    "%sYou %s %s %s this fight! %s",
    prefix,
    verb,
    color(valColor, tostring(amount)),
    color(COL_HP_NAME, "Holy Power"),
    BuildLogLink()
  )

  if _G.DEFAULT_CHAT_FRAME and _G.DEFAULT_CHAT_FRAME.AddMessage then
    _G.DEFAULT_CHAT_FRAME:AddMessage(msg)
  else
    print(msg)
  end

  lastAnnounceAt = now
end

-- -------------------------------------------------------------------
-- Event driver (no idle polling)
-- -------------------------------------------------------------------
local ef = CreateFrame("Frame", "PHP_HPL_EventDriver")
ef:SetScript("OnEvent", function(_, ev)
  if ev == "PLAYER_LOGIN" or ev == "PLAYER_ENTERING_WORLD" then
    InstallHooksOnce()
    ApplyVisibility()

  elseif ev == "PLAYER_REGEN_DISABLED" then
    ApplyVisibility()

  elseif ev == "PLAYER_REGEN_ENABLED" then
    ApplyVisibility()
    AnnounceFightSummary()

  elseif ev == "ENCOUNTER_END" then
    AnnounceFightSummary()
  end
end)

ef:RegisterEvent("PLAYER_LOGIN")
ef:RegisterEvent("PLAYER_ENTERING_WORLD")
ef:RegisterEvent("PLAYER_REGEN_DISABLED")
ef:RegisterEvent("PLAYER_REGEN_ENABLED")
ef:RegisterEvent("ENCOUNTER_END")