-- parameters.lua
local _, ns = ...
local UI = {}
ns.UI = UI

local E, L, V, P, G = unpack(ElvUI or {})

local MODES = {
  ["words-only"] = "Переводить только слова",
  ["phrases-first"] = "Фразы первыми",
  ["transparent"] = "Без перевода"
}
local LANGS = { "en", "ru" }
local LOGLEVELS = { "info", "debug", "warn"}


-- Показываем окно с кнопкой "Перезагрузить UI"
local function ShowReloadPopup()
    StaticPopupDialogs["MYADDON_RELOADUI"] = {
        text = "Для применения изменений требуется перезагрузка интерфейса.",
        button1 = "Перезагрузить UI",
        button2 = "Позже",
        OnAccept = function() ReloadUI() end,
        timeout = 0,
        whileDead = true,
        hideOnEscape = true,
        preferredIndex = 3,
    }
    StaticPopup_Show("MYADDON_RELOADUI")
end

function UI:Init()
  print("Init UI Settings Frame")

  local S = nil

  if E then 
    S = E:GetModule("Skins")
  end

  local panel = CreateFrame("Frame")
  panel.name = "Magic Translator"

  local title = panel:CreateFontString(nil, "ARTWORK", "GameFontNormalLarge")
  title:SetPoint("TOPLEFT", 16, -16)
  title:SetText("Magic Translator")

  -- Enable
  local cb = CreateFrame("CheckButton", nil, panel, "InterfaceOptionsCheckButtonTemplate")
  cb:SetPoint("TOPLEFT", title, "BOTTOMLEFT", 0, -16)
  cb.Text:SetText(" Включить перевод")
  cb:SetChecked(MagicTranslatorDB.enabled)
  cb:SetScript("OnClick", function(self) MagicTranslatorDB.enabled = self:GetChecked() end)

  if S then
    -- Применить стиль ElvUI
    S:HandleCheckBox(cb)
  end

  -- Mode dropdown
  local modeDD = CreateFrame("Frame", nil, panel, "UIDropDownMenuTemplate")
  modeDD:SetPoint("TOPLEFT", cb, "BOTTOMLEFT", -16, -26)
  local modeLabel = panel:CreateFontString(nil, "ARTWORK", "GameFontNormal")
  modeLabel:SetPoint("LEFT", modeDD, "LEFT", 16, 26)
  modeLabel:SetText("Режим")

  UIDropDownMenu_Initialize(modeDD, function(self, level)
    for key, mode_label in pairs(MODES) do
      local info = UIDropDownMenu_CreateInfo()
      info.text = mode_label
      info.value = key
      info.func = function()
        MagicTranslatorDB.mode = key
        UIDropDownMenu_SetText(modeDD, mode_label)
      end
      info.checked = (MagicTranslatorDB.mode == key)
      UIDropDownMenu_AddButton(info, level)
    end
  end)
  UIDropDownMenu_SetText(modeDD, MODES[MagicTranslatorDB.mode])

  -- Language selectors (src/dst)
  local srcDD = CreateFrame("Frame", nil, panel, "UIDropDownMenuTemplate")
  srcDD:SetPoint("TOPLEFT", modeDD, "BOTTOMLEFT", 0, -26)
  local srcLabel = panel:CreateFontString(nil, "ARTWORK", "GameFontNormal")
  srcLabel:SetPoint("LEFT", srcDD, "LEFT", 16, 26)
  srcLabel:SetText("Источник (src)")

  UIDropDownMenu_Initialize(srcDD, function(self, level)
    for _, l in ipairs(LANGS) do
      local info = UIDropDownMenu_CreateInfo()
      info.text = l
      info.func = function()
        MagicTranslatorDB.src = l
        UIDropDownMenu_SetText(srcDD, l)
        ns.Dictionary:BuildIndex(MagicTranslatorDB.src, MagicTranslatorDB.dst)
      end
      info.checked = (MagicTranslatorDB.src == l)
      UIDropDownMenu_AddButton(info, level)
    end
  end)
  UIDropDownMenu_SetText(srcDD, MagicTranslatorDB.src)

  local dstDD = CreateFrame("Frame", nil, panel, "UIDropDownMenuTemplate")
  dstDD:SetPoint("TOPLEFT", srcDD, "BOTTOMLEFT", 0, -26)
  local dstLabel = panel:CreateFontString(nil, "ARTWORK", "GameFontNormal")
  dstLabel:SetPoint("LEFT", dstDD, "LEFT", 16, 26)
  dstLabel:SetText("Назначение (dst)")

  UIDropDownMenu_Initialize(dstDD, function(self, level)
    for _, l in ipairs(LANGS) do
      local info = UIDropDownMenu_CreateInfo()
      info.text = l
      info.func = function()
        MagicTranslatorDB.dst = l
        UIDropDownMenu_SetText(dstDD, l)
        ns.Dictionary:BuildIndex(MagicTranslatorDB.src, MagicTranslatorDB.dst)
      end
      info.checked = (MagicTranslatorDB.dst == l)
      UIDropDownMenu_AddButton(info, level)
    end
  end)
  UIDropDownMenu_SetText(dstDD, MagicTranslatorDB.dst)


  local levelDD = CreateFrame("Frame", nil, panel, "UIDropDownMenuTemplate")
  levelDD:SetPoint("TOPLEFT", dstDD, "BOTTOMLEFT", 0, -26)
  local levelLabel = panel:CreateFontString(nil, "ARTWORK", "GameFontNormal")
  levelLabel:SetPoint("LEFT", levelDD, "LEFT", 16, 26)
  levelLabel:SetText("Уроверь логов")

  UIDropDownMenu_Initialize(levelDD, function(self, level)
    for _, l in ipairs(LOGLEVELS) do
      local info = UIDropDownMenu_CreateInfo()
      info.text = l
      info.func = function()
        MagicTranslatorDB.logLevel = l
        UIDropDownMenu_SetText(levelDD, l)
      end
      info.checked = (MagicTranslatorDB.logLevel == l)
      UIDropDownMenu_AddButton(info, level)
    end
  end)
  UIDropDownMenu_SetText(levelDD, MagicTranslatorDB.logLevel)


  -- Enable
  local cbMorph = CreateFrame("CheckButton", nil, panel, "InterfaceOptionsCheckButtonTemplate")
  cbMorph:SetPoint("TOPLEFT", levelDD, "BOTTOMLEFT", 16, -16)
  cbMorph.Text:SetText(" Морфологический анализ")
  cbMorph:SetChecked(MagicTranslatorDB.useMorphologicalAnalysis)
  cbMorph:SetScript("OnClick", function(self) MagicTranslatorDB.useMorphologicalAnalysis = self:GetChecked() end)

  if S then
    -- Применить стиль ElvUI
    S:HandleCheckBox(cbMorph)
  end

  -- Enable
  local cShowCyrlicInfo = CreateFrame("CheckButton", nil, panel, "InterfaceOptionsCheckButtonTemplate")
  cShowCyrlicInfo:SetPoint("TOPLEFT", cbMorph, "BOTTOMLEFT", 0, -16)
  cShowCyrlicInfo.Text:SetText(" Показывать информационный текст для русских фраз (Кирилица)")
  cShowCyrlicInfo:SetChecked(MagicTranslatorDB.showCyrlicInfo)
  cShowCyrlicInfo:SetScript("OnClick", function(self) MagicTranslatorDB.showCyrlicInfo = self:GetChecked() end)

  if S then
    -- Применить стиль ElvUI
    S:HandleCheckBox(cShowCyrlicInfo)
  end

  -- Status
  local status = panel:CreateFontString(nil, "ARTWORK", "GameFontHighlightSmall")
  status:SetPoint("TOPLEFT", cShowCyrlicInfo, "BOTTOMLEFT", 0, -16)
  status:SetText("Статус: словарь загружен")


  -- local buttonCleanMissing = CreateFrame("Frame", "MyAddonFrame", UIParent)
  -- frame:SetSize(120, 40)
  -- frame:SetPoint("CENTER") -- позиция на экране

  local buttonCleanMissing = CreateFrame("Button", nil, panel, "UIPanelButtonTemplate")
  buttonCleanMissing:SetPoint("TOPLEFT", status, "BOTTOMLEFT", 0, -26)
  buttonCleanMissing:SetSize(300, 40)
  buttonCleanMissing:SetText("Очистисть журнал непереведенных слов")
  buttonCleanMissing:SetPoint("CENTER")

  buttonCleanMissing:SetScript("OnClick", function()
    MagicTranslatorDB.missing = {}
     ShowReloadPopup()
  end)

  if S then
    -- Применить стиль ElvUI
    S:HandleButton(buttonCleanMissing)
  end

    -- Регистрируем панель
  if Settings and Settings.RegisterAddOnCategory then
      -- Новый API (Retail)
      local category = Settings.RegisterCanvasLayoutCategory(panel, panel.name)
      Settings.RegisterAddOnCategory(category)
  else
      -- Старый API (Classic / старые версии)
      InterfaceOptions_AddCategory(panel)
  end

  print("Initialized UI Settings Frame")
end