local _, addon = ...
local HLY = addon.HLY

-- Shift + double-right-click casts Fishing. Casting from a plain click is
-- protected, so we route it through a secure button + an override binding on
-- BUTTON2 (same trick GoFish/ZenFishing use), armed on the double-click.

local DOUBLE_MAX = 0.4
local DOUBLE_MIN = 0.05
local BTN = "HLYFishingButton"

local function GetFishingSpellName()
    if not GetProfessions then return nil end
    local _, _, _, fishing = GetProfessions()
    if not fishing then return nil end
    return (GetProfessionInfo(fishing))  -- localized "Fishing"
end

function HLY:SetupFishing()
    if self.fishingSetup then return end
    self.fishingSetup = true

    local btn = _G[BTN] or CreateFrame("Button", BTN, UIParent, "SecureActionButtonTemplate")
    btn:Hide()

    local lastClick
    local frame = CreateFrame("Frame")
    frame:RegisterEvent("GLOBAL_MOUSE_DOWN")
    frame:SetScript("OnEvent", function(_, _, button)
        if not self.db or not self.db.fishing or not self.db.fishing.enabled then return end
        -- Override bindings are protected during combat lockdown; skip entirely.
        if InCombatLockdown() then return end

        if button ~= "RightButton" or not IsShiftKeyDown() then
            ClearOverrideBindings(btn)
            lastClick = nil
            return
        end

        local now = GetTime()
        if lastClick and (now - lastClick) < DOUBLE_MAX and (now - lastClick) > DOUBLE_MIN
            and not (LootFrame and LootFrame:IsShown()) then
            lastClick = nil
            local name = GetFishingSpellName()
            if name then
                if IsMouselooking() then MouselookStop() end
                SetOverrideBindingSpell(btn, true, "BUTTON2", name)
            end
        else
            lastClick = now
            ClearOverrideBindings(btn)
        end
    end)
end

-- LibHLYUI options pane (v2) ------------------------------------------------
function HLY:BuildFishingOptions(tab)
    tab:Note("Shift + Doppel-Rechtsklick wirft die Angel aus (Beruf Angeln erforderlich).")
    tab:Checkbox({
        label = "Enable",
        get = function() return self.db.fishing.enabled end,
        set = function(v) self.db.fishing.enabled = v end,
    })
end

addon.options = addon.options or {}
addon.options[#addon.options + 1] = {
    group = "Other", groupOrder = 800, name = "Fishing", order = 4, groupAsEntry = true,
    build = "BuildFishingOptions",
}
