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

function Modules.BuildOptions(ctx, env, FT)
  local UI = env.UI
  local Widgets = env.Widgets
  local C4 = env.C4
  local TEXT = env.TEXT
  local MUTED = env.MUTED
  local PANEL = env.PANEL
  local ACCENT = env.ACCENT
  local rSC = env.rSC
  local bBW = env.bBW
  local MakeDivider = env.MakeDivider
  local MakeSectionTitle = env.MakeSectionTitle
  local MakeMutedText = env.MakeMutedText
  local _WF_ApplyGearOptionButton = env.ApplyGearOptionButton
  local _WF_GearOpt_SetHover = env.GearOptionSetHover
  local WF_ApplyBlueCheck = env.ApplyBlueCheck
  local _WF_TooltipFollow_Stop = env.TooltipFollowStop
  local rightBottom = bBW

    -- UI section ----------------------------------------------------------
local ftDiv = MakeDivider(rSC)
ftDiv:SetPoint("LEFT", rSC, "LEFT", 12, 0)
ftDiv:SetPoint("RIGHT", rSC, "RIGHT", -12, 0)
ftDiv:SetPoint("TOP", rightBottom, "BOTTOM", 0, -14)

local ftHeader = CreateFrame("Frame", nil, rSC)
ftHeader:SetPoint("TOPLEFT", ftDiv, "BOTTOMLEFT", 0, -14)
ftHeader:SetPoint("TOPRIGHT", ftDiv, "BOTTOMRIGHT", 0, -14)
ftHeader:SetHeight(20)

local ftTitle = MakeSectionTitle(ftHeader, "Farm Timer")
ftTitle:SetPoint("LEFT", 0, 0)

local ftOptBtn = CreateFrame("Button", nil, ftHeader)
ftOptBtn:SetSize(64, 18)
ftOptBtn:SetPoint("RIGHT", 0, 0)

ftOptBtn.bg = ftOptBtn:CreateTexture(nil, "BACKGROUND")
ftOptBtn.bg:SetAllPoints(ftOptBtn)
ftOptBtn.bg:SetTexture("Interface\\Buttons\\WHITE8x8")
ftOptBtn.bg:SetVertexColor(1, 1, 1, 1)
ftOptBtn.bg:SetAlpha(0)

ftOptBtn.txt = ftOptBtn:CreateFontString(nil, "OVERLAY", "WF_GameFontDisableSmall")
ftOptBtn.txt:SetPoint("CENTER", 0, 0)
ftOptBtn.txt:SetText("Options")
do
  local mr, mg, mb = C4(MUTED, MUTED)
  if ftOptBtn.txt then ftOptBtn.txt:SetTextColor(mr, mg, mb, 1) end
end


_WF_ApplyGearOptionButton(ftOptBtn)
ftOptBtn:SetScript("OnEnter", function()
  _WF_GearOpt_SetHover(ftOptBtn, true)
  if GameTooltip then
    if Widgets and Widgets.EnsureTooltipSkin then Widgets:EnsureTooltipSkin() end
    GameTooltip:SetOwner(ftOptBtn, "ANCHOR_RIGHT")
    if GameTooltip.ClearLines then GameTooltip:ClearLines() end

    local ar, ag, ab = C4(ACCENT, ACCENT)
    GameTooltip:AddLine("Farm Timer Options", ar, ag, ab)
    GameTooltip:AddLine("Toggle the options panel below.", TEXT[1], TEXT[2], TEXT[3], true)
    GameTooltip:AddLine("Edit phase durations, warnings, and HUD settings.", 0.75, 0.75, 0.75, true)
    GameTooltip:Show()
  end
end)
ftOptBtn:SetScript("OnLeave", function()
  _WF_GearOpt_SetHover(ftOptBtn, false)
  if GameTooltip then GameTooltip:Hide() end
    _WF_TooltipFollow_Stop()
end)

local ftStatus = MakeMutedText(ftHeader, "")
ftStatus:SetPoint("LEFT", ftTitle, "RIGHT", 10, 0)
ftStatus:SetPoint("RIGHT", ftOptBtn, "LEFT", -8, 0)
ftStatus:SetJustifyH("RIGHT")
if ftStatus.SetWordWrap then ftStatus:SetWordWrap(false) end
-- Distinct phase cards (Kill / Loot / Grace)

-- Farm Timer styling: rounded corners for phase cards / buttons (match addon look)
local function _FT_SetRoundedBackdrop(frame, bgA, borderA, edgeSize, inset)
  if not (frame and frame.SetBackdrop) then return end
  edgeSize = tonumber(edgeSize) or 10
  inset = tonumber(inset) or 3

  frame:SetBackdrop({
    bgFile = "Interface/Buttons/WHITE8X8",
    edgeFile = "Interface/Tooltips/UI-Tooltip-Border",
    edgeSize = edgeSize,
    insets = { left = inset, right = inset, top = inset, bottom = inset },
  })

  if frame.SetBackdropColor then
    frame:SetBackdropColor(0, 0, 0, tonumber(bgA) or 0.16)
  end
  if frame.SetBackdropBorderColor then
    frame:SetBackdropBorderColor(1, 1, 1, tonumber(borderA) or 0.10)
  end
end

local function _FT_RoundExistingBackdrop(frame, edgeSize, inset)
  if not (frame and frame.SetBackdrop) then return end

  local bd = (frame.GetBackdrop and frame:GetBackdrop()) or nil
  local bgFile = (bd and bd.bgFile) or "Interface/Buttons/WHITE8X8"

  -- Preserve current colors if supported
  local br, bg, bb, ba
  local r, g, b, a
  if frame.GetBackdropColor then
    r, g, b, a = frame:GetBackdropColor()
  end
  if frame.GetBackdropBorderColor then
    br, bg, bb, ba = frame:GetBackdropBorderColor()
  end

  edgeSize = tonumber(edgeSize) or 9
  inset = tonumber(inset) or 3

  frame:SetBackdrop({
    bgFile = bgFile,
    edgeFile = "Interface/Tooltips/UI-Tooltip-Border",
    edgeSize = edgeSize,
    insets = { left = inset, right = inset, top = inset, bottom = inset },
  })

  if r and frame.SetBackdropColor then
    frame:SetBackdropColor(r, g, b, a)
  end
  if br and frame.SetBackdropBorderColor then
    frame:SetBackdropBorderColor(br, bg, bb, ba)
  end
end

local function MakePhaseCard(parent, label, w)
  local card = CreateFrame("Frame", nil, parent, (BackdropTemplateMixin and "BackdropTemplate") or nil)
  card:SetSize(w or 68, 40)

  local tr, tg, tb = C4(TEXT, TEXT)
  local mr, mg, mb = C4(MUTED, MUTED)

  -- Subtle dark panel with rounded corners
  _FT_SetRoundedBackdrop(card, 0.16, 0.10, 9, 3)

  card.lbl = card:CreateFontString(nil, "OVERLAY", "WF_GameFontDisableSmall")
  card.lbl:SetPoint("TOP", 0, -5)
  card.lbl:SetJustifyH("CENTER")
  card.lbl:SetTextColor(mr, mg, mb)
  card.lbl:SetText(label or "")

  card.edit = CreateFrame("EditBox", nil, card)
  card.edit:SetSize((w or 68) - 16, 18)
  card.edit:SetPoint("BOTTOM", 0, 6)
  card.edit:SetFontObject("WF_GameFontHighlightSmall")
  card.edit:SetAutoFocus(false)
  card.edit:SetJustifyH("CENTER")
  card.edit:SetTextInsets(4, 4, 0, 0)
  card.edit:SetTextColor(tr, tg, tb)

  do
    local f, _, fl = card.edit:GetFont()
    if f then
      card.edit:SetFont(f, 14, fl or "OUTLINE")
    end
  end

  card.edit:SetScript("OnEscapePressed", card.edit.ClearFocus)
  card.edit:SetScript("OnEnterPressed", card.edit.ClearFocus)

  card.edit:SetScript("OnEditFocusGained", function()
    if card.SetBackdropBorderColor then card:SetBackdropBorderColor(1, 1, 1, 0.18) end
    if card.SetBackdropColor then card:SetBackdropColor(0, 0, 0, 0.22) end
  end)

  card.edit:SetScript("OnEditFocusLost", function()
    if card.SetBackdropBorderColor then card:SetBackdropBorderColor(1, 1, 1, 0.10) end
    if card.SetBackdropColor then card:SetBackdropColor(0, 0, 0, 0.16) end
  end)

  return card
end

local cardKill = MakePhaseCard(rSC, "Kill", 68)
cardKill:SetPoint("TOPLEFT", ftHeader, "BOTTOMLEFT", 0, -10)

local cardLoot = MakePhaseCard(rSC, "Loot", 68)
cardLoot:SetPoint("LEFT", cardKill, "RIGHT", 6, 0)

local cardGrace = MakePhaseCard(rSC, "Grace", 68)
cardGrace:SetPoint("LEFT", cardLoot, "RIGHT", 6, 0)
cardKill.edit:SetText(tostring(FT.cfg.kill or "1:45"))
cardLoot.edit:SetText(tostring(FT.cfg.loot or "0:15"))
cardGrace.edit:SetText(tostring(FT.cfg.grace or "0:05"))

-- Options panel (collapsed by default)
FT.cfg.uiOpen = FT.cfg.uiOpen and true or false

local optPanel = CreateFrame("Frame", nil, rSC, (BackdropTemplateMixin and "BackdropTemplate") or nil)
optPanel:SetPoint("TOP", cardKill, "BOTTOM", 0, -10)
optPanel:SetPoint("LEFT", ftDiv, "LEFT", 0, 0)
optPanel:SetPoint("RIGHT", ftDiv, "RIGHT", 0, 0)
optPanel:SetHeight(82)

_FT_SetRoundedBackdrop(optPanel, 0.10, 0.08, 9, 3)

local function MakeCheck(parent, label)
  local cb = CreateFrame("CheckButton", nil, parent, "UICheckButtonTemplate")
  cb:SetSize(20, 20)

  WF_ApplyBlueCheck(cb)
  local t = cb:CreateFontString(nil, "OVERLAY", "WF_GameFontDisableSmall")
  t:SetPoint("LEFT", cb, "RIGHT", 4, 1)
  t:SetText(label or "")
  cb._label = t

  return cb
end

local cbLoop = MakeCheck(optPanel, "Loop cycle")
local col1X, col2X = 8, 118

cbLoop:SetPoint("TOPLEFT", optPanel, "TOPLEFT", col1X, -8)

local cbParty = MakeCheck(optPanel, "Party mode")
cbParty:SetPoint("TOPLEFT", optPanel, "TOPLEFT", col2X, -8)

local cbHud = MakeCheck(optPanel, "Mini timer HUD")
cbHud:SetPoint("TOPLEFT", optPanel, "TOPLEFT", col1X, -30)

local function _FT_AttachTip(frame, title, body)
  if not (frame and frame.HookScript) then return end

  frame:HookScript("OnEnter", function(selfTip)
    if not GameTooltip then return end
    if Widgets and Widgets.EnsureTooltipSkin then Widgets:EnsureTooltipSkin() end
    GameTooltip:SetOwner(selfTip, "ANCHOR_RIGHT")
    GameTooltip:AddLine(tostring(title or ""), ACCENT[1], ACCENT[2], ACCENT[3], true)
    body = tostring(body or "")
    if body ~= "" then
      GameTooltip:AddLine(body, TEXT[1], TEXT[2], TEXT[3], true)
    end
    GameTooltip:Show()
  end)

  frame:HookScript("OnLeave", function()
    if GameTooltip then GameTooltip:Hide() end
    _WF_TooltipFollow_Stop()
  end)
end

_FT_AttachTip(cbLoop, "Loop cycle", "Automatically restarts after the Grace phase.")
_FT_AttachTip(cbParty, "Party mode", "Announce phase changes and warnings in group chat (Party/Raid/Raid Warning when appropriate).")
_FT_AttachTip(cbHud, "Mini timer HUD", "Show a small on-screen timer overlay while running.")

local warnLbl = MakeMutedText(optPanel, "Warn at")
warnLbl:SetPoint("TOPLEFT", optPanel, "TOPLEFT", col1X + 2, -54)
warnLbl:SetJustifyH("LEFT")

local warnBox = CreateFrame("Frame", nil, optPanel, (BackdropTemplateMixin and "BackdropTemplate") or nil)
warnBox:SetSize(42, 20)
warnBox:SetPoint("LEFT", warnLbl, "RIGHT", 8, 0)

if warnBox.SetBackdrop then
  local ar, ag, ab = C4(ACCENT, TEXT)
  warnBox:SetBackdrop({
    bgFile = "Interface/Buttons/WHITE8X8",
    edgeFile = "Interface/Buttons/WHITE8X8",
    edgeSize = 1,
    insets = { left = 1, right = 1, top = 1, bottom = 1 },
  })
  warnBox:SetBackdropColor(0, 0, 0, 0.22)
  warnBox:SetBackdropBorderColor(1, 1, 1, 0.12)
end

local warnEB = CreateFrame("EditBox", nil, warnBox)
warnEB:SetAllPoints(warnBox)
warnEB:SetFontObject("WF_GameFontHighlightSmall")
warnEB:SetAutoFocus(false)
warnEB:SetJustifyH("CENTER")
warnEB:SetMaxLetters(3)
warnEB:SetTextInsets(6, 6, 0, 0)
if warnEB.SetNumeric then warnEB:SetNumeric(true) end
warnEB:SetScript("OnEscapePressed", warnEB.ClearFocus)
warnEB:SetScript("OnEnterPressed", warnEB.ClearFocus)

local warnSuf = MakeMutedText(optPanel, "s")
warnSuf:SetPoint("LEFT", warnBox, "RIGHT", 6, 0)

_FT_AttachTip(warnBox, "Warn at", "Seconds before the phase ends to trigger the warning.")
_FT_AttachTip(warnEB, "Warn at", "Seconds before the phase ends to trigger the warning.")


local function _ReflowFTOptions()
  if not (optPanel and optPanel.GetWidth) then return end
  local w = optPanel:GetWidth() or 0
  if w <= 0 then return end

  local pad  = 8
  local rowH = 22
  local single = (w < 220)

  -- Clear anchors (we re-anchor based on available width)
  cbLoop:ClearAllPoints()
  cbParty:ClearAllPoints()
  cbHud:ClearAllPoints()
  warnLbl:ClearAllPoints()
  warnBox:ClearAllPoints()
  warnSuf:ClearAllPoints()

  local function _SetLabelWidth(cb, width)
    if not (cb and cb._label and cb._label.SetWidth) then return end
    if width < 60 then width = 60 end
    cb._label:SetWidth(width)
    if cb._label.SetWordWrap then cb._label:SetWordWrap(false) end
    if cb._label.SetJustifyH then cb._label:SetJustifyH("LEFT") end
  end

  if single then
    cbLoop:SetPoint("TOPLEFT", optPanel, "TOPLEFT", pad, -8)
    cbParty:SetPoint("TOPLEFT", optPanel, "TOPLEFT", pad, -8 - rowH)
    cbHud:SetPoint("TOPLEFT", optPanel, "TOPLEFT", pad, -8 - (rowH * 2))

    local warnY = -8 - (rowH * 3) - 8
    warnLbl:SetPoint("TOPLEFT", optPanel, "TOPLEFT", pad + 2, warnY)

    local boxW = 42
    if w < 220 then boxW = 36 end
    if warnBox.SetWidth then warnBox:SetWidth(boxW) end

    warnBox:SetPoint("LEFT", warnLbl, "RIGHT", 8, 0)
    warnSuf:SetPoint("LEFT", warnBox, "RIGHT", 6, 0)

    if optPanel.SetHeight then optPanel:SetHeight(132) end

    local labelW = w - (pad * 2) - 28
    _SetLabelWidth(cbLoop, labelW)
    _SetLabelWidth(cbParty, labelW)
    _SetLabelWidth(cbHud, labelW)
  else
    local inner = w - (pad * 2)
    local colW  = math.floor(inner / 2)
    local col2X = pad + colW

    cbLoop:SetPoint("TOPLEFT", optPanel, "TOPLEFT", pad, -8)
    cbParty:SetPoint("TOPLEFT", optPanel, "TOPLEFT", col2X, -8)
    cbHud:SetPoint("TOPLEFT", optPanel, "TOPLEFT", pad, -30)

    warnLbl:SetPoint("TOPLEFT", optPanel, "TOPLEFT", pad + 2, -54)

    local boxW = 42
    if w < 280 then boxW = 38 end
    if warnBox.SetWidth then warnBox:SetWidth(boxW) end

    warnBox:SetPoint("LEFT", warnLbl, "RIGHT", 8, 0)
    warnSuf:SetPoint("LEFT", warnBox, "RIGHT", 6, 0)

    if optPanel.SetHeight then optPanel:SetHeight(82) end

    local labelW = colW - 28
    _SetLabelWidth(cbLoop, labelW)
    _SetLabelWidth(cbParty, labelW)
    _SetLabelWidth(cbHud, labelW)
  end
end

-- Make the options panel responsive so nothing gets clipped on narrow widths
optPanel:HookScript("OnSizeChanged", function() _ReflowFTOptions() end)
optPanel:HookScript("OnShow", function() _ReflowFTOptions() end)
_ReflowFTOptions()


cbLoop:SetChecked(FT.cfg.loop and true or false)
cbParty:SetChecked(FT.cfg.party and true or false)
cbHud:SetChecked(FT.cfg.hud and true or false)
FT._uiCbUnlock = nil

warnEB:SetText(tostring(tonumber(FT.cfg.warn or 10) or 10))

if FT.cfg.uiOpen then optPanel:Show() else optPanel:Hide() end

local ftHint = MakeMutedText(rSC, "")
ftHint:SetJustifyH("LEFT")

local ftBtnRow = CreateFrame("Frame", nil, rSC)
ftBtnRow:SetSize(220, 26)

local bFT = Widgets:Button(ftBtnRow, "Start Timer", 220, 26)
bFT:SetPoint("LEFT", 0, 0)

-- Round the timer buttons (only if they use backdrops)
_FT_RoundExistingBackdrop(bFT, 9, 3)

local bFTStop = Widgets:Button(ftBtnRow, "Stop", 106, 26)
bFTStop:SetPoint("LEFT", bFT, "RIGHT", 8, 0)
bFTStop:Hide()

_FT_RoundExistingBackdrop(bFTStop, 9, 3)

-- Some custom button templates don't expose :SetText, but FT:UpdateUI expects it.
local function _FT_EnsureButtonSetText(btn)
  if not btn or btn._wfPatchedSetText then return end

  local fs = nil
  if btn.GetFontString then
    fs = btn:GetFontString()
  end
  if not fs then
    fs = btn.label or btn.text or btn._text or btn._label or btn.Text
  end

  if fs and fs.SetText then
    btn.SetText = function(selfBtn, s)
      fs:SetText(tostring(s or ""))
    end
    btn._wfPatchedSetText = true
  end
end

_FT_EnsureButtonSetText(bFT)
_FT_EnsureButtonSetText(bFTStop)

local function _LayoutTimerButtons(running)
  if running then
    if bFT.SetWidth then bFT:SetWidth(106) end
    bFT:SetPoint("LEFT", 0, 0)

    if bFTStop.SetWidth then bFTStop:SetWidth(106) end
    bFTStop:ClearAllPoints()
    bFTStop:SetPoint("LEFT", bFT, "RIGHT", 8, 0)
    bFTStop:Show()
  else
    bFTStop:Hide()
    if bFT.SetWidth then bFT:SetWidth(220) end
    bFT:SetPoint("LEFT", 0, 0)
  end
end


local function _SaveTimerEdits()
  FT.cfg.kill = tostring(cardKill.edit:GetText() or "")
  FT.cfg.loot = tostring(cardLoot.edit:GetText() or "")
  FT.cfg.grace = tostring(cardGrace.edit:GetText() or "")

  local w = tonumber(warnEB:GetText() or "")
  if not w then w = tonumber(FT.cfg.warn) or 10 end
  w = math.floor(w + 0.00001)
  if w < 1 then w = 1 end
  if w > 999 then w = 999 end
  FT.cfg.warn = w
  warnEB:SetText(tostring(w))
end

local function _UpdateHint()
  local w = tonumber(FT.cfg.warn or 10) or 10
  ftHint:SetText("Warn at " .. tostring(w) .. "s: raid warning + repeat announce")
end

local function _LayoutFarmTimer()
  ftHint:ClearAllPoints()
  ftBtnRow:ClearAllPoints()

  if optPanel:IsShown() then
    ftHint:SetPoint("TOPLEFT", optPanel, "BOTTOMLEFT", 6, -6)
  else
    ftHint:SetPoint("TOPLEFT", cardKill, "BOTTOMLEFT", 2, -6)
  end

  ftBtnRow:SetPoint("TOPLEFT", ftHint, "BOTTOMLEFT", -2, -6)
end

_UpdateHint()
_LayoutFarmTimer()

rightBottom = ftBtnRow

-- Wire UI -> timer
FT._uiStatus = ftStatus
FT._uiStart = bFT
FT._uiStop = bFTStop
FT._uiLayoutButtons = _LayoutTimerButtons
FT:UpdateUI(true)

ftOptBtn:SetScript("OnClick", function()
  FT.cfg.uiOpen = not FT.cfg.uiOpen
  if FT.cfg.uiOpen then
    optPanel:Show()
    _ReflowFTOptions()
  else
    optPanel:Hide()
  end
  _LayoutFarmTimer()

  if UI and UI._UpdateOverviewRightScroll then
    UI:_UpdateOverviewRightScroll()
  end
end)

local function _AfterOptionChange()
  _SaveTimerEdits()
  _UpdateHint()
  if FT and FT.UpdateUI then FT:UpdateUI(true) end
end

cbLoop:SetScript("OnClick", function(selfBtn)
  FT.cfg.loop = selfBtn:GetChecked() and true or false
end)
cbParty:SetScript("OnClick", function(selfBtn)
  FT.cfg.party = selfBtn:GetChecked() and true or false
end)
cbHud:SetScript("OnClick", function(selfBtn)
  FT.cfg.hud = selfBtn:GetChecked() and true or false
  if FT.state and FT.state.running then
    FT:_ShowHUD(FT.cfg.hud)
  end
end)
warnEB:SetScript("OnEditFocusLost", function()
  _AfterOptionChange()
end)

bFT:SetScript("OnClick", function()
  if FT.state and FT.state.running then
    if FT.state.paused then
      FT:Resume()
    else
      FT:Pause()
    end
  else
    _SaveTimerEdits()
    _UpdateHint()
    FT:Start()
  end

  if UI and UI._UpdateOverviewRightScroll then
    UI:_UpdateOverviewRightScroll()
  end
end)

bFTStop:SetScript("OnClick", function()
  if FT.state and FT.state.running then
    FT:Stop()
    if UI and UI._UpdateOverviewRightScroll then
      UI:_UpdateOverviewRightScroll()
    end
  end
end)


return rightBottom
end
