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

local function WarnMissingPriceProvider()
  if not (WF and WF.Price and WF.Price.WarnIfConfiguredProviderUnavailable) then
    return
  end

  -- Do a couple delayed checks so load-on-demand addons have time to initialize.
  if C_Timer and C_Timer.After then
    C_Timer.After(1, function()
      if WF and WF.Price then
        WF.Price:WarnIfConfiguredProviderUnavailable(false)
      end
    end)

    C_Timer.After(5, function()
      if WF and WF.Price then
        WF.Price:WarnIfConfiguredProviderUnavailable(false)
      end
    end)

    return
  end

  WF.Price:WarnIfConfiguredProviderUnavailable(false)
end

WF.Events:On("ADDON_LOADED", function(_, name)
  if name ~= ADDON_NAME then
    return
  end

  WF.DB:Init()

  -- If we were tracking when the UI reloaded, restore the active session.
  if WF.Tracker and WF.Tracker.ResumeFromReload then
    WF.Tracker:ResumeFromReload()
  end

  -- Persist the active session on /reload so recording survives.
  WF.Events:On("PLAYER_LOGOUT", function()
    if WF.Tracker and WF.Tracker._PersistActiveSession then
      WF.Tracker:_PersistActiveSession()
    end
  end)

  -- LootAppraiser-style warning: if your selected price source addon isn't enabled, tell you.
  WF.Events:On("PLAYER_LOGIN", function()
    WarnMissingPriceProvider()
  end)

  if WF.UI and WF.UI.Main and WF.UI.Main.Create then
    WF.UI.Main:Create()

    -- Re-open the main window after /reload if it was open previously.
    local open = false
    if WF.DB and WF.DB.GetSetting then
      open = WF.DB:GetSetting("mainWindowOpen") and true or false
    end

    if open and WF.UI.Main.Show then
      WF.UI.Main:Show()
    else
      WF.UI.Main:Hide()
    end
  end

  if WF.UI and WF.UI.Help and WF.UI.Help.Create then
    WF.UI.Help:Create()
    if WF.UI.Help.frame then
      WF.UI.Help.frame:Hide()
    end
  end

  if WF.UI and WF.UI.Minimap and WF.UI.Minimap.Create then
    WF.UI.Minimap:Create()
  end
end)

SLASH_WHATFARM1 = "/wf"
SLASH_WHATFARM2 = "/whatfarm"

SlashCmdList["WHATFARM"] = function(msg)
  local rawMsg = tostring(msg or "")
  local lowerMsg = rawMsg:lower()

  if lowerMsg == "help" or lowerMsg == "settings" then
    WF.UI.Help:Show("Overview")
    return
  end

  if lowerMsg == "history" then
    WF.UI.Help:Show("History")
    return
  end

  if lowerMsg == "farms" then
    WF.UI.Help:Show("Farms")
    return
  end

  local scrambleRest = rawMsg:match("^[Ss][Cc][Rr][Aa][Mm][Bb][Ll][Ee][Ff][Rr][Ii][Ee][Nn][Dd][Ss]%s*(.-)$")
    or rawMsg:match("^[Ff][Rr][Ii][Ee][Nn][Dd][Ss][Ss][Cc][Rr][Aa][Mm][Bb][Ll][Ee]%s*(.-)$")
    or rawMsg:match("^[Ff][Ss][Cc][Rr][Aa][Mm][Bb][Ll][Ee]%s*(.-)$")

  if scrambleRest ~= nil and WF.Util and WF.Util.FriendsScrambler then
    local cmd = tostring(scrambleRest or ""):gsub("^%s+", ""):gsub("%s+$", ""):lower()
    if cmd == "on" or cmd == "1" or cmd == "true" then
      WF.Util.FriendsScrambler:SetEnabled(true)
    elseif cmd == "off" or cmd == "0" or cmd == "false" then
      WF.Util.FriendsScrambler:SetEnabled(false)
    else
      WF.Util.FriendsScrambler:Toggle()
    end
    return
  end

  if lowerMsg == "import" then
    if WF and WF.Share and WF.Share.ShowShareDialog then
      WF.Share:ShowShareDialog(nil)
      return
    end
  end

  local importPayload = rawMsg:match("^[Ii][Mm][Pp][Oo][Rr][Tt]%s+(.+)$")
  if importPayload then
    if WF and WF.Share and WF.Share.ShowShareDialog then
      WF.Share:ShowShareDialog(nil, importPayload)
      return
    end
  end

  local compRest = rawMsg:match("^[Cc][Oo][Mm][Pp]%s+(.+)$")
  if compRest and WF and WF.UI and WF.UI.Main then
    local sub, rest = compRest:match("^(%S+)%s*(.-)$")
    sub = tostring(sub or ""):lower()
    rest = tostring(rest or "")

    if sub == "invite" then
      if WF.UI.Main.InviteChallenge then
        WF.UI.Main:InviteChallenge(rest)
        return
      end
    elseif sub == "join" then
      local sid, tail = rest:match("^(%S+)%s*(.-)$")
      local host, password = "", ""
      tail = tostring(tail or ""):gsub("^%s+", ""):gsub("%s+$", "")
      local atHost, atPassword = tail:match("^@%s*(%S+)%s*(%S*)%s*$")
      if atHost then
        host, password = atHost, atPassword or ""
      else
        local pwBeforeHost, hostAfter = tail:match("^(%S+)%s*@%s*(.+)$")
        if hostAfter then
          host, password = hostAfter, pwBeforeHost or ""
        else
          password = tail
        end
      end
      if WF.UI.Main.JoinCompetitiveSession then
        WF.UI.Main:JoinCompetitiveSession(sid or "", host or "", password or "")
        return
      end
    elseif sub == "load" then
      if WF.UI.Main.LoadCompetitiveSession then
        WF.UI.Main:LoadCompetitiveSession()
        return
      end
    elseif sub == "start" then
      if WF.UI.Main.StartChallenge then
        WF.UI.Main:StartChallenge()
        return
      end
    elseif sub == "pause" or sub == "resume" then
      if WF.UI.Main.ToggleCompetitivePause then
        WF.UI.Main:ToggleCompetitivePause()
        return
      end
    elseif sub == "leave" or sub == "quit" or sub == "end" then
      if WF.UI.Main.QuitCompetitiveMatch then
        WF.UI.Main:QuitCompetitiveMatch()
        return
      end
    end
  end

  WF.UI.Main:Toggle()
end
