local addonName, BM = ...

BM.Locales = {
    en = {
        title = "BetterMailbox",
        subtitle = "Premium inbox panel for faster looting and mailing",
        inbox = "Inbox",
        send = "Send",
        mails = "MAILS",
        lootable = "LOOTABLE",
        attached_gold = "ATTACHED GOLD",
        send_gold = "Send gold",
        item = "ITEM",
        item_subject = "ITEM       SUBJECT",
        gold = "GOLD",
        silver = "SILVER",
        copper = "COPPER",
        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",
        delete = "Delete",
        delete_selected = "Delete Selected",
        deleting = "Deleting...",
        done = "Done",
        delete_selection_empty = "No messages selected for deletion",
        delete_blocked = "Remove attachments or gold before deleting mails",
        delete_done = "Mail deleted",
        delete_done_multi = "%d mails deleted",
        delete_partial = "%d mails deleted, some could not be removed",
        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_face = "FONT",
        font_size = "FONT SIZE",
        guild = "Guild",
        friends = "Friends",
        search = "Search",
        recent = "Recent",
        no_results = "No matching recipients found.",
        back = "Back",
        reply = "Reply",
        reply_prepared = "Reply draft prepared",
        mail_from = "FROM",
        mail_body = "MESSAGE",
        no_mail_text = "This letter has no text.",
        no_attachments = "No attachments on this mail.",
        open_mail_status = "Reading message",
    },
    de = {
        title = "BetterMailbox",
        subtitle = "Premium-Postfach für schnelleres Looten und Senden",
        inbox = "Posteingang",
        send = "Senden",
        mails = "POST",
        lootable = "LOOTBAR",
        attached_gold = "ANGEHÄNGTES GOLD",
        send_gold = "Gold senden",
        item = "ITEM",
        item_subject = "ITEM       BETREFF",
        gold = "GOLD",
        silver = "SILBER",
        copper = "KUPFER",
        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",
        delete = "Löschen",
        delete_selected = "Auswahl löschen",
        deleting = "Lösche...",
        done = "Fertig",
        delete_selection_empty = "Keine Nachrichten zum Löschen ausgewählt",
        delete_blocked = "Entferne zuerst Anhänge oder Gold, bevor du diese Post löschst",
        delete_done = "Post gelöscht",
        delete_done_multi = "%d Nachrichten gelöscht",
        delete_partial = "%d Nachrichten gelöscht, einige konnten nicht entfernt werden",
        refresh = "Aktualisieren",
        collecting = "Sammle...",
        refreshing = "Postfach wird aktualisiert...",
        selected_mail_ready = "Ausgewählte Nachricht kann jetzt entnommen werden",
        selected_mail_empty = "In der ausgewählten Nachricht ist nichts zum Entnehmen",
        skin = "SKIN",
        language = "SPRACHE",
        options = "Optionen",
        ui_scale = "UI-SKALIERUNG",
        font_face = "SCHRIFTART",
        font_size = "SCHRIFTGRÖSSE",
        guild = "Gilde",
        friends = "Freunde",
        search = "Suchen",
        recent = "Zuletzt benutzt",
        no_results = "Keine passenden Empfänger gefunden.",
        back = "Zurück",
        reply = "Antworten",
        reply_prepared = "Antwort wurde vorbereitet",
        mail_from = "VON",
        mail_body = "NACHRICHT",
        no_mail_text = "Dieser Brief hat keinen Text.",
        no_attachments = "Keine Anhänge in diesem Brief.",
        open_mail_status = "Nachricht wird gelesen",
    },
    ru = {
        title = "BetterMailbox",
        subtitle = "Премиум-почта для быстрого сбора и отправки",
        inbox = "Входящие",
        send = "Отправить",
        mails = "ПИСЬМА",
        lootable = "ДОБЫЧА",
        attached_gold = "ПРИЛОЖЕННОЕ ЗОЛОТО",
        send_gold = "Отправить золото",
        item = "ПРЕДМЕТ",
        item_subject = "ПРЕДМЕТ       ТЕМА",
        gold = "ЗОЛОТО",
        silver = "СЕРЕБРО",
        copper = "МЕДЬ",
        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 = "Забрать золото",
        take_selected = "Забрать выбранное",
        delete = "Удалить",
        delete_selected = "Удалить выбранное",
        deleting = "Удаление...",
        done = "Готово",
        delete_selection_empty = "Нет писем, выбранных для удаления",
        delete_blocked = "Сначала заберите вложения или золото, прежде чем удалять письма",
        delete_done = "Письмо удалено",
        delete_done_multi = "Удалено писем: %d",
        delete_partial = "Удалено писем: %d, некоторые удалить не удалось",
        refresh = "Обновить",
        collecting = "Сбор...",
        refreshing = "Обновление почты...",
        selected_mail_ready = "Выбранное письмо готово к получению",
        selected_mail_empty = "В выбранном письме нечего забирать",
        skin = "ТЕМА",
        language = "ЯЗЫК",
        options = "Настройки",
        ui_scale = "МАСШТАБ UI",
        font_face = "ШРИФТ",
        font_size = "РАЗМЕР ШРИФТА",
        guild = "Гильдия",
        friends = "Друзья",
        search = "Поиск",
        recent = "Недавние",
        no_results = "Подходящие получатели не найдены.",
        back = "Назад",
        reply = "Ответить",
        reply_prepared = "Ответ подготовлен",
        mail_from = "ОТ",
        mail_body = "СООБЩЕНИЕ",
        no_mail_text = "В этом письме нет текста.",
        no_attachments = "В этом письме нет вложений.",
        open_mail_status = "Чтение письма",
    },
    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",
        send_gold = "Envoyer de l'or",
        item = "OBJET",
        item_subject = "OBJET       SUJET",
        gold = "OR",
        silver = "ARGENT",
        copper = "CUIVRE",
        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 joint",
        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",
        take_selected = "Prendre la sélection",
        delete = "Supprimer",
        delete_selected = "Supprimer la sélection",
        deleting = "Suppression...",
        done = "Terminé",
        delete_selection_empty = "Aucun courrier sélectionné pour la suppression",
        delete_blocked = "Retirez d'abord les pièces jointes ou l'or avant de supprimer les courriers",
        delete_done = "Courrier supprimé",
        delete_done_multi = "%d courriers supprimés",
        delete_partial = "%d courriers supprimés, certains n'ont pas pu être retirés",
        refresh = "Rafraîchir",
        collecting = "Collecte...",
        refreshing = "Actualisation du courrier...",
        selected_mail_ready = "Le courrier sélectionné est prêt à être récupéré",
        selected_mail_empty = "Le courrier sélectionné ne contient rien à récupérer",
        skin = "APPARENCE",
        language = "LANGUE",
        options = "Options",
        ui_scale = "ÉCHELLE UI",
        font_face = "POLICE",
        font_size = "TAILLE DE POLICE",
        guild = "Guilde",
        friends = "Amis",
        search = "Rechercher",
        recent = "Récent",
        no_results = "Aucun destinataire correspondant.",
        back = "Retour",
        reply = "Répondre",
        reply_prepared = "Réponse préparée",
        mail_from = "DE",
        mail_body = "MESSAGE",
        no_mail_text = "Cette lettre ne contient aucun texte.",
        no_attachments = "Aucune pièce jointe dans ce courrier.",
        open_mail_status = "Lecture du courrier",
    },
}

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
