local _, ns = ...

ns.regions = {
    US = {
        enUS = [[
kilrogg winterhoof proudmoore kiljaeden tichondrius silverhand thoriumbrotherhood
farstriders eitrigg shuhalo alleria exodar medivh khadgar hellscream gorefiend
spinebreaker zangarmarsh wildhammer eredar blackhand galakrond whisperwind dentarg
illidan stormreaver stormrage zuljin durotan ysera bloodhoof duskwood elune
laughingskull auchindoun chogall gilneas arthas warsong gorgonnash theforgottencoast
balnazzar alteracmountains undermine anvilmar bleedinghollow argentdawn thescryers
sargeras azgalor thunderlord destromath bloodfurnace mannoroth nazjatar azshara
magtheridon anetheron ysondre altarofstorms dragonmaw uldum akama korialstrasz
eldrethalas mugthol antonidas silvermoon skywall terenas hydraxis drakthul boreantundra
moknathal shadowsong eonar skullcrusher guldan zuluhed ursin andorhal blackdragonflight
velen scilla llane arygos earthenring malygos garona lightningsblade icecrown onyxia
burningblade aggramar fizzcrank suramar windrunner darrowmere draka dragonblight fenris
draenor echoisles bronzebeard shandris feathermoon scarletcrusade darkspear azjolnerub
muradin nordrassil blackrock khazmodan shadowcouncil sistersofelune cenarioncircle
blackwaterraiders firetree draktharon rivendare vashj spirestone malorne frostwolf
stormscale runetotem uther detheroc dethecus lethon blackwinglair shadowmoon haomarush
kalecgos shatteredhalls executus deathwing darkiron shatteredhand coilfang demonsoul
dalvengyr greymane tanaris staghelm dawnbringer madoran azuremyst emeralddream maelstrom
twistingnether lightninghoof theventureco ravenholdt alexstrasza terokkar kirintor
steamwheedlecartel sentinels ravencrest uldaman agamaggan kargath burninglegion
thunderhorn theunderbog bladesedge archimonde norgannon jaedenar aegwynn gurubashi
bonechewer hakkar garrosh daggerspine chromaggus nathrezim smolderthorn anubarak arathor
garithos drenden crushridge kultiras bladefist rexxar misha cairne cenarius frostmane
tortheldrin nerzhul korgath perenolde wyrmrestaccord trollbane grizzlyhills malfurion
lothar kaelthas gnomeregan moonrunner ghostlands veknilash nazgrel nesingwary senjin
dunemaul maiev bloodscalp queldorei boulderfist stonemaul baelgun doomhammer aeriepeak
hyjal moonguard area52 thrall dalaran malganis turalyon kelthuzad lightbringer
caelestrasz nagrand saurfang barthilas frostmourne dreadmaul thaurissan jubeithos
gundrak khazgoroth amanthul dathremar
]],
        esMX = [[
drakkari ragnaros quelthalas
]],
        ptBR = [[
goldrinn nemesis tolbarad azralon gallywix
]],
    },
    EU = {
        frFR = [[
garona sargeras nerzhul voljin chantséternels arakarahm rashgarroth kaelthas
throkferoth uldaman drekthar krasus eitrigg confrérieduthorium lacroisadeécarlate
cultedelarivenoire lessentinelles kirintor lesclairvoyants conseildesombres archimonde
elune varimathras suramar medivh ysondre hyjal marécagedezangar chogall eldrethalas
sinstralis dalaran naxxramas arathi illidan templenoir khazmodan
]],
        deDE = [[
dethecus theradras onyxia mugthol terrordar lothar baelgun azshara kragjin arthas
blutkessel wrathbringer durotan kelthuzad veklor tirion blackmoore tichondrius lordaeron
blackrock thrall kargath ambossar nefarian gilneas destromath ulduar mannoroth
gorgonnash nerathor ysera malorne malygos malfurion rexxar alleria anetheron kiljaeden
rajaxx festungderstürme guldan nathrezim nazjatar zuluhed dalvengyr amanthul
frostmourne anubarak diearguswacht dieewigewacht dietodeskrallen dassyndikat
derabyssischerat kultderverdammten daskonsortium diesilbernehand ungoro senjin area52
garrosh shattrath nozdormu perenolde teldrassil todeswache zirkeldescenarius
dermithrilorden forscherliga derratvondalaran dienachtwache arygos khazgoroth norgannon
dunmorogh diealdor aegwynn antonidas echsenkessel blackhand malganis taerar eredar
nethersturm alexstrasza madmortem proudmoore frostwolf
]],
        enGB = [[
korgall executus shatteredhand bloodfeather terokkar saurfang darkspear burningsteppes
khadgar bloodhoof kultiras alonsus anachronos dentarg tarrenmill moonglade
steamwheedlecartel theshatar emeriss twilightshammer bloodscalp crushridge agamaggan
hakkar drakthul burningblade scarshieldlegion sporeggar earthenring defiasbrotherhood
ravenholdt darkmoonfaire theventureco outland grimbatol frostmane kazzak
chamberofaspects wildhammer thunderhorn aggramar hellscream ravencrest lightbringer
mazrigos bronzedragonflight nordrassil quelthalas azjolnerub turalyon doomhammer draenor
bladesedge eonar veknilash aeriepeak bronzebeard azuremyst stormrage hellfire runetotem
arathor kilrogg nagrand karazhan dragonblight themaelstrom ghostlands lightningsblade
deathwing auchindoun dunemaul sylvanas jaedenar shatteredhalls chromaggus sunstrider
balnazzar talnivarr ahnqiraj daggerspine laughingskull trollbane boulderfist stormscale
terenas emeralddream silvermoon spinebreaker dragonmaw vashj stormreaver haomarush
genjuros zenedar bladefist neptulon frostwhisper darksorrow shadowsong aszune
twistingnether magtheridon ragnaros argentdawn alakir skullcrusher xavius burninglegion
]],
        ptPT = [[
aggraportuguês
]],
        itIT = [[
pozzodelleternità nemesis
]],
        esES = [[
dunmodr cthun zuljin uldum sanguino shendralar tyrande loserrantes colinaspardas exodar
minahonda
]],
        ruRU = [[
ревущийфьорд гордунни свежевательдуш
вечнаяпесня черныйшрам пиратскаябухта
борейскаятундра ткачсмерти гром термоштепсель
подземье галакронд разувий голдринн седогрив
корольлич азурегос дракономор ясеневыйлес
стражсмерти
]],
    },
    KR = {
        koKR = [[
azshara durotan burninglegion stormrage windrunner alexstrasza rexxar deathwing
wildhammer zuljin guldan malfurion dalaran norgannon garona hellscream hyjal cenarius
]],
    },
    TW = {
        zhTW = [[
shadowmoon icecrown chillwindpoint spirestone arthas zealotblade hellscream whisperwind
queldorei dragonmaw bleedinghollow worldtree stormscale arygos frostmane menethil
nightsong orderofthecloudserpent skywall wrathbringer lightshope demonfallcanyon
sundownmarsh crystalpinestinger silverwinghold krolblade oldblanchy
]],
    },
}

local lookup

local function Realms()
    if lookup then return lookup end

    local region = ns.regions[GetCurrentRegionName() or ""]
    if not region then return nil end -- too early to tell, ask again later

    lookup = {}
    for locale, slugs in pairs(region) do
        for slug in slugs:gmatch("%S+") do
            lookup[slug] = locale
        end
    end

    ns.regions = nil
    return lookup
end

local function FoldUpper(lead, trail)
    local b = trail:byte()

    if lead == "\208" then
        if b >= 0x90 and b <= 0x9F then return lead .. string.char(b + 0x20) end -- А-П
        if b >= 0xA0 and b <= 0xAF then return "\209" .. string.char(b - 0x20) end -- Р-Я
        if b == 0x81 then return "\209\145" end -- Ё
    elseif lead == "\195" and b >= 0x80 and b <= 0x9E and b ~= 0x97 then -- À-Þ, not ×
        return lead .. string.char(b + 0x20)
    end
end

---@param realm string
---@return string
function ns.RealmSlug(realm)
    realm = realm:gsub("([\195\208\209])([\128-\191])", FoldUpper)
    return (realm:gsub("[%s'%-]", "")):lower()
end

---@param realm string
---@return string|nil
function ns.RealmLocale(realm)
    local realms = Realms()
    return realms and realms[ns.RealmSlug(realm)]
end

---@param realm string
---@return string|nil
function ns.RealmLanguage(realm)
    local locale = ns.RealmLocale(realm)
    return locale and ns.L["lang_" .. locale]
end

---@param realm string
---@return string|nil
function ns.RealmFlag(realm)
    local locale = ns.RealmLocale(realm)
    return locale and ("|TInterface/AddOns/BetterTooltip/Media/" .. locale .. "_flag:10:18|t ")
end
