--[[ In-journal preferences. The locale selector is deliberately explicit: it
     changes only Shiny Hunter and never promises to change the game client. ]]

local _, ns = ...

local OptionsPanel = ns.NewModule("OptionsPanel")
ns.UI = ns.UI or {}
ns.UI.OptionsPanel = OptionsPanel

local Theme = ns.UI.Theme
local LOCALES = { "auto", "enUS", "enGB", "esES", "deDE", "frFR", "itIT", "ptBR" }

local function LocaleName(locale)
    if locale == "auto" then
        return ns.L["OPTIONS_LANGUAGE_AUTO"]:format(ns.Localization:GetClientLocale())
    end
    return ns.L["LOCALE_" .. locale:upper()] or locale
end

function OptionsPanel:Create(parent)
    local panel = { rows = {} }
    local title = parent:CreateFontString(nil, "ARTWORK", "GameFontNormalLarge")
    title:SetPoint("TOPLEFT", parent, "TOPLEFT", 24, -20)
    title:SetTextColor(Theme.color.gold[1], Theme.color.gold[2], Theme.color.gold[3])
    local section = parent:CreateFontString(nil, "ARTWORK", "GameFontNormal")
    section:SetPoint("TOPLEFT", title, "BOTTOMLEFT", 0, -32)
    section:SetTextColor(Theme.color.tracker[1], Theme.color.tracker[2], Theme.color.tracker[3])
    local hint = parent:CreateFontString(nil, "ARTWORK", "GameFontHighlightSmall")
    hint:SetPoint("TOPLEFT", section, "BOTTOMLEFT", 0, -8)
    hint:SetPoint("TOPRIGHT", parent, "TOPRIGHT", -28, -8)
    hint:SetJustifyH("LEFT")
    hint:SetJustifyV("TOP")
    hint:SetWordWrap(true)
    hint:SetTextColor(Theme.color.muted[1], Theme.color.muted[2], Theme.color.muted[3])
    hint:SetHeight(42)
    local active = parent:CreateFontString(nil, "ARTWORK", "GameFontHighlight")
    active:SetPoint("TOPLEFT", hint, "BOTTOMLEFT", 0, -12)
    active:SetTextColor(Theme.color.text[1], Theme.color.text[2], Theme.color.text[3])

    for index, locale in ipairs(LOCALES) do
        local row = CreateFrame("Button", nil, parent, "BackdropTemplate")
        row:SetPoint("TOPLEFT", parent, "TOPLEFT", 24, -156 - (index - 1) * 39)
        row:SetSize(360, 32)
        row:SetNormalFontObject(GameFontNormal)
        row.locale = locale
        row:SetScript("OnClick", function(self)
            ns.Config:Set("language", self.locale)
        end)
        panel.rows[index] = row
    end

    function panel:Refresh()
        local L = ns.L
        title:SetText(L["OPTIONS_TITLE"])
        section:SetText(L["OPTIONS_LANGUAGE_TITLE"])
        hint:SetText(L["OPTIONS_LANGUAGE_HINT"])
        active:SetText(L["OPTIONS_LANGUAGE_ACTIVE"]:format(
            LocaleName(ns.Localization:GetEffectiveLocale())))
        local selected = ns.Config:Get("language") or "auto"
        for _, row in ipairs(self.rows) do
            row:SetText(LocaleName(row.locale))
            Theme:ApplyButton(row, row.locale == selected)
        end
    end
    panel:Refresh()
    return panel
end
