local ADDON_NAME, ns = ...
local WF = ns.WF

WF.UI = WF.UI or {}
WF.UI.HelpPages = WF.UI.HelpPages or {}
WF.UI.HelpPages.OverviewFarmTimer = WF.UI.HelpPages.OverviewFarmTimer or {}

local Modules = WF.UI.HelpPages.OverviewFarmTimer

local BODY_FONT = (WF and WF.UI and WF.UI.Fonts and WF.UI.Fonts.body) or ("Interface\\AddOns\\" .. tostring(ADDON_NAME) .. "\\Media\\Fonts\\PTSansNarrow.ttf")
local DISPLAY_FONT = (WF and WF.UI and WF.UI.Fonts and WF.UI.Fonts.display) or ("Interface\\AddOns\\" .. tostring(ADDON_NAME) .. "\\Media\\Fonts\\Expressway.ttf")

function Modules.EnsureHUD(ctx, env, FT)
  if not FT then return nil end
  if FT._hudInited then return FT end
  FT._hudInited = true

  local WF = env.WF
  local Widgets = env.Widgets
  local C4 = env.C4
  local TEXT = env.TEXT
  local MUTED = env.MUTED
  local PANEL = env.PANEL
  local ACCENT = env.ACCENT

FT._hudLockKey = FT._hudLockKey or "uiLocked_farmTimerHUD"
  
function FT:IsHUDUnlocked()
  if Widgets and Widgets.IsLocked and WF and WF.DB and WF.DB.GetSetting then
    local locked = WF.DB:GetSetting(self._hudLockKey)
    if locked == nil then
      return self.cfg and self.cfg.hudUnlock and true or false
    end
    return not locked
  end
  return self.cfg and self.cfg.hudUnlock and true or false
end
  
function FT:SetHUDUnlocked(unlocked)
  unlocked = unlocked and true or false
  if self.cfg then
    self.cfg.hudUnlock = unlocked
  end
  if Widgets and Widgets.SetLocked then
    Widgets:SetLocked(self._hudLockKey, not unlocked)
  end
end
  
function FT:_PersistHUDSize()
  if not (self and self.hud and self.cfg) then return end
  local w, h = self.hud:GetSize()
  self.cfg.hudSize = {
    math.floor((w or 0) + 0.5),
    math.floor((h or 0) + 0.5),
  }
end
  
function FT:_SyncHUDLockCheckbox()
  if self._uiCbUnlock and self._uiCbUnlock.SetChecked then
    self._uiCbUnlock:SetChecked(self:IsHUDUnlocked() and true or false)
  end
end
  
function FT:_EnsureTicker()
  if FT._ticker then return end
  local f = CreateFrame("Frame")
  f:Hide()
  f:SetScript("OnUpdate", function(_, _)
    FT:Tick()
  end)
  FT._ticker = f
end
  
function FT:_DoFlash()
  if not UIParent then return end
  
  local ar, ag, ab = C4(ACCENT, TEXT)
  ar = tonumber(ar) or 0.20
  ag = tonumber(ag) or 0.55
  ab = tonumber(ab) or 1.00
  
  if not self._flashFrame then
    local flash = CreateFrame("Frame", nil, UIParent)
    flash:SetAllPoints(UIParent)
    flash:SetFrameStrata("FULLSCREEN")
    flash:SetFrameLevel(2)
    flash:EnableMouse(false)
    flash:SetAlpha(0)
    flash:Hide()
  
    local tex = flash:CreateTexture(nil, "BACKGROUND")
    tex:SetAllPoints(flash)
    tex:SetTexture("Interface/Buttons/WHITE8X8")
    tex:SetBlendMode("ADD")
    tex:SetVertexColor(ar, ag, ab, 1)
  
    local anim = flash:CreateAnimationGroup()
  
    local pulseIn1 = anim:CreateAnimation("Alpha")
    pulseIn1:SetOrder(1)
    pulseIn1:SetFromAlpha(0.00)
    pulseIn1:SetToAlpha(0.12)
    pulseIn1:SetDuration(0.08)
  
    local pulseOut1 = anim:CreateAnimation("Alpha")
    pulseOut1:SetOrder(2)
    pulseOut1:SetFromAlpha(0.12)
    pulseOut1:SetToAlpha(0.04)
    pulseOut1:SetDuration(0.10)
  
    local pulseIn2 = anim:CreateAnimation("Alpha")
    pulseIn2:SetOrder(3)
    pulseIn2:SetFromAlpha(0.04)
    pulseIn2:SetToAlpha(0.09)
    pulseIn2:SetDuration(0.07)
  
    local pulseOut2 = anim:CreateAnimation("Alpha")
    pulseOut2:SetOrder(4)
    pulseOut2:SetFromAlpha(0.09)
    pulseOut2:SetToAlpha(0.00)
    pulseOut2:SetDuration(0.24)
  
    anim:SetScript("OnPlay", function()
      flash:SetAlpha(0)
      flash:Show()
    end)
    anim:SetScript("OnFinished", function()
      flash:SetAlpha(0)
      flash:Hide()
    end)
  
    self._flashFrame = flash
    self._flashTex = tex
    self._flashAnim = anim
  end
  
  if self._flashTex and self._flashTex.SetVertexColor then
    self._flashTex:SetVertexColor(ar, ag, ab, 1)
  end
  
  if self._flashAnim and self._flashAnim.IsPlaying and self._flashAnim:IsPlaying() then
    self._flashAnim:Stop()
  end
  
  if self._flashFrame then
    self._flashFrame:SetAlpha(0)
    self._flashFrame:Show()
  end
  
  if self._flashAnim then
    self._flashAnim:Play()
  end
end

      function FT:_EnsureHUD()
  if FT.hud then return end
  
  local tr, tg, tb = C4(TEXT, TEXT)
  local mr, mg, mb = C4(MUTED, MUTED)
  local ar, ag, ab = C4(ACCENT, TEXT)
  
  local bodyFont = (WF and WF.UI and WF.UI.Fonts and WF.UI.Fonts.body) or BODY_FONT
  local displayFont = (WF and WF.UI and WF.UI.Fonts and WF.UI.Fonts.display) or DISPLAY_FONT
  
  if Widgets and Widgets.SetLocked and WF and WF.DB and WF.DB.GetSetting then
    local savedLock = WF.DB:GetSetting(FT._hudLockKey)
    if savedLock == nil then
      Widgets:SetLocked(FT._hudLockKey, not (FT.cfg and FT.cfg.hudUnlock and true or false))
    else
      FT.cfg.hudUnlock = not savedLock
    end
  end
  
  local hud = CreateFrame("Frame", "WhatFarm_FarmTimerHUD", UIParent, (BackdropTemplateMixin and "BackdropTemplate") or nil)
  hud:SetSize(268, 44)
  hud:SetFrameStrata("HIGH")
  hud:SetFrameLevel(50)
  hud:SetClampedToScreen(true)
  hud:SetMovable(true)
  hud:SetResizable(true)
  if hud.SetMinResize then
    hud:SetMinResize(236, 40)
  end
  if hud.SetMaxResize then
    hud:SetMaxResize(360, 56)
  end
  hud:EnableMouse(true)
  
  if hud.SetBackdrop then
    hud:SetBackdrop({
      bgFile = "Interface/Buttons/WHITE8X8",
      edgeFile = "Interface/Buttons/WHITE8X8",
      edgeSize = 1,
      insets = { left = 1, right = 1, top = 1, bottom = 1 },
    })
    local pr, pg, pb = C4(PANEL, PANEL)
    pr = pr or 0.10
    pg = pg or 0.10
    pb = pb or 0.10
    hud:SetBackdropColor(pr, pg, pb, 0.96)
    hud:SetBackdropBorderColor(mr, mg, mb, 0.28)
  end
  
  hud.topAccent = hud:CreateTexture(nil, "BORDER")
  hud.topAccent:SetHeight(1)
  hud.topAccent:SetPoint("TOPLEFT", 1, -1)
  hud.topAccent:SetPoint("TOPRIGHT", -1, -1)
  hud.topAccent:SetColorTexture(mr, mg, mb, 0.22)
  
  hud.dragZone = CreateFrame("Frame", nil, hud)
  hud.dragZone:SetPoint("TOPLEFT", 8, -5)
  hud.dragZone:SetPoint("TOPRIGHT", -24, -5)
  hud.dragZone:SetHeight(13)
  hud.dragZone:EnableMouse(true)
  hud.dragZone:RegisterForDrag("LeftButton")
  
  hud.title = hud:CreateFontString(nil, "OVERLAY", "WF_GameFontDisableSmall")
  hud.title:SetPoint("TOPLEFT", 10, -7)
  hud.title:SetJustifyH("LEFT")
  hud.title:SetTextColor(tr, tg, tb, 0.92)
  hud.title:SetText("WF Timer")
  if hud.title.SetFont then
    hud.title:SetFont(bodyFont, 10, "")
  end
  
  hud.phaseText = hud:CreateFontString(nil, "OVERLAY", "WF_GameFontDisableSmall")
  hud.phaseText:SetPoint("LEFT", hud.title, "RIGHT", 10, 0)
  hud.phaseText:SetJustifyH("LEFT")
  hud.phaseText:SetTextColor(mr, mg, mb, 0.92)
  hud.phaseText:SetText("")
  if hud.phaseText.SetFont then
    hud.phaseText:SetFont(bodyFont, 10, "")
  end
  
  hud.stateText = hud:CreateFontString(nil, "OVERLAY", "WF_GameFontDisableSmall")
  hud.stateText:SetPoint("TOPRIGHT", -10, -7)
  hud.stateText:SetJustifyH("RIGHT")
  hud.stateText:SetTextColor(ar, ag, ab, 0.96)
  hud.stateText:SetText("")
  if hud.stateText.SetFont then
    hud.stateText:SetFont(bodyFont, 10, "")
  end
  
  hud.timeText = hud:CreateFontString(nil, "OVERLAY", "WF_GameFontNormalLarge")
  hud.timeText:SetPoint("BOTTOMLEFT", 10, 6)
  hud.timeText:SetJustifyH("LEFT")
  hud.timeText:SetTextColor(ar, ag, ab, 1)
  hud.timeText:SetText("0:00")
  if hud.timeText.SetFont then
    hud.timeText:SetFont(displayFont, 18, "")
  end
  if hud.timeText.SetShadowColor then
    hud.timeText:SetShadowColor(0, 0, 0, 0.55)
  end
  if hud.timeText.SetShadowOffset then
    hud.timeText:SetShadowOffset(1, -1)
  end
  
  local function _HUDButton(parent, label, w)
    local b = CreateFrame("Button", nil, parent, (BackdropTemplateMixin and "BackdropTemplate") or nil)
    b:SetSize(w or 52, 18)
    b:EnableMouse(true)
  
    if b.SetBackdrop then
      b:SetBackdrop({
        bgFile = "Interface/Buttons/WHITE8X8",
        edgeFile = "Interface/Buttons/WHITE8X8",
        edgeSize = 1,
        insets = { left = 1, right = 1, top = 1, bottom = 1 },
      })
      local pr, pg, pb = C4(PANEL, PANEL)
      pr = pr or 0.10
      pg = pg or 0.10
      pb = pb or 0.10
      b:SetBackdropColor(pr + 0.02, pg + 0.02, pb + 0.02, 0.98)
      b:SetBackdropBorderColor(mr, mg, mb, 0.24)
    end
  
    b.txt = b:CreateFontString(nil, "OVERLAY", "WF_GameFontHighlightSmall")
    b.txt:SetPoint("CENTER", 0, 0)
    b.txt:SetJustifyH("CENTER")
    b.txt:SetTextColor(tr, tg, tb, 0.94)
    b.txt:SetText(label)
    if b.txt.SetFont then
      b.txt:SetFont(bodyFont, 10, "")
    end
  
    b:SetScript("OnEnter", function()
      local pr, pg, pb = C4(PANEL, PANEL)
      pr = pr or 0.10
      pg = pg or 0.10
      pb = pb or 0.10
      if b.SetBackdropColor then b:SetBackdropColor(pr + 0.04, pg + 0.04, pb + 0.04, 1) end
      if b.SetBackdropBorderColor then b:SetBackdropBorderColor(ar, ag, ab, 0.38) end
    end)
    b:SetScript("OnLeave", function()
      local pr, pg, pb = C4(PANEL, PANEL)
      pr = pr or 0.10
      pg = pg or 0.10
      pb = pb or 0.10
      if b.SetBackdropColor then b:SetBackdropColor(pr + 0.02, pg + 0.02, pb + 0.02, 0.98) end
      if b.SetBackdropBorderColor then b:SetBackdropBorderColor(mr, mg, mb, 0.24) end
      GameTooltip:Hide()
    end)
  
    return b
  end
  
  hud.btnStop = _HUDButton(hud, "Stop", 46)
  hud.btnStop:SetPoint("BOTTOMRIGHT", -22, 6)
  
  hud.btnPause = _HUDButton(hud, "Pause", 54)
  hud.btnPause:SetPoint("RIGHT", hud.btnStop, "LEFT", -6, 0)
  
  hud.btnStop:SetScript("OnClick", function()
    FT:Stop()
  end)
  
  hud.btnPause:SetScript("OnClick", function()
    if not (FT.state and FT.state.running) then return end
    if FT.state.paused then
      FT:Resume()
    else
      FT:Pause()
    end
  end)
  
  hud.dragZone:SetScript("OnDragStart", function()
    local unlocked = FT:IsHUDUnlocked()
    if unlocked and hud.StartMoving then
      hud._wfDragging = true
      hud:StartMoving()
    end
  end)
  
  hud.dragZone:SetScript("OnDragStop", function()
    if not hud._wfDragging then return end
    hud._wfDragging = nil
    hud:StopMovingOrSizing()
    if FT.cfg then
      local p, rel, rp, x, y = hud:GetPoint(1)
      FT.cfg.hudPoint = { p or "CENTER", rp or "CENTER", x or 0, y or 0 }
    end
  end)
  
  hud:SetScript("OnDragStop", function()
    if not hud._wfDragging then return end
    hud._wfDragging = nil
    hud:StopMovingOrSizing()
    if FT.cfg then
      local p, rel, rp, x, y = hud:GetPoint(1)
      FT.cfg.hudPoint = { p or "CENTER", rp or "CENTER", x or 0, y or 0 }
    end
  end)
  
  if Widgets and Widgets.AttachCornerLockGrip then
    hud.resizeGrip = Widgets:AttachCornerLockGrip(hud, {
      lockKey = FT._hudLockKey,
      size = 14,
      x = -4,
      y = 4,
      alpha = 0.55,
      noLockText = true,
      onResizeStart = function()
        if hud.StopMovingOrSizing then
          hud:StopMovingOrSizing()
        end
      end,
      onResizeStop = function()
        FT:_PersistHUDSize()
      end,
    })
  
    if hud.resizeGrip and hud.resizeGrip.HookScript then
      local function _SyncHUDGripState()
        if FT.cfg then
          FT.cfg.hudUnlock = FT:IsHUDUnlocked()
        end
        FT:_SyncHUDLockCheckbox()
      end
  
      hud.resizeGrip:HookScript("OnMouseDown", _SyncHUDGripState)
      hud.resizeGrip:HookScript("OnMouseUp", _SyncHUDGripState)
      hud.resizeGrip:HookScript("OnEnter", function(selfBtn)
        if not GameTooltip or not GameTooltip.SetOwner then return end
        if Widgets and Widgets.EnsureTooltipSkin then Widgets:EnsureTooltipSkin() end
        GameTooltip:SetOwner(selfBtn, "ANCHOR_LEFT")
        GameTooltip:ClearLines()
        GameTooltip:AddLine("Farm Timer HUD", ACCENT[1], ACCENT[2], ACCENT[3], true)
        if FT:IsHUDUnlocked() then
          GameTooltip:AddLine("Drag the corner grip to resize. Drag the top bar to move. Click the grip again to lock it.", 0.7, 0.7, 0.7, true)
        else
          GameTooltip:AddLine("Click the corner grip to unlock moving and resizing.", 0.7, 0.7, 0.7, true)
        end
        GameTooltip:Show()
      end)
      hud.resizeGrip:HookScript("OnLeave", function()
        GameTooltip:Hide()
      end)
    end
  end
  
  hud:Hide()
  FT.hud = hud
  
  if FT.cfg and FT.cfg.hudSize then
    local w = tonumber(FT.cfg.hudSize[1]) or 268
    local h = tonumber(FT.cfg.hudSize[2]) or 44
    if w < 236 then w = 236 end
    if h < 40 then h = 40 end
    if w > 360 then w = 360 end
    if h > 56 then h = 56 end
    hud:SetSize(w, h)
  end
  
  if FT.cfg and FT.cfg.hudPoint then
    local p = FT.cfg.hudPoint[1] or "CENTER"
    local rp = FT.cfg.hudPoint[2] or "CENTER"
    local x = FT.cfg.hudPoint[3] or 0
    local y = FT.cfg.hudPoint[4] or 0
    hud:ClearAllPoints()
    hud:SetPoint(p, UIParent, rp, x, y)
  else
    hud:SetPoint("CENTER", UIParent, "CENTER", 0, 220)
  end
  
  if FT.cfg then
    FT.cfg.hudUnlock = FT:IsHUDUnlocked()
  end
end
  
function FT:_ShowHUD(show)
  FT:_EnsureHUD()
  if not FT.hud then return end
  if show then
    FT.hud:Show()
  else
    FT.hud:Hide()
  end
end
  

  return FT
end
