-- Sleek RP - Warlock Pets (Options.lua)
-- Full in-game options UI with tabs + Addon Compartment + slash command.

local ADDON_NAME, SRPWL = ...
SRPWL = SRPWL or {}
_G.SRPWL = SRPWL

-- ==== Env (détection capacités) ==============================================
-- Assure-toi que Core/Env.lua est chargé avant ce fichier dans le TOC.
local Env = SRPWL.Env or {
  hasAddonCompartment = (AddonCompartmentFrame and AddonCompartmentFrame.RegisterAddon)
     or (C_AddOns and C_AddOns.RegisterAddonCompartment) or false,
}

SleekRP_WLP_DB = SleekRP_WLP_DB or {}
local DB = SleekRP_WLP_DB

-- ========= Handshake registry (used by Extensions page) =========
SRPWL._voicePackHello = SRPWL._voicePackHello or {} -- [addonName] = meta or true
function SRPWL.RegisterVoicePack(addonName, meta)
  if type(addonName) == "string" and addonName ~= "" then
    SRPWL._voicePackHello[addonName] = meta or true
    if _G.SRPWL_ExtensionsRefresh then pcall(_G.SRPWL_ExtensionsRefresh) end
  end
end

-- ===========================
-- Defaults (non-destructive)
-- ===========================
local function initDefaults()
  if DB.use_talking_style == nil then DB.use_talking_style = false end
  DB.talking_scale        = DB.talking_scale        or 1.0
  DB.talking_point        = DB.talking_point        or { "TOP", UIParent, "TOP", 0, -160 }
  DB.talking_duration     = DB.talking_duration     or 4.5
  DB.talking_lock         = (DB.talking_lock == true)
  DB.talking_instsuppress = (DB.talking_instsuppress ~= false)

  DB.global_scale         = DB.global_scale         or 1.0
  DB.mute_sounds          = (DB.mute_sounds == true)
  DB.dialogue_rate        = DB.dialogue_rate        or 1.0
  DB.portrait_style       = DB.portrait_style       or "cartoon"

  -- préférence Sayaad (Succubus par défaut)
  DB.sayaad_form          = (DB.sayaad_form == "incubus") and "incubus" or "succubus"
end

initDefaults()

-- Light API
SRPWL.GetMuteSounds     = function() return DB.mute_sounds end
SRPWL.GetDialogueRate   = function() return DB.dialogue_rate end
SRPWL.GetPortraitStyle  = function() return DB.portrait_style end
SRPWL.GetGlobalScale    = function() return DB.global_scale end

-- Notify helpers
local function notifyConfigChanged(key)
  if SRPWL and type(SRPWL.OnConfigChanged) == "function" then
    pcall(SRPWL.OnConfigChanged, key, DB[key], DB)
  end
  local f = _G["SRPWL_ConfigEventFrame"] or CreateFrame("Frame", "SRPWL_ConfigEventFrame")
  f:UnregisterAllEvents()
  f:RegisterEvent("PLAYER_LOGIN")
  if not f:GetScript("OnEvent") then f:SetScript("OnEvent", function() end) end
  if C_Timer and SRPWL and type(SRPWL.Broadcast) == "function" then
    C_Timer.After(0, function() pcall(SRPWL.Broadcast, "SRPWL_CONFIG_CHANGED", key, DB[key]) end)
  end
end

-- ===========================
-- Copy popup (Dragonflight/Classic-safe)
-- ===========================
local function ShowCopyPopup(title, text)
  if not StaticPopupDialogs["SRPWL_COPYPOPUP"] then
    StaticPopupDialogs["SRPWL_COPYPOPUP"] = {
      text = "%s",
      button1 = OKAY,
      hasEditBox = true,
      maxLetters = 512,
      editBoxWidth = 320,
      timeout = 0, whileDead = true, hideOnEscape = true, preferredIndex = 3,
      OnShow = function(self)
        local titleFS = self.Text or self.text
        if titleFS and titleFS.SetText then
          titleFS:SetText(self.data and self.data.title or "Link")
        end
        local eb = self.EditBox or self.editBox
        if eb then
          eb:SetText(self.data and self.data.text or "")
          if eb.SetFocus then eb:SetFocus() end
          if eb.HighlightText then eb:HighlightText() end
        end
      end,
      OnAccept = function(self) end,
      EditBoxOnEnterPressed = function(self) self:GetParent():Hide() end,
      EditBoxOnEscapePressed = function(self) self:GetParent():Hide() end,
    }
  end
  StaticPopup_Show("SRPWL_COPYPOPUP", title, nil, { title = title, text = text })
end

-- ===========================
-- Addon Compartment (Retail/MoP si dispo)
-- ===========================
local function registerAddonCompartment()
  if not Env.hasAddonCompartment then return end
  local iconTexture = "Interface\\AddOns\\" .. ADDON_NAME .. "\\Art\\Icon_Succubus_02"
  local function onClick()
    if type(_G.SRPWL_Options_Open) == "function" then _G.SRPWL_Options_Open() end
  end
  if AddonCompartmentFrame and AddonCompartmentFrame.RegisterAddon then
    AddonCompartmentFrame:RegisterAddon({
      text = "Sleek RP - Warlock Pets",
      icon = iconTexture, notCheckable = true,
      func = onClick,
      tooltip = "Open Sleek RP - Warlock Pets options",
    })
  elseif C_AddOns and C_AddOns.RegisterAddonCompartment then
    pcall(C_AddOns.RegisterAddonCompartment, "Sleek RP - Warlock Pets", onClick, iconTexture,
      "Open Sleek RP - Warlock Pets options")
  end
end

-- ===========================
-- Frame & Tabs
-- ===========================
local PANEL_WIDTH, PANEL_HEIGHT = 720, 540

local main = CreateFrame("Frame", "SRPWLOptionsFrame", UIParent, "BackdropTemplate")
main:SetSize(PANEL_WIDTH, PANEL_HEIGHT)
main:SetPoint("CENTER")
main:Hide()
main:SetFrameStrata("DIALOG")
main:SetClampedToScreen(true)
main:SetMovable(true)
main:EnableMouse(true)
main:RegisterForDrag("LeftButton")
main:SetScript("OnDragStart", main.StartMoving)
main:SetScript("OnDragStop", main.StopMovingOrSizing)

main:SetBackdrop({
  bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background",
  edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
  tile = true, tileSize = 16, edgeSize = 16,
  insets = { left = 4, right = 4, top = 4, bottom = 4 }
})

local title = main:CreateFontString(nil, "OVERLAY", "GameFontHighlightLarge")
title:SetPoint("TOP", 0, -12)
title:SetText("Sleek RP - Warlock Pets")

local close = CreateFrame("Button", nil, main, "UIPanelCloseButton")
close:SetPoint("TOPRIGHT", -4, -4)

-- ==== Safe tab helpers (Classic-safe) ========================================
local function hasGlobal(name) return _G[name] ~= nil end

local TAB_TEMPLATE = (hasGlobal("PanelTopTabButtonTemplate") and "PanelTopTabButtonTemplate")
                  or (hasGlobal("CharacterFrameTabButtonTemplate") and "CharacterFrameTabButtonTemplate")
                  or "UIPanelButtonTemplate"

local function SafeTabResize(tab, padding)
  padding = padding or 0
  local ok = false
  if PanelTemplates_TabResize then ok = pcall(PanelTemplates_TabResize, tab, padding) end
  if not ok then
    local fs = tab.Text or tab:GetFontString()
    if not fs then
      fs = tab:CreateFontString(nil, "ARTWORK", "GameFontHighlight")
      fs:SetPoint("CENTER", 0, -3)
      tab:SetFontString(fs)
      tab.Text = fs
    end
    tab:SetWidth((fs:GetStringWidth() or 80) + 24 + padding)
  end
end

local function SafeSelectTab(tab)
  if PanelTemplates_SelectTab then
    local ok = pcall(PanelTemplates_SelectTab, tab)
    if ok then return end
  end
  -- Fallback visual
  if tab.SetNormalFontObject then tab:SetNormalFontObject(GameFontHighlight) end
  if tab.Disable then tab:Disable() end
end

local function SafeDeselectTab(tab)
  if PanelTemplates_DeselectTab then
    local ok = pcall(PanelTemplates_DeselectTab, tab)
    if ok then return end
  end
  -- Fallback visual
  if tab.SetNormalFontObject then tab:SetNormalFontObject(GameFontNormal) end
  if tab.Enable then tab:Enable() end
end

local tabs = {}
local function CreateTab(id, text)
  local tab = CreateFrame("Button", nil, main, TAB_TEMPLATE)
  tab:SetID(id)
  if not tab.Text then
    local fs = tab:CreateFontString(nil, "ARTWORK", "GameFontHighlight")
    fs:SetPoint("CENTER", 0, (TAB_TEMPLATE == "UIPanelButtonTemplate") and 0 or -3)
    tab:SetFontString(fs)
    tab.Text = fs
  end
  tab:SetText(text or ("Tab "..id))
  if id == 1 then
    tab:SetPoint("TOPLEFT", main, "TOPLEFT", 12, -40)
  else
    tab:SetPoint("LEFT", tabs[id-1], "RIGHT", (TAB_TEMPLATE == "UIPanelButtonTemplate") and 8 or -15, 0)
  end
  SafeTabResize(tab, 0)
  tabs[id] = tab
  return tab
end

local pages = {}
local function CreatePage(name)
  local f = CreateFrame("Frame", nil, main, "BackdropTemplate")
  f:SetPoint("TOPLEFT", 12, -72)
  f:SetPoint("BOTTOMRIGHT", -12, 12)
  f:Hide()
  pages[name] = f
  return f
end

local function ShowTab(idx)
  for i, tab in ipairs(tabs) do
    if i == idx then SafeSelectTab(tab) else SafeDeselectTab(tab) end
  end
  local order = { "general", "appearance", "extensions", "sayaad", "donation" }
  for i, key in ipairs(order) do if pages[key] then pages[key]:SetShown(i == idx) end end
end

local function EnsureLabel(btn)
  if btn.Text and btn.Text.GetObjectType and btn.Text:GetObjectType() == "FontString" then return btn.Text end
  local fs = btn:CreateFontString(nil, "ARTWORK", "GameFontHighlight")
  fs:SetPoint("LEFT", btn, "RIGHT", 6, 0)
  btn.Text = fs
  return fs
end

local function tex(path) return "Interface\\AddOns\\"..ADDON_NAME.."\\Art\\"..path end

-- ===========================
-- General
-- ===========================
CreateTab(1, "General")
local general = CreatePage("general")

local scaleTitle = general:CreateFontString(nil, "OVERLAY", "GameFontNormal")
scaleTitle:SetPoint("TOPLEFT", 16, -8)
scaleTitle:SetText("Global Scale")

local scaleSlider = CreateFrame("Slider", "SRPWL_ScaleSlider", general, "OptionsSliderTemplate")
scaleSlider:SetPoint("TOPLEFT", scaleTitle, "BOTTOMLEFT", 0, -8)
scaleSlider:SetMinMaxValues(0.6, 1.6)
scaleSlider:SetValueStep(0.01)
scaleSlider:SetObeyStepOnDrag(true)
scaleSlider:SetWidth(260)
_G[scaleSlider:GetName().."Low"]:SetText("0.6")
_G[scaleSlider:GetName().."High"]:SetText("1.6")
_G[scaleSlider:GetName().."Text"]:SetText(string.format("Scale: %.2f", DB.global_scale or 1.0))
scaleSlider:SetValue(DB.global_scale or 1.0)
scaleSlider:SetScript("OnValueChanged", function(self, val)
  DB.global_scale = tonumber(string.format("%.2f", val))
  _G[self:GetName().."Text"]:SetText(string.format("Scale: %.2f", DB.global_scale))
  notifyConfigChanged("global_scale")
end)

local resetBtn = CreateFrame("Button", nil, general, "UIPanelButtonTemplate")
resetBtn:SetSize(180, 24)
resetBtn:SetPoint("TOPLEFT", scaleSlider, "BOTTOMLEFT", 0, -12)
resetBtn:SetText("Reset position / scale")
resetBtn:SetScript("OnClick", function()
  DB.global_scale  = 1.0
  DB.talking_scale = 1.0
  DB.talking_point = { "TOP", UIParent, "TOP", 0, -160 }
  if _G.SRPWL_TalkingFrame then
    local f = _G.SRPWL_TalkingFrame
    f:ClearAllPoints(); f:SetPoint(unpack(DB.talking_point)); f:SetScale(DB.talking_scale)
  end
  scaleSlider:SetValue(DB.global_scale)
  notifyConfigChanged("global_scale"); notifyConfigChanged("talking_scale"); notifyConfigChanged("talking_point")
end)

local freqTitle = general:CreateFontString(nil, "OVERLAY", "GameFontNormal")
freqTitle:SetPoint("TOPLEFT", resetBtn, "BOTTOMLEFT", 0, -18)
freqTitle:SetText("Dialogue Frequency")

local freqSlider = CreateFrame("Slider", "SRPWL_FreqSlider", general, "OptionsSliderTemplate")
freqSlider:SetPoint("TOPLEFT", freqTitle, "BOTTOMLEFT", 0, -8)
freqSlider:SetMinMaxValues(0.25, 2.0)
freqSlider:SetValueStep(0.05)
freqSlider:SetObeyStepOnDrag(true)
freqSlider:SetWidth(260)
_G[freqSlider:GetName().."Low"]:SetText("0.25x")
_G[freqSlider:GetName().."High"]:SetText("2.0x")
_G[freqSlider:GetName().."Text"]:SetText(string.format("Rate: %.2fx", DB.dialogue_rate or 1.0))
freqSlider:SetValue(DB.dialogue_rate or 1.0)
freqSlider:SetScript("OnValueChanged", function(self, val)
  DB.dialogue_rate = tonumber(string.format("%.2f", val))
  _G[self:GetName().."Text"]:SetText(string.format("Rate: %.2fx", DB.dialogue_rate))
  notifyConfigChanged("dialogue_rate")
end)

local muteCheck = CreateFrame("CheckButton", nil, general, "InterfaceOptionsCheckButtonTemplate")
muteCheck:SetPoint("TOPLEFT", freqSlider, "BOTTOMLEFT", 0, -14)
EnsureLabel(muteCheck):SetText("Temporarily disable pet sounds")
muteCheck:SetChecked(DB.mute_sounds)
muteCheck:SetScript("OnClick", function(self)
  DB.mute_sounds = self:GetChecked() and true or false
  notifyConfigChanged("mute_sounds")
end)

local testBtn = CreateFrame("Button", nil, general, "UIPanelButtonTemplate")
testBtn:SetSize(200, 26)
testBtn:SetPoint("TOPLEFT", muteCheck, "BOTTOMLEFT", 0, -16)
testBtn:SetText("Play a random test line")
testBtn:SetScript("OnClick", function()
  if SRPWL and type(SRPWL.TestRandomUtterance) == "function" then
    pcall(SRPWL.TestRandomUtterance)
  elseif SRPWL and SRPWL.Trigger and type(SRPWL.Trigger) == "function" then
    pcall(SRPWL.Trigger, "TEST_RANDOM")
  elseif _G.SRPWL_ShowTalkingHead then
    pcall(_G.SRPWL_ShowTalkingHead, "Random Pet", "Preview…", "This is a preview line.", "Interface\\Icons\\inv_misc_questionmark")
  else
    print("|cFFB595E9Sleek RP|r: No test hook available. (Wire SRPWL.TestRandomUtterance for this button.)")
  end
end)

-- Instance/Raid talking suppression toggle
local instCheck = CreateFrame("CheckButton", nil, general, "InterfaceOptionsCheckButtonTemplate")
instCheck:SetPoint("TOPLEFT", testBtn, "BOTTOMLEFT", 0, -14)
EnsureLabel(instCheck):SetText("Hide talking window in instances/raids")
instCheck:SetChecked(DB.talking_instsuppress)
instCheck:SetScript("OnClick", function(self)
  DB.talking_instsuppress = self:GetChecked() and true or false
  notifyConfigChanged("talking_instsuppress")
end)

local instNote = general:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
instNote:SetPoint("TOPLEFT", instCheck, "BOTTOMLEFT", 24, -6)
instNote:SetWidth(PANEL_WIDTH - 64)
instNote:SetJustifyH("LEFT")
instNote:SetText("When enabled, the pet talking window is hidden while you are in LFD/LFR/instance or raid groups.")

-- ===========================
-- Appearance
-- ===========================
CreateTab(2, "Appearance")
local appearance = CreatePage("appearance")

local portraitTitle = appearance:CreateFontString(nil, "OVERLAY", "GameFontNormal")
portraitTitle:SetPoint("TOPLEFT", 16, -8)
portraitTitle:SetText("Pet Portrait Style")

local cartoon = CreateFrame("CheckButton", nil, appearance, "UIRadioButtonTemplate")
cartoon:SetPoint("TOPLEFT", portraitTitle, "BOTTOMLEFT", 0, -8)
EnsureLabel(cartoon):SetText("Cartoon")
cartoon:SetChecked(DB.portrait_style == "cartoon")

local realistic = CreateFrame("CheckButton", nil, appearance, "UIRadioButtonTemplate")
realistic:SetPoint("TOPLEFT", cartoon, "BOTTOMLEFT", 0, -8)
EnsureLabel(realistic):SetText("Realistic")
realistic:SetChecked(DB.portrait_style == "realistic")

local function refreshPortraitRadios()
  cartoon:SetChecked(DB.portrait_style == "cartoon")
  realistic:SetChecked(DB.portrait_style == "realistic")
end

cartoon:SetScript("OnClick", function()
  DB.portrait_style = "cartoon"; refreshPortraitRadios(); notifyConfigChanged("portrait_style")
end)
realistic:SetScript("OnClick", function()
  DB.portrait_style = "realistic"; refreshPortraitRadios(); notifyConfigChanged("portrait_style")
end)

local note = appearance:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
note:SetPoint("TOPLEFT", realistic, "BOTTOMLEFT", 0, -10)
note:SetWidth(PANEL_WIDTH - 64)
note:SetJustifyH("LEFT")
note:SetText("Choose how pet portraits look in chat: stylized (Cartoon) or more detailed (Realistic).")

-- ===========================
-- Extensions
-- ===========================
CreateTab(3, "Extensions")
local ext = CreatePage("extensions")

local extTitle = ext:CreateFontString(nil, "OVERLAY", "GameFontNormal")
extTitle:SetPoint("TOPLEFT", 16, -8)
extTitle:SetText("Optional Packs / Extensions Loaded")

local EXT_ADDONS = {
  { key = "Imp",        names = { "SleekRP_Warlock_ImpVoice"        }, art = "Icon_Imp_02" },
  { key = "Voidwalker", names = { "SleekRP_Warlock_VoidwalkerVoice"  }, art = "Icon_Voidwalker_02" },
  { key = "Succubus",   names = { "SleekRP_Warlock_SuccubusVoice"    }, art = "Icon_Succubus_02" },
  { key = "Sayaad",     names = { "SleekRP_Warlock_IncubusVoice"     }, art = "Icon_Sayaad_02" }, -- Incubus pack
  { key = "Felhunter",  names = { "SleekRP_Warlock_FelhunterVoice"   }, art = "Icon_Felhunter_02" },
  { key = "Felguard",   names = { "SleekRP_Warlock_FelguardVoice"    }, art = "Icon_Felguard_02" },
}

local COLS, ROWS = 3, 2
local CELL_W, CELL_H = 200, 160
local startX, startY = 16, -36

-- expose a refresh for handshake callbacks
local refreshers = {}
_G.SRPWL_ExtensionsRefresh = function()
  for _, fn in ipairs(refreshers) do pcall(fn) end
end

local function pickHandshakeName(info)
  for _, n in ipairs(info.names) do
    if SRPWL._voicePackHello[n] ~= nil then return n end
  end
  return info.names[1]
end

for i, info in ipairs(EXT_ADDONS) do
  local col = ((i-1) % COLS)
  local row = math.floor((i-1) / COLS)

  local holder = CreateFrame("Frame", nil, ext, "BackdropTemplate")
  holder:SetSize(CELL_W, CELL_H)
  holder:SetPoint("TOPLEFT", startX + col*(CELL_W+12), startY - row*(CELL_H+12))
  holder:SetBackdrop({
    bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background",
    edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
    tile = true, tileSize = 16, edgeSize = 12,
    insets = { left = 4, right = 4, top = 4, bottom = 4 }
  })

  local icon = holder:CreateTexture(nil, "ARTWORK")
  icon:SetSize(64, 64)
  icon:SetPoint("TOP", 0, -12)
  icon:SetTexture(tex(info.art or "Icon_Succubus_02"))

  local label = holder:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
  label:SetPoint("TOP", icon, "BOTTOM", 0, -6)
  label:SetText(info.key)

  local status = holder:CreateTexture(nil, "OVERLAY")
  status:SetSize(18, 18)
  status:SetPoint("TOP", label, "BOTTOM", 0, -8)

  local function refresh()
    local name = pickHandshakeName(info)
    local handshake = SRPWL._voicePackHello[name] ~= nil
    if handshake then
      status:SetColorTexture(0.15, 0.80, 0.20, 1)
      status.tooltipText = name .. " detected."
    else
      status:SetColorTexture(0.90, 0.15, 0.15, 1)
      status.tooltipText = (name or info.key) .. " not detected (no handshake)."
    end
    status:SetDesaturated(false)
    status:Show()
    holder.tooltipText = info.key .. " voice pack"
  end

  holder:SetScript("OnShow", refresh)
  refresh()
  table.insert(refreshers, refresh)

  holder:EnableMouse(true)
  holder:SetScript("OnEnter", function(self)
    GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
    GameTooltip:SetText(holder.tooltipText or info.key)
    GameTooltip:AddLine(status.tooltipText or "", 1, 1, 1, true)
    GameTooltip:Show()
  end)
  holder:SetScript("OnLeave", function() GameTooltip:Hide() end)
end

-- ===========================
-- Sayaad (nouvel onglet)
-- ===========================
CreateTab(4, "Sayaad")
local sayaad = CreatePage("sayaad")

local sTitle = sayaad:CreateFontString(nil, "OVERLAY", "GameFontNormal")
sTitle:SetPoint("TOPLEFT", 16, -8)
sTitle:SetText("Sayaad Form (applies to both Succubus/Incubus family)")

local function MakeCard(parent, x, iconFile, labelText, valueKey)
  local frame = CreateFrame("Button", nil, parent, "BackdropTemplate")
  frame:SetSize(220, 210)
  frame:SetPoint("TOPLEFT", x, -36)
  frame:SetBackdrop({
    bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background",
    edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
    tile = true, tileSize = 16, edgeSize = 12,
    insets = { left = 4, right = 4, top = 4, bottom = 4 }
  })

  local icon = frame:CreateTexture(nil, "ARTWORK")
  icon:SetSize(96, 96)
  icon:SetPoint("TOP", 0, -16)
  icon:SetTexture(tex(iconFile))

  local label = frame:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
  label:SetPoint("TOP", icon, "BOTTOM", 0, -10)
  label:SetText(labelText)

  local selected = frame:CreateTexture(nil, "OVERLAY")
  selected:SetPoint("TOPLEFT", 6, -6)
  selected:SetPoint("BOTTOMRIGHT", -6, 6)
  selected:SetColorTexture(0, 0.8, 0.2, 0.12) -- léger voile vert quand sélectionné

  frame.valueKey = valueKey
  frame._selectTex = selected
  return frame
end

local cardSucc = MakeCard(sayaad, 16,    "Icon_Succubus_02", "Succubus (female)", "succubus")
local cardIncu = MakeCard(sayaad, 16+240,"Icon_Sayaad_02",   "Incubus (male)",    "incubus")

local function refreshSayaadCards()
  local v = (DB.sayaad_form == "incubus") and "incubus" or "succubus"
  cardSucc._selectTex:SetShown(v == "succubus")
  cardIncu._selectTex:SetShown(v == "incubus")
end

cardSucc:SetScript("OnClick", function()
  DB.sayaad_form = "succubus"
  notifyConfigChanged("sayaad_form")
  refreshSayaadCards()
end)
cardIncu:SetScript("OnClick", function()
  DB.sayaad_form = "incubus"
  notifyConfigChanged("sayaad_form")
  refreshSayaadCards()
end)

refreshSayaadCards()

local sHelp = sayaad:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
sHelp:SetPoint("TOPLEFT", 16, -260)
sHelp:SetWidth(PANEL_WIDTH - 64)
sHelp:SetJustifyH("LEFT")
sHelp:SetText("Tip: Your pet may still be listed by the game as “Succubus/Succube”, but the selected Sayaad form here forces which dialogue pack is used: Succubus or Incubus.")

-- ===========================
-- Donation
-- ===========================
CreateTab(5, "Donation")
local donate = CreatePage("donation")

local dTitle = donate:CreateFontString(nil, "OVERLAY", "GameFontNormal")
dTitle:SetPoint("TOPLEFT", 16, -8)
dTitle:SetText("Support & Downloads")

local line = donate:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
line:SetPoint("TOPLEFT", dTitle, "BOTTOMLEFT", 0, -8)
line:SetWidth(PANEL_WIDTH - 64)
line:SetJustifyH("LEFT")
line:SetText("Thanks for using Sleek RP - Warlock Pets! If you'd like to support development or grab my other addon, use the links below (click a button to copy the URL).")

local LINKS = {
  { label = "Donate (Ko-fi)", url = "https://ko-fi.com/spadawan" },
  { label = "Donate (PayPal)", url = "https://www.paypal.com/paypalme/SimonPdv" },
  { label = "Sleek Combat Text on CurseForge", url = "https://www.curseforge.com/wow/addons/sleekcombattext" },
}

local bx, by = 16, -64
for i, item in ipairs(LINKS) do
  local b = CreateFrame("Button", nil, donate, "UIPanelButtonTemplate")
  b:SetSize(280, 24)
  b:SetPoint("TOPLEFT", bx, by - (i-1)*30)
  b:SetText(item.label)
  b:SetScript("OnClick", function() ShowCopyPopup(item.label, item.url) end)
end

-- ===========================
-- Navigation
-- ===========================
for i = 1, 5 do
  tabs[i]:SetScript("OnClick", function() ShowTab(i) end)
end
ShowTab(1)

function SRPWL_Options_Open()
  if not main:IsShown() then main:Show() end
  main:SetScale(DB.global_scale or 1.0)
end
function SRPWL_Options_Toggle()
  if main:IsShown() then main:Hide() else SRPWL_Options_Open() end
end

SLASH_SRPWL1 = "/sleekrp"
SLASH_SRPWL2 = "/srpwl"
SlashCmdList["SRPWL"] = function(_) SRPWL_Options_Toggle() end

local initFrame = CreateFrame("Frame")
initFrame:RegisterEvent("ADDON_LOADED")
initFrame:RegisterEvent("PLAYER_LOGIN")
initFrame:SetScript("OnEvent", function(self, event, arg1)
  if event == "ADDON_LOADED" and arg1 == ADDON_NAME then
    initDefaults()
  elseif event == "PLAYER_LOGIN" then
    registerAddonCompartment()
  end
end)
