local ADDON, ns = ...
local L = ns.L
local Addon = LibStub("AceAddon-3.0"):GetAddon(ADDON)
local AceConfig = LibStub("AceConfig-3.0")
local AceConfigDialog = LibStub("AceConfigDialog-3.0")
local AceGUI = LibStub("AceGUI-3.0")

local function get(info) return Addon.db.profile[info[#info]] end
local function set(info, val) Addon.db.profile[info[#info]] = val end

-- ElvUI skin helper (best effort)
local function TrySkinWithElvUI(btnFrame)
  if not btnFrame then return end
  if type(_G.ElvUI) ~= "table" then return end

  local ok, E = pcall(unpack, _G.ElvUI)
  if not ok or not E or not E.GetModule then return end

  local S = E:GetModule("Skins", true)
  if not S then return end

  if type(S.HandleButton) == "function" then
    pcall(S.HandleButton, S, btnFrame, true)
  end
end

local options = {
  type = "group",
  name = L["AddonName"],
  args = {
    general = {
      type = "group",
      name = L["General"],
      inline = true,
      order = 1,
      args = {
        -- bleibt im Table, aber unsichtbar (Standard-Button ist oben rechts)
        defaults = {
          type = "execute",
          name = DEFAULTS, -- WoW-global, lokalisiert
          desc = L["DefaultsDesc"],
          confirm = true,
          confirmText = L["DefaultsConfirm"],
          order = 0,
          width = 0.8,
          hidden = true,
          func = function()
            if Addon.db and Addon.db.ResetProfile then
              Addon.db:ResetProfile()
            end

            if Addon.ApplyBugSackAltWipe then
              Addon:ApplyBugSackAltWipe()
            end
            if Addon.db and Addon.db.profile and Addon.db.profile.extendTooltip and Addon.PatchBugSackTooltip then
              Addon:PatchBugSackTooltip()
            end

            LibStub("AceConfigRegistry-3.0"):NotifyChange(ADDON)
          end,
        },

        disableSend = {
          type = "toggle",
          name = (L["DisableSendShort"] or L["DisableSend"]),
          desc = L["DisableSendDesc"],
          descStyle = "inline",
          width = "full",
          get = get, set = set,
          order = 1,
        },

        receiveMode = {
          type = "select",
          name = (L["ReceiveModeShort"] or L["ReceiveMode"]),
          desc = L["ReceiveModeDesc"],
          descStyle = "inline",
          width = "full",
          values = {
            OFF = L["ModeOff"],
            ALWAYS = L["ModeAlways"],
            COMBAT = L["ModeCombat"],
            OPENWORLD = L["ModeOpenWorldOnly"],
          },
          get = get, set = set,
          order = 2,
        },

        replyToSender = {
          type = "toggle",
          name = (L["ReplyToSenderShort"] or L["ReplyToSender"]),
          desc = L["ReplyToSenderDesc"],
          descStyle = "inline",
          width = "full",
          get = get, set = set,
          order = 3,
        },

        replyMessage = {
          type = "input",
          name = (L["ReplyMessageShort"] or L["ReplyMessage"]),
          desc = L["ReplyMessageDesc"],
          descStyle = "inline",
          width = "full",
          get = function() return Addon.db.profile.replyMessage or "" end,
          set = function(_, val) Addon.db.profile.replyMessage = val end,
          order = 4,
          disabled = function() return not Addon.db.profile.replyToSender end,
        },

        replyThrottle = {
          type = "range",
          name = (L["ReplyThrottleShort"] or L["ReplyThrottle"]),
          desc = L["ReplyThrottleDesc"],
          descStyle = "inline",
          width = "full",
          min = 0, max = 60, step = 1,
          get = function() return tonumber(Addon.db.profile.replyThrottle) or 5 end,
          set = function(_, val) Addon.db.profile.replyThrottle = val end,
          order = 5,
          disabled = function() return not Addon.db.profile.replyToSender end,
        },

        verbose = {
          type = "toggle",
          name = (L["VerboseShort"] or L["Verbose"]),
          desc = L["VerboseDesc"],
          descStyle = "inline",
          width = "full",
          get = get, set = set,
          order = 6,
        },

        enableAltWipe = {
          type = "toggle",
          name = (L["EnableAltWipeShort"] or L["EnableAltWipe"]),
          desc = L["EnableAltWipeDesc"],
          descStyle = "inline",
          width = "full",
          order = 7,
          get = function() return Addon.db.profile.enableAltWipe end,
          set = function(_, val)
            Addon.db.profile.enableAltWipe = val and true or false
            Addon:ApplyBugSackAltWipe()
          end,
        },

        extendTooltip = {
          type = "toggle",
          name = (L["ExtendTooltipShort"] or L["ExtendTooltip"]),
          desc = L["ExtendTooltipDesc"],
          descStyle = "inline",
          width = "full",
          order = 8,
          get = function() return Addon.db.profile.extendTooltip end,
          set = function(_, val)
            Addon.db.profile.extendTooltip = val and true or false
            if Addon.db.profile.extendTooltip then
              Addon:PatchBugSackTooltip()
            end
          end,
        },
      }
    }
  }
}

AceConfig:RegisterOptionsTable(ADDON, options)

-- AddToBlizOptions liefert (frame, categoryID). Wir hängen Deko/Buttons an "frame".
local frame, categoryID = AceConfigDialog:AddToBlizOptions(ADDON, L["AddonName"] .. " |TInterface/AddOns/BugSackBlock/Media/icon.tga:18:18:0:0|t")

-- Watermark: Logo unten rechts im Hintergrund (Originalfarben)
do
  if frame and not frame.BugSackBlockWatermark then
    local wm = frame:CreateTexture(nil, "BACKGROUND", nil, -8) -- weit nach hinten
    frame.BugSackBlockWatermark = wm

    wm:SetTexture("Interface\\AddOns\\BugSackBlock\\Media\\icon.tga")
    wm:SetSize(192, 192)
    wm:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", -12, 12)

    if wm.SetDesaturated then wm:SetDesaturated(false) end
    if wm.SetVertexColor then wm:SetVertexColor(1, 1, 1, 1) end
    wm:SetBlendMode("BLEND")
    wm:SetAlpha(0.14)
  end
end

-- Container nach unten schieben (best effort, einmalig)
do
  local function ShiftContentDown()
    if not frame or frame.__BSB_shifted then return end
    frame.__BSB_shifted = true

    local defaultsFrame = frame.BugSackBlockDefaultsAceGUI and frame.BugSackBlockDefaultsAceGUI.frame

    for _, child in ipairs({ frame:GetChildren() }) do
      if child ~= defaultsFrame then
        local p, rel, rp, x, y = child:GetPoint(1)
        if rel == frame and (p == "TOPLEFT" or p == "TOP") then
          child:ClearAllPoints()
          child:SetPoint(p, rel, rp, x, (y or 0) - 26) -- << hier kannst du die Zahl anpassen
          break
        end
      end
    end
  end

  if frame and not frame.__BSB_shiftHooked then
    frame.__BSB_shiftHooked = true
    frame:HookScript("OnShow", ShiftContentDown)
    ShiftContentDown()
  end
end

-- Standard-Button oben rechts + Confirm
do
  local function DoReset()
    options.args.general.args.defaults.func()
  end

  if type(StaticPopupDialogs) == "table" and not StaticPopupDialogs.BugSackBlockDefaultsConfirm then
    StaticPopupDialogs.BugSackBlockDefaultsConfirm = {
      text = L["DefaultsConfirm"],
      button1 = OKAY,
      button2 = CANCEL,
      timeout = 0,
      whileDead = true,
      hideOnEscape = true,
      preferredIndex = 3,
      OnAccept = function()
        DoReset()
      end,
    }
  end

  if frame and not frame.BugSackBlockDefaultsAceGUI then
    local b = AceGUI:Create("Button")
    frame.BugSackBlockDefaultsAceGUI = b

    b:SetText(DEFAULTS)
    b:SetWidth(120)
    b:SetHeight(22)

    b.frame:SetParent(frame)
    b.frame:ClearAllPoints()
    b.frame:SetPoint("TOPRIGHT", frame, "TOPRIGHT", -16, -16)
    b.frame:SetFrameStrata("HIGH")
    b.frame:SetFrameLevel((frame:GetFrameLevel() or 0) + 10)
    b.frame:Show()

    TrySkinWithElvUI(b.frame)

    local f = CreateFrame("Frame")
    f:RegisterEvent("ADDON_LOADED")
    f:SetScript("OnEvent", function(_, _, name)
      if name == "ElvUI" then
        TrySkinWithElvUI(b.frame)
        f:UnregisterEvent("ADDON_LOADED")
      end
    end)

    b:SetCallback("OnClick", function()
      StaticPopup_Show("BugSackBlockDefaultsConfirm")
    end)
  end
end

Addon.optionsCategoryID = categoryID