local AddOnName, nsVars = ...
local ss = nsVars.SS

local CreateFrame, CreateTexture, getglobal, UIParent, ReloadUI = CreateFrame, CreateTexture, getglobal, UIParent, ReloadUI
local UIDropDownMenu_SetSelectedID, UIDropDownMenu_SetText, ipairs, unpack = UIDropDownMenu_SetSelectedID, UIDropDownMenu_SetText, ipairs, unpack
local ColorPickerFrame, OpacitySliderFrame, pairs, table = ColorPickerFrame, OpacitySliderFrame, pairs, table
local UIDropDownMenu_AddButton, strlower, CloseDropDownMenus, UIDropDownMenu_SetSelectedValue = UIDropDownMenu_AddButton, strlower, CloseDropDownMenus, UIDropDownMenu_SetSelectedValue
local UIDropDownMenu_Initialize, UIDropDownMenu_JustifyText = UIDropDownMenu_Initialize, UIDropDownMenu_JustifyText
local type, InCombatLockdown = type, InCombatLockdown

local itemCol = 1
local itemRow = 1

local function createDropdown(menu)
  local dropdown = CreateFrame("Button", menu.name, menu.parent, "UIDropDownMenuTemplate")
  dropdown:SetSize(menu.len, menu.width)
  dropdown:SetPoint(menu.anchor, menu.x, menu.y)
  UIDropDownMenu_Initialize(dropdown, menu.init)
  UIDropDownMenu_JustifyText(dropdown, menu.tAlign)

  return dropdown
end

local function createSliderField(sliderConf, sliderEditBoxConf)
  local slider = CreateFrame("Slider",sliderConf.name,sliderConf.parent, "OptionsSliderTemplate")
  slider:SetPoint(sliderConf.anchor,sliderConf.x,sliderConf.y)
  slider:SetSize(sliderConf.len, sliderConf.width)
  slider:SetScript("OnValueChanged", sliderConf.onChanged)

  if sliderConf.values then
    getglobal(slider:GetName().."Text"):SetText(sliderConf.values.label)
    getglobal(slider:GetName().."High"):SetText(sliderConf.values.high)
    getglobal(slider:GetName().."Low"):SetText(sliderConf.values.low)
    slider:SetMinMaxValues(sliderConf.values.low, sliderConf.values.high)
    slider:SetValueStep(sliderConf.values.step)
    slider:SetValue(sliderConf.values.value)
  end

  -- Add the glow scale slider edit box
  local sliderEditBox = CreateFrame("EditBox",sliderConf.name.."EditBox",slider, "InputBoxTemplate")
  sliderEditBox:SetSize(50, 10)
  sliderEditBox:SetPoint("BOTTOMRIGHT", 0, 35)
  sliderEditBox:SetMaxLetters(sliderEditBoxConf.maxLetters)
  sliderEditBox:SetText(slider:GetValue())
  sliderEditBox:SetAutoFocus(false)
  sliderEditBox:SetScript("OnEnterPressed", sliderEditBoxConf.onEnterPressed)

  return slider, sliderEditBox
end

local function getItemPos()
  if itemCol == 1 then
    itemCol = itemCol + 1

    if itemRow == 1 then
      return "TOPLEFT", 26, -281
  elseif itemRow == 2 then
      return "TOPLEFT", 26, -319
  elseif itemRow == 3 then
      return "TOPLEFT", 26, -357
  elseif itemRow == 4 then
      return "TOPLEFT", 26, -395
  elseif itemRow == 5 then
      return "TOPLEFT", 26, -435
    end
  elseif itemCol == 2 then
    local row = itemRow
    itemCol = itemCol - 1
    itemRow = itemRow + 1

    if row == 1 then
      return "TOPLEFT", 200, -281
    elseif row == 2 then
      return "TOPLEFT", 200, -319
    elseif row == 3 then
      return "TOPLEFT", 200, -357
    elseif row == 4 then
      return "TOPLEFT", 200, -395
    elseif row == 5 then
      return "TOPLEFT", 200, -435
    end
  end
  return "CENTER", 0, 0
end

local function createCheckbox(name, text, parent, checked, onClick)
  ss.Config.buttonFrame[name] = CreateFrame("CheckButton",name,parent, "UICheckButtonTemplate")
  ss.Config.buttonFrame[name]:SetPoint(getItemPos())
  ss.Config.buttonFrame[name]:SetChecked(checked)
  getglobal(name.."Text"):SetText(text)
  ss.Config.buttonFrame[name]:SetScript("OnClick", onClick)
end

ss["Config"] = ss["Config"] or {
};

function ss:InitializeConfigPanel()
  -- Create the config frame home
  ss.Config = CreateFrame("Frame","SeamoreSpheresConfig",UIParent)
  ss.Config:SetPoint("CENTER",0,0)
  ss.Config:SetHeight(500)
  ss.Config:SetWidth(400)

  ss.Config.createDropdown = createDropdown
  ss.Config.createSliderField = createSliderField

  ss.Config:SetScript("OnHide", function(self)
    ss.ConfigPreview:Hide()
    ss.ConfigProfile:Hide()
    ss.ConfigMicroSpheres:Hide()
  end)

  ss:MakeFrameMovable(ss.Config)
  ss.Config:SetUserPlaced(true)

  -- Add the background
  ss.Config:SetBackdrop({
    bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background-Dark",
    edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Border",
    tile = true,
    tileSize = 32,
    edgeSize = 32,
    insets = {
      left = 11,
      right = 12,
      top = 12,
      bottom = 11
    },
  });

  -- Add the title
  ss.Config.fontLayer1 = CreateFrame("Frame", "ConfigFontLayer1", ss.Config)
  ss.Config.fontLayer1:SetAllPoints(ss.Config)

  ss.Config.fontLayer1.FontString1 = ss.Config.fontLayer1:CreateFontString("FontString1", "ARTWORK", "NumberFontNormalHuge")
  ss.Config.fontLayer1.FontString1:SetFont(ss.private.font["general"], 42)
  ss.Config.fontLayer1.FontString1:SetPoint("TOP",0,-20)
  ss.Config.fontLayer1.FontString1:SetSize(262, 57)
  ss.Config.fontLayer1.FontString1:SetTextColor(1,0,0,1)
  ss.Config.fontLayer1.FontString1:SetText("Seamore Spheres")
  ss.Config.fontLayer1.FontString1:SetJustifyV("TOP")

  ss.Config.fontLayer1.FontString3 = ss.Config.fontLayer1:CreateFontString("$parenttext", "ARTWORK", "GameFontNormalSmall")
  ss.Config.fontLayer1.FontString3:SetPoint("LEFT",-317,209, "RIGHT")

  -- Add the button container
  ss.Config.buttonFrame = CreateFrame("Frame",nil,ss.Config)
  ss.Config.buttonFrame:SetAllPoints(ss.Config)

  -- Add the power sphere button and event handlers
  ss.Config.buttonFrame.ProfileButton = CreateFrame("Button","ProfileButton",ss.Config.buttonFrame)
  ss.Config.buttonFrame.ProfileButton:SetSize(85,27)
  ss.Config.buttonFrame.ProfileButton:SetPoint("TOP",0,-60)

  ss.Config.buttonFrame.ProfileButton.fontLayer = CreateFrame("Frame","ProfileButtonFontLayer",ss.Config.buttonFrame.ProfileButton)
  ss.Config.buttonFrame.ProfileButton.fontLayer:SetAllPoints(ss.Config.buttonFrame.ProfileButton)

  ss.Config.buttonFrame.ProfileButton.fontLayer.FontString = ss.Config.buttonFrame.ProfileButton.fontLayer:CreateFontString(nil, "ARTWORK", "BossEmoteNormalHuge")
  ss.Config.buttonFrame.ProfileButton.fontLayer.FontString:SetFont(ss.private.font["general"], 26)
  ss.Config.buttonFrame.ProfileButton.fontLayer.FontString:SetPoint("CENTER",0,0)

  ss.Config.buttonFrame.ProfileButton.fontLayer.FontString:SetTextColor(0, 0, 1, 1)
  ss.Config.buttonFrame.ProfileButton.fontLayer.FontString:SetText("Profile Settings")
  ss.Config.buttonFrame.ProfileButton.fontLayer.FontString:SetJustifyV("TOP")

  ss.Config.buttonFrame.ProfileButton:SetScript("OnLoad", function(self)
    if self then
      self:RegisterForClicks("LeftButtonUp")
    else
      self:Hide()
    end
  end)

  ss.Config.buttonFrame.ProfileButton:SetScript("OnEnter", function(self)
    local r,g,b,a = self.fontLayer.FontString:GetTextColor()
    self.fontLayer.FontString:SetTextColor(1,1,1,a)
  end)

  ss.Config.buttonFrame.ProfileButton:SetScript("OnLeave", function(self)
    self.fontLayer.FontString:SetTextColor(0, 0, 1, 1)
  end)

  ss.Config.buttonFrame.ProfileButton:SetScript("OnMouseDown", function(self)
    local r,g,b,a = self.fontLayer.FontString:GetTextColor()
    self.fontLayer.FontString:SetTextColor(r,g,b,a/2)
  end)

  ss.Config.buttonFrame.ProfileButton:SetScript("OnMouseUp", function(self)
    local r,g,b,a = self.fontLayer.FontString:GetTextColor()
    self.fontLayer.FontString:SetTextColor(r,g,b,a*2)
  end)

  ss.Config.buttonFrame.ProfileButton:SetScript("OnClick", function()
    ss.Config:OpenProfilePanel()
  end)

  -- Add preview sphere select dropdown
  ss.Config.previewFontLayer = CreateFrame("Frame", "PreviewFontLayer", ss.Config)
  ss.Config.previewFontLayer:SetAllPoints(ss.Config)

  ss.Config.previewFontLayer.PreviewSphereLabel = ss.Config.previewFontLayer:CreateFontString("PreviewSphereLabel")
  ss.Config.previewFontLayer.PreviewSphereLabel:SetFont(ss.private.font["general"], 19)
  ss.Config.previewFontLayer.PreviewSphereLabel:SetPoint("TOPLEFT",25,-100)
  ss.Config.previewFontLayer.PreviewSphereLabel:SetSize(181, 39)
  ss.Config.previewFontLayer.PreviewSphereLabel:SetTextColor(0,1,0,1)
  ss.Config.previewFontLayer.PreviewSphereLabel:SetText("Preview Sphere:")
  ss.Config.previewFontLayer.PreviewSphereLabel:SetJustifyV("TOP")

  ss.Config.previewSphereList = {}

  ss.Config.PreviewDropDown = ss.Config.createDropdown{
    name = "PreviewDropDown",
    parent = ss.Config,
    tAlign = "LEFT",
    len = 400,
    width = 50,
    anchor = "TOPLEFT",
    x = 200,
    y = -100,
    init = function(self, level)
      local stuff = {}

      for k,v in pairs(ss.Config.previewSphereList) do
        stuff = {}
        stuff.text = v[1]
        stuff.value = v[1]
        stuff.notCheckable = true

        stuff.func = function(self)
          if self:GetText() ~= "Select Sphere" then
            UIDropDownMenu_SetText(ss.Config.PreviewDropDown, v[1])
            ss.Config:PreviewSphere(self:GetText(), k, v[2] .. "SphereOptionsDropDown")
            CloseDropDownMenus()
          end
        end

        UIDropDownMenu_AddButton(stuff, level)
      end
    end,
  };

  ss.Config.PreviewDropDown:SetScript("OnShow", function()
    UIDropDownMenu_SetText(ss.Config.PreviewDropDown, "Select Sphere")
  end)

  -- Add micro sphere group select dropdown
  ss.Config.microSphereSettingsFontLayer = CreateFrame("Frame", "MicroSphereSettingsFontLayer", ss.Config)
  ss.Config.microSphereSettingsFontLayer:SetAllPoints(ss.Config)

  ss.Config.microSphereSettingsFontLayer.MicroSphereSettingsLabel = ss.Config.microSphereSettingsFontLayer:CreateFontString("MicroSphereSettingsLabel")
  ss.Config.microSphereSettingsFontLayer.MicroSphereSettingsLabel:SetFont(ss.private.font["general"], 19)
  ss.Config.microSphereSettingsFontLayer.MicroSphereSettingsLabel:SetPoint("TOPLEFT",25,-135)
  ss.Config.microSphereSettingsFontLayer.MicroSphereSettingsLabel:SetSize(181, 39)
  ss.Config.microSphereSettingsFontLayer.MicroSphereSettingsLabel:SetTextColor(0,1,0,1)
  ss.Config.microSphereSettingsFontLayer.MicroSphereSettingsLabel:SetText("Micro Sphere Settings:")
  ss.Config.microSphereSettingsFontLayer.MicroSphereSettingsLabel:SetJustifyV("TOP")

  ss.Config.MicroSphereSettingsDropDown = ss.Config.createDropdown{
    name = "MicroSphereSettingsDropDown",
    parent = ss.Config,
    tAlign = "LEFT",
    len = 400,
    width = 50,
    anchor = "TOPLEFT",
    x = 200,
    y = -130,
    init = function(self, level, menuList)
      local stuff = {}
      local microGroups = ss.MicroSphereData.getGroupList()

      if level == 1 then
        for k,v in pairs(microGroups) do
          if type(v) == "table" then
            stuff.text = k
            stuff.menuList = k
            stuff.checked = ss.ConfigMicroSpheres.selectedMicroGroup[1] == k and not ss.ConfigMicroSpheres.region
            stuff.hasArrow = true
          else
            stuff.text = v
            stuff.checked = ss.ConfigMicroSpheres.selectedMicroGroup[1] == v and not ss.ConfigMicroSpheres.region
            stuff.func = function(self)
              if self:GetText() ~= "Select Group" then
                UIDropDownMenu_SetText(ss.Config.MicroSphereSettingsDropDown, self:GetText())
                UIDropDownMenu_SetText(ss.Config.SecondaryMicroSphereSettingsDropDown, "Select Group")
                ss.ConfigMicroSpheres.selectedMicroGroup = {v}

                local microResource = ss.MicroSphereData.get() or {}
                microResource =  table.copy(microResource[strlower(ss.curSpecName)] or {}, true)
                ss.Config:ConfigureMicroSphereGroup(v, microResource)

                CloseDropDownMenus()
              end
            end
          end

          UIDropDownMenu_AddButton(stuff, level)
        end
      elseif level == 2 then
        for k,v in pairs(microGroups[menuList]) do
          stuff.text = v
          stuff.value = k
          stuff.checked = ss.ConfigMicroSpheres.selectedMicroGroup[1] == menuList and ss.ConfigMicroSpheres.selectedMicroGroup[2] == k and not ss.ConfigMicroSpheres.region

          stuff.func = function(self)
            if self:GetText() ~= "Select Group" then
              UIDropDownMenu_SetText(ss.Config.MicroSphereSettingsDropDown, menuList .. " - " .. self:GetText())
              UIDropDownMenu_SetText(ss.Config.SecondaryMicroSphereSettingsDropDown, "Select Group")
              ss.ConfigMicroSpheres.selectedMicroGroup = {v, strlower(menuList)}

              local microResource = ss.MicroSphereData.get() or {}
              microResource =  table.copy(microResource[strlower(ss.curSpecName)], true)
              microResource = microResource and microResource[strlower(menuList)] or {}
              ss.Config:ConfigureMicroSphereGroup(v, microResource)

              CloseDropDownMenus()
            end
          end

          UIDropDownMenu_AddButton(stuff, level)
        end
      end
    end,
  };

  -- Add micro sphere group select dropdown
  ss.Config.secondaryMicroSphereSettingsFontLayer = CreateFrame("Frame", "SecondaryMicroSphereSettingsFontLayer", ss.Config)
  ss.Config.secondaryMicroSphereSettingsFontLayer:SetAllPoints(ss.Config)

  ss.Config.secondaryMicroSphereSettingsFontLayer.SecondaryMicroSphereSettingsLabel = ss.Config.secondaryMicroSphereSettingsFontLayer:CreateFontString("SecondaryMicroSphereSettingsLabel")
  ss.Config.secondaryMicroSphereSettingsFontLayer.SecondaryMicroSphereSettingsLabel:SetFont(ss.private.font["general"], 19)
  ss.Config.secondaryMicroSphereSettingsFontLayer.SecondaryMicroSphereSettingsLabel:SetPoint("TOPLEFT",25,-165)
  ss.Config.secondaryMicroSphereSettingsFontLayer.SecondaryMicroSphereSettingsLabel:SetSize(181, 39)
  ss.Config.secondaryMicroSphereSettingsFontLayer.SecondaryMicroSphereSettingsLabel:SetTextColor(0,1,0,1)
  ss.Config.secondaryMicroSphereSettingsFontLayer.SecondaryMicroSphereSettingsLabel:SetText("Secondary Micro Sphere Settings:")
  ss.Config.secondaryMicroSphereSettingsFontLayer.SecondaryMicroSphereSettingsLabel:SetJustifyV("TOP")

  ss.Config.SecondaryMicroSphereSettingsDropDown = ss.Config.createDropdown{
    name = "SecondaryMicroSphereSettingsDropDown",
    parent = ss.Config,
    tAlign = "LEFT",
    len = 400,
    width = 50,
    anchor = "TOPLEFT",
    x = 200,
    y = -160,
    init = function(self, level, menuList)
      local stuff = {}
      local microGroups = ss.MicroSphereData.getGroupList("secondary")

      if level == 1 then
        for k,v in pairs(microGroups) do
          if type(v) == "table" then
            stuff.text = k
            stuff.menuList = k
            stuff.checked = ss.ConfigMicroSpheres.selectedMicroGroup[1] == k and ss.ConfigMicroSpheres.region == "secondary"
            stuff.hasArrow = true
          else
            stuff.text = v
            stuff.checked = ss.ConfigMicroSpheres.selectedMicroGroup[1] == v and ss.ConfigMicroSpheres.region == "secondary"
            stuff.func = function(self)
              if self:GetText() ~= "Select Group" then
                UIDropDownMenu_SetText(ss.Config.MicroSphereSettingsDropDown, "Select Group")
                UIDropDownMenu_SetText(ss.Config.SecondaryMicroSphereSettingsDropDown, self:GetText())
                ss.ConfigMicroSpheres.selectedMicroGroup = {v}

                local microResource = ss.MicroSphereData.getSecondary() or {}
                microResource =  table.copy(microResource[strlower(ss.curSpecName)] or {}, true)
                ss.Config:ConfigureMicroSphereGroup(v, microResource, "secondary")

                CloseDropDownMenus()
              end
            end
          end

          UIDropDownMenu_AddButton(stuff, level)
        end
      elseif level == 2 then
        for k,v in pairs(microGroups[menuList]) do
          stuff.text = v
          stuff.value = k
          stuff.checked = ss.ConfigMicroSpheres.selectedMicroGroup[1] == menuList and ss.ConfigMicroSpheres.selectedMicroGroup[2] == k and ss.ConfigMicroSpheres.region == "secondary"

          stuff.func = function(self)
            if self:GetText() ~= "Select Group" then
              UIDropDownMenu_SetText(ss.Config.MicroSphereSettingsDropDown, "Select Group")
              UIDropDownMenu_SetText(ss.Config.SecondaryMicroSphereSettingsDropDown, menuList .. " - " .. self:GetText())
              ss.ConfigMicroSpheres.selectedMicroGroup = {v, strlower(menuList)}

              local microResource = ss.MicroSphereData.getSecondary() or {}
              microResource =  table.copy(microResource[strlower(ss.curSpecName)], true)
              microResource = microResource and microResource[strlower(menuList)] or {}
              ss.Config:ConfigureMicroSphereGroup(v, microResource, "secondary")

              CloseDropDownMenus()
            end
          end

          UIDropDownMenu_AddButton(stuff, level)
        end
      end
    end,
  };

  -- Add the close button and click event
  ss.Config.buttonFrame.CloseButton = CreateFrame("Button","CloseButton",ss.Config.buttonFrame, "UIPanelButtonTemplate")
  ss.Config.buttonFrame.CloseButton:SetSize(75,23)
  ss.Config.buttonFrame.CloseButton:SetPoint("BOTTOM",5,10)
  ss.Config.buttonFrame.CloseButton:SetText("Close")

  ss.Config.buttonFrame.CloseButton:SetScript("OnMouseUp", function(self)
    ss:ToggleConfig()
  end)

  -- Add the track combat check button and click event
  createCheckbox("TrackCombatCheckButton", "Track Combat", ss.Config.buttonFrame, ss.global.track.combat, function(self)
    if not self:GetChecked() and ss.Layout:InCombat() then
      ss.Layout:EndCombat()
    end

    ss.global.track.combat = self:GetChecked()

    if self:GetChecked() and ss.Layout:InCombat() then
      ss.Layout:StartCombat()
    end
  end)

  -- Add the show artwork check button and click event
  createCheckbox("ShowArtworkCheckButton", "Show Artwork", ss.Config.buttonFrame, ss.global.show.artwork, function(self)
    ss.Layout:ShowArtwork(self:GetChecked())
    ss.global.general.showArtwork = self:GetChecked()
  end)

  -- Add the show player frame check button and click event
  createCheckbox("ShowBlizzPlayerFrameCheckButton", "Use Player Frame", ss.Config.buttonFrame, ss.global.show.playerFrame, function(self)
    ss.global.general["showPlayerFrame"] = self:GetChecked()
    ReloadUI()
  end)

  -- Add the smooth animate check button and click event
  createCheckbox("AnimateSphereValuesCheckButton", "Smooth Animate", ss.Config.buttonFrame, ss.global.general.smoothing, function(self)
    ss.global.general["smoothing"] = self:GetChecked()
  end)

  -- Add the use pet sphere check button and click event
  createCheckbox("UsePetSphereCheckButton", "Use Pet Sphere", ss.Config.buttonFrame, ss.db.track["pet"], function(self)
    ss.db.track["pet"] = self:GetChecked()
    ss.Layout:TrackPet(self:GetChecked())
  end)

  -- Add the use power tracker check button and click event
  createCheckbox("UsePowerTrackerCheckButton", "Use Power Tracker", ss.Config.buttonFrame, ss.db.track["additionalResource"], function(self)
    ss.db.track["additionalResource"] = self:GetChecked()
    ss.Layout:TrackAdditionalResource(self:GetChecked())
  end)

  -- Add the global scale slider
  ss.Config.buttonFrame.SSScaleSlider, ss.Config.buttonFrame.SSScaleSliderEditBox = ss.Config.createSliderField({
    name = "SS32ScaleSlider",
    parent = ss.Config.buttonFrame,
    len = 220,
    width = 16,
    anchor = "Top",
    x = 0,
    y = -245,
    values = {
      label = "Global Scale",
      high = 150,
      low = 50,
      step = 1,
      value = ss.global.general.scale,
    },
    onChanged = function(self)
      ss.global.general["scale"] = self:GetValue()
--      ss.Layout:SetGlobalScale(self:GetValue())
    end,
  },{
    maxLetters = 5,
    onEnterPressed = function(self)
      local val = self:GetText()
      if tonumber(val) then
        self:GetParent():SetValue(val)
        self:SetText(self:GetParent():GetValue())
        self:ClearFocus()
      end
    end,
  });

  function ss.Config:UpdateXMLText()
    local configName = ss.ConfigPreview.buttonFrame.xmlSphereDisplayFrame2.sphere:Get("configName")
    configName = configName == "vehicle" and "health" or configName
    configName = configName == "vehicleResource" and "mainResource" or configName

    if configName and ss.Layout.spheres[configName] then
      local text = ss.Layout.spheres[configName]:getText()
      local text2 = ss.Layout.spheres[configName]:getText2()

      ss.ConfigPreview.buttonFrame.xmlSphereDisplayFrame2.sphere:setText(text)
      ss.ConfigPreview.buttonFrame.xmlSphereDisplayFrame2.sphere:setText2(text2)
    else
      ss.ConfigPreview.buttonFrame.xmlSphereDisplayFrame2.sphere:setText("")
      ss.ConfigPreview.buttonFrame.xmlSphereDisplayFrame2.sphere:setText2("")
    end
  end

  function ss.Config:FillXMLTemplate(frame)
    frame.sphere = ss.Sphere:New()
    frame.sphere:initialize(ss.db.health,frame,"preview")
    frame:SetScale(1.5)
  end

  function ss.Config:UpdateXMLTextures()
    if ss.ConfigPreview.buttonFrame.xmlSphereDisplayFrame2.sphere:getFillColor()[2] then
      ss.ConfigPreview.sliderTargets.Filling = {
        "Color1",
        "Color2",
      };
    else
      ss.ConfigPreview.sliderTargets.Filling = {
        "Color",
      };
    end

    -- set rotaion and fill texture dropdoown
    if ss.ConfigPreview.RotationTexturesDropDown then
      UIDropDownMenu_SetText(ss.ConfigPreview.RotationTexturesDropDown,ss.db[ss.ConfigPreview.buttonFrame.xmlSphereDisplayFrame2.sphere:Get("configName")].animation.id) -- loads from db
    end

    -- Fix default value for fill texture dropdown
    if ss.ConfigPreview.FillTexturesDropDown and not ss.ConfigPreview.buttonFrame.xmlSphereDisplayFrame2.sphere:getFillColor()[2]then
      local mode = ss.profile.modeInfo[ss.ConfigPreview.buttonFrame.xmlSphereDisplayFrame2.sphere:Get("configName")].mode
      local modeSpec = ss.profile.modeInfo[ss.ConfigPreview.buttonFrame.xmlSphereDisplayFrame2.sphere:Get("configName")].modeSpec
      local connfigName = ss.ConfigPreview.buttonFrame.xmlSphereDisplayFrame2.sphere:Get("configName")
      local text = ss.db[connfigName].modes[modeSpec][mode].fillInfo["fillId"] == 1 and "moon" or ss.db[connfigName].modes[modeSpec][mode].fillInfo["fillId"]

      UIDropDownMenu_SetSelectedValue(ss.ConfigPreview.FillTexturesDropDown, text)
      UIDropDownMenu_SetText(ss.ConfigPreview.FillTexturesDropDown, text) -- loads from db
      ss.ConfigPreview.FillTexturesDropDown:Show();
      ss.ConfigPreview.fontLayer1.FontString2:Show()
    else
      ss.ConfigPreview.FillTexturesDropDown:Hide();
      ss.ConfigPreview.fontLayer1.FontString2:Hide()
    end

    if ss.ConfigPreview.TextFormattingDropdown then
      --set the selected value appropriately
      local textFormat = ss.db[ss.ConfigPreview.buttonFrame.xmlSphereDisplayFrame2.sphere:Get("configName")].textFormat

      if textFormat == "truncated" then
        textFormat = "Truncate Value"
      elseif textFormat == "commaSeparated" then
        textFormat = "Comma Separated Value"
      else
        textFormat = "Raw Value"
      end

      UIDropDownMenu_SetSelectedValue(ss.ConfigPreview.TextFormattingDropdown, textFormat)
      UIDropDownMenu_SetText(ss.ConfigPreview.TextFormattingDropdown, textFormat) -- loads from db
    end

    ss.ConfigPreview.buttonFrame.SSSpherePercentageCheckBox:SetChecked(ss.db[ss.ConfigPreview.buttonFrame.xmlSphereDisplayFrame2.sphere:Get("configName")].font[1].show)
    ss.ConfigPreview.buttonFrame.SSSphereValueCheckBox:SetChecked(ss.db[ss.ConfigPreview.buttonFrame.xmlSphereDisplayFrame2.sphere:Get("configName")].font[2].show)
  end

  function ss.Config:OpenProfilePanel()
    if ss.ConfigPreview:IsVisible() then
      ss.ConfigPreview:Hide()
      ss.ConfigPreview.HealthSphereOptionsDropDown:Hide()
      ss.ConfigPreview.VehicleSphereOptionsDropDown:Hide()
      ss.ConfigPreview.VehicleResourceSphereOptionsDropDown:Hide()
      ss.ConfigPreview.MainResourceSphereOptionsDropDown:Hide()
      ss.ConfigPreview.AdditionalResourceSphereOptionsDropDown:Hide()
      ss.ConfigPreview.PetSphereOptionsDropDown:Hide()
    end

    if ss.ConfigMicroSpheres:IsVisible() then
      ss.ConfigMicroSpheres:Hide()
    end

    if ss.ConfigProfile:IsVisible() then
      ss.ConfigProfile:Hide()
    else
      UIDropDownMenu_SetSelectedValue(ss.ConfigProfile.ProfileToUseDropDown, ss.profile.profileName)
      UIDropDownMenu_SetText(ss.ConfigProfile.ProfileToUseDropDown, "Select Profile")
      UIDropDownMenu_SetText(ss.ConfigProfile.CopyProfileDropDown, "Select Profile")
      UIDropDownMenu_SetText(ss.ConfigProfile.DeleteProfileDropDown, "Select Profile")
      ss.ConfigProfile:Show()
    end
  end

  function ss.Config:PreviewSphere(label, dbConfig, optionsDropdown)
    if ss.ConfigProfile:IsVisible() then
      ss.ConfigProfile:Hide()
    end

    if ss.ConfigMicroSpheres:IsVisible() then
      ss.ConfigMicroSpheres:Hide()
    end

    if not ss.ConfigPreview:IsVisible() or (ss.ConfigPreview:IsVisible() and ss.ConfigPreview.titleLayer.Title:GetText() ~= label) then
      ss.ConfigPreview.buttonFrame.xmlSphereDisplayFrame2.sphere:setResource(ss.db[dbConfig])
      ss.Config:UpdateXMLTextures()
      ss.Config:UpdateXMLText()
      ss.ConfigPreview.titleLayer.Title:SetText(label)
      dbConfig = dbConfig == "vehicle" and "health" or dbConfig
      dbConfig = dbConfig == "vehicleResource" and "mainResource" or dbConfig

      ss.ConfigPreview.titleLayer.Title:SetTextColor(ss.private.config[dbConfig.."SphereButton"].color.r, ss.private.config[dbConfig.."SphereButton"].color.g, ss.private.config[dbConfig.."SphereButton"].color.b, ss.private.config[dbConfig.."SphereButton"].color.a)

      ss.ConfigPreview:Show()
      ss.ConfigPreview.SSTargetSlider:Hide()
      UIDropDownMenu_SetText(ss.ConfigPreview.SliderTargetDropDown, "Configure Sphere")
      UIDropDownMenu_SetSelectedValue(ss.ConfigPreview[optionsDropdown], "default")
      UIDropDownMenu_SetText(ss.ConfigPreview[optionsDropdown], "default")

      ss.ConfigPreview.HealthSphereOptionsDropDown:Hide()
      ss.ConfigPreview.VehicleSphereOptionsDropDown:Hide()
      ss.ConfigPreview.VehicleResourceSphereOptionsDropDown:Hide()
      ss.ConfigPreview.MainResourceSphereOptionsDropDown:Hide()
      ss.ConfigPreview.AdditionalResourceSphereOptionsDropDown:Hide()
      ss.ConfigPreview.PetSphereOptionsDropDown:Hide()
      ss.ConfigPreview[optionsDropdown]:Show()
    end
  end

  function ss.Config:ConfigureMicroSphereGroup(group, microResource, region)
    if ss.ConfigPreview:IsVisible() then
      ss.ConfigPreview:Hide()
      ss.ConfigPreview.HealthSphereOptionsDropDown:Hide()
      ss.ConfigPreview.VehicleSphereOptionsDropDown:Hide()
      ss.ConfigPreview.VehicleResourceSphereOptionsDropDown:Hide()
      ss.ConfigPreview.MainResourceSphereOptionsDropDown:Hide()
      ss.ConfigPreview.AdditionalResourceSphereOptionsDropDown:Hide()
      ss.ConfigPreview.PetSphereOptionsDropDown:Hide()
    end

    if ss.ConfigProfile:IsVisible() then
      ss.ConfigProfile:Hide()
    end

    local regionLabel = region and region == "secondary" and "Secondary " or ""
    local fillTextureIndex = (region and region == "secondary") and 2 or 1
    ss.ConfigMicroSpheres.fontLayer1.Title:SetText(regionLabel .. "Micro Sphere " .. group .. " Settings")
    ss.ConfigMicroSpheres.selectedTexture = ss.profile.microResourceFillTextures[fillTextureIndex]
    UIDropDownMenu_SetText(ss.ConfigMicroSpheres.ResourceRemoveDropDown, "Select Resource")
    UIDropDownMenu_SetText(ss.ConfigMicroSpheres.ResourceAddDropDown, "Select Resource")
    UIDropDownMenu_SetText(ss.ConfigMicroSpheres.ResourceTypeDropDown, "Select Resource Type")
    UIDropDownMenu_SetText(ss.ConfigMicroSpheres.backgroundDropDown, ss.ConfigMicroSpheres.selectedTexture)
    ss.ConfigMicroSpheres.resourceOptionList = nil
    ss.ConfigMicroSpheres.region = region

    local groupIndex = group == "Group 1" and 1 or 2

    if microResource and not microResource.getMinMax and not microResource.buffGroup then
      microResource = (microResource[groupIndex] and (microResource[groupIndex].buffGroup or microResource[groupIndex].getMinMax)) and microResource[groupIndex] or {}
    elseif microResource then
      microResource = groupIndex == 1 and microResource or {}
    end

    ss.ConfigMicroSpheres.recources = microResource
    ss.ConfigMicroSpheres:Show()
  end

  self:InitializeConfigPreviewPanel()
  self:InitializeConfigProfilePanel()
  self:InitializeConfigMicroSpheresPanel()
  self:ToggleConfig()
end
