local addonName, BM = ...

BM.Locales = {
    en = {
        title = "BetterMailbox",
        subtitle = "Premium-Postfach für schnelleres Looten und Senden",
        subtitle = "Premium inbox panel for faster looting and mailing",
        inbox = "Inbox",
        send = "Send",
        mails = "MAILS",
        lootable = "LOOTABLE",
        attached_gold = "ATTACHED GOLD",
        item = "ITEM",
        item_subject = "ITEM       SUBJECT",
        gold = "GOLD",
        expires = "EXPIRES",
        sender = "SENDER",
        no_mails = "No mails in inbox",
        no_mails_sub = "Your inbox is clean. New deliveries will appear here.",
        compose_status = "Compose a new message",
        indexed_single = "1 message indexed",
        indexed_multi = "%d messages indexed",
        attached_item = "Attached item",
        contains_gold = "Contains attached gold",
        letter_only = "Letter only",
        no_subject = "(No subject)",
        recipient = "RECIPIENT",
        subject = "SUBJECT",
        message = "MESSAGE",
        attachments = "ATTACHMENTS",
        send_hint = "Write your mail here and use the attachment slots below for items.",
        send_mail = "Send Mail",
        sending = "Sending...",
        sent_success = "Mail sent successfully",
        sent_fail = "Mail could not be sent",
        recipient_required = "Recipient is required",
        sending_status = "Sending mail...",
        take_all = "Take All",
        take_gold = "Take Gold",
        take_selected = "Take Selected",
        refresh = "Refresh",
        collecting = "Collecting...",
        refreshing = "Refreshing inbox...",
        selected_mail_ready = "Selected message ready to collect",
        selected_mail_empty = "The selected message has nothing to collect",
        skin = "SKIN",
        language = "LANGUAGE",
        options = "Options",
        ui_scale = "UI SCALE",
        font_size = "FONT SIZE",
        guild = "Guild",
        friends = "Friends",
        search = "Search",
        recent = "Recent",
        no_results = "No matching recipients found.",
    },
    de = {
        subtitle = "Premium-Postfach für schnelleres Looten und Senden",
        title = "BetterMailbox",
        subtitle = "Premium-Postfach für schnelleres Looten und Senden",
        inbox = "Posteingang",
        send = "Senden",
        mails = "POST",
        lootable = "LOOTBAR",
        attached_gold = "ANGEHÄNGTES GOLD",
        item = "ITEM",
        item_subject = "ITEM       BETREFF",
        gold = "GOLD",
        expires = "LÄUFT AB",
        sender = "ABSENDER",
        no_mails = "Keine Post im Briefkasten",
        no_mails_sub = "Dein Briefkasten ist leer. Neue Sendungen erscheinen hier.",
        compose_status = "Neue Nachricht verfassen",
        indexed_single = "1 Nachricht erfasst",
        indexed_multi = "%d Nachrichten erfasst",
        attached_item = "Angehängter Gegenstand",
        contains_gold = "Enthält angehängtes Gold",
        letter_only = "Nur Brief",
        no_subject = "(Kein Betreff)",
        recipient = "EMPFÄNGER",
        subject = "BETREFF",
        message = "NACHRICHT",
        attachments = "ANHÄNGE",
        send_hint = "Verfasse hier deine Post und nutze unten die Anhang-Slots für Gegenstände.",
        send_mail = "Post senden",
        sending = "Wird gesendet...",
        sent_success = "Post erfolgreich gesendet",
        sent_fail = "Post konnte nicht gesendet werden",
        recipient_required = "Empfänger wird benötigt",
        sending_status = "Post wird gesendet...",
        take_all = "Alles nehmen",
        take_gold = "Gold nehmen",
        take_selected = "Auswahl nehmen",
        refresh = "Aktualisieren",
        collecting = "Sammle...",
        refreshing = "Postfach wird aktualisiert...",
        selected_mail_ready = "Ausgewaehlte Nachricht kann jetzt entnommen werden",
        selected_mail_empty = "In der ausgewaehlten Nachricht ist nichts zum Entnehmen",
        skin = "SKIN",
        language = "SPRACHE",
        options = "Optionen",
        ui_scale = "UI-SKALIERUNG",
        font_size = "SCHRIFTGRÖSSE",
        guild = "Gilde",
        friends = "Freunde",
        search = "Suchen",
        recent = "Zuletzt benutzt",
        no_results = "Keine passenden Empfänger gefunden.",
    },
    ru = {
        title = "BetterMailbox",
        subtitle = "Премиум-почта для быстрого сбора и отправки",
        inbox = "Входящие",
        send = "Отправить",
        mails = "ПИСЬМА",
        lootable = "ДОБЫЧА",
        attached_gold = "ПРИЛОЖЕННОЕ ЗОЛОТО",
        item_subject = "ПРЕДМЕТ / ТЕМА",
        gold = "ЗОЛОТО",
        expires = "ИСТЕКАЕТ",
        sender = "ОТПРАВИТЕЛЬ",
        no_mails = "Во входящих нет писем",
        no_mails_sub = "Ваш ящик пуст. Новые письма появятся здесь.",
        compose_status = "Создать новое письмо",
        indexed_single = "1 письмо загружено",
        indexed_multi = "%d писем загружено",
        attached_item = "Прикрепленный предмет",
        contains_gold = "Содержит приложенное золото",
        letter_only = "Только письмо",
        no_subject = "(Без темы)",
        recipient = "ПОЛУЧАТЕЛЬ",
        subject = "ТЕМА",
        message = "СООБЩЕНИЕ",
        attachments = "ВЛОЖЕНИЯ",
        send_hint = "Пишите письмо здесь и используйте слоты ниже для предметов.",
        send_mail = "Отправить письмо",
        sending = "Отправка...",
        sent_success = "Письмо успешно отправлено",
        sent_fail = "Не удалось отправить письмо",
        recipient_required = "Нужно указать получателя",
        sending_status = "Отправка письма...",
        take_all = "Забрать всё",
        take_gold = "Забрать золото",
        refresh = "Обновить",
        collecting = "Сбор...",
        refreshing = "Обновление почты...",
        language = "ЯЗЫК",
        options = "Настройки",
        ui_scale = "МАСШТАБ UI",
        font_size = "РАЗМЕР ШРИФТА",
        guild = "Гильдия",
        friends = "Друзья",
        search = "Поиск",
        recent = "Недавние",
        no_results = "Подходящие получатели не найдены.",
    },
    fr = {
        title = "BetterMailbox",
        subtitle = "Boîte aux lettres premium pour récupérer et envoyer plus vite",
        inbox = "Boîte de réception",
        send = "Envoyer",
        mails = "COURRIERS",
        lootable = "BUTIN",
        attached_gold = "OR JOINT",
        item_subject = "OBJET / SUJET",
        gold = "OR",
        expires = "EXPIRE",
        sender = "EXPÉDITEUR",
        no_mails = "Aucun courrier dans la boîte",
        no_mails_sub = "Votre boîte est vide. Les nouveaux courriers apparaîtront ici.",
        compose_status = "Rédiger un nouveau courrier",
        indexed_single = "1 courrier chargé",
        indexed_multi = "%d courriers chargés",
        attached_item = "Objet joint",
        contains_gold = "Contient de l'or",
        letter_only = "Lettre seule",
        no_subject = "(Sans sujet)",
        recipient = "DESTINATAIRE",
        subject = "SUJET",
        message = "MESSAGE",
        attachments = "PIÈCES JOINTES",
        send_hint = "Rédigez votre courrier ici et utilisez les emplacements ci-dessous pour les objets.",
        send_mail = "Envoyer",
        sending = "Envoi...",
        sent_success = "Courrier envoyé",
        sent_fail = "Échec de l'envoi",
        recipient_required = "Destinataire requis",
        sending_status = "Envoi du courrier...",
        take_all = "Tout prendre",
        take_gold = "Prendre l'or",
        refresh = "Rafraîchir",
        collecting = "Collecte...",
        refreshing = "Actualisation du courrier...",
        language = "LANGUE",
        options = "Options",
        ui_scale = "ÉCHELLE UI",
        font_size = "TAILLE DE POLICE",
        guild = "Guilde",
        friends = "Amis",
        search = "Rechercher",
        recent = "Récent",
        no_results = "Aucun destinataire correspondant.",
    },
}

BM.LanguageOrder = { "de", "en", "ru", "fr" }

function BM:GetLocale()
    local db = BetterMailboxDB or {}
    local lang = db.language or "en"
    return BM.Locales[lang] and lang or "en"
end

function BM:L(key, ...)
    local lang = BM:GetLocale()
    local locale = BM.Locales[lang] or BM.Locales.en
    local fallback = BM.Locales.en
    local text = locale[key] or fallback[key] or key
    if select("#", ...) > 0 then
        return string.format(text, ...)
    end
    return text
end

function BM:GetLanguageDisplay(lang)
    local names = {
        de = "Deutsch",
        en = "English",
        ru = "Русский",
        fr = "Français",
    }
    return names[lang] or string.upper(lang or "en")
end

function BM:SetLanguage(lang)
    BetterMailboxDB = BetterMailboxDB or {}
    BetterMailboxDB.language = BM.Locales[lang] and lang or "en"
    if BM.UpdateTexts then
        BM:UpdateTexts()
    end
    if BM.RefreshInbox then
        BM:RefreshInbox()
    end
end

function BM:CycleLanguage()
    local current = BM:GetLocale()
    local index = 1
    for i, lang in ipairs(BM.LanguageOrder) do
        if lang == current then
            index = i
            break
        end
    end
    local nextIndex = index + 1
    if nextIndex > #BM.LanguageOrder then
        nextIndex = 1
    end
    BM:SetLanguage(BM.LanguageOrder[nextIndex])
end
