export const languages = ["de", "en", "fr", "es", "it", "nl", "pl", "pt", "ja", "ko", "zh-CN"] as const;
export type Language = typeof languages[number];

export const languageNames: Record<Language, string> = {
  de: "Deutsch", en: "English", fr: "Français", es: "Español", it: "Italiano", nl: "Nederlands",
  pl: "Polski", pt: "Português", ja: "日本語", ko: "한국어", "zh-CN": "简体中文",
};

const en = {
  automaticActive: "Your wallpapers change automatically", automaticPaused: "Automatic rotation is paused",
  settings: "Settings", currentWallpaper: "Current wallpaper", currentImage: "Current image", nextImage: "Next image",
  changeInterval: "Change image", paused: "Paused", selectImages: "Select images", pleaseWait: "Please wait …",
  collection: "My collection", image: "image", images: "images", motif: "Image", noImages: "No images selected yet",
  collectionHint: "Tap the image count to open your gallery.", shuffle: "Shuffle order", lockScreenOnly: "Lock screen only",
  settingsIntro: "Choose how WallpaperFlow works in the background.", language: "Language", noImageLimit: "No image limit",
  privacyInfo: "Your selection stays private on this device. The only limit is the available storage.", home: "Home", back: "Back",
  addImages: "Add images", backToGallery: "Back to gallery", editImage: "Adjust image", savedForImage: "Saved only for this image",
  saveCrop: "Save image crop", myImages: "My images", current: "Current", adjustImage: "Adjust image", deleteImage: "Delete image",
  emptyCollection: "Your collection is empty", emptyCollectionText: "Add images that should rotate automatically on your lock screen.",
  galleryLoading: "Loading gallery …", loadMore: "Load more images", editCrop: "Edit image crop",
  gestureLabel: "Move the image with one finger and zoom with two fingers", cropPreview: "Image crop preview", imageFit: "Image fit",
  fill: "Fill", fit: "Fit", adjustOnScreen: "Adjust directly on screen", gestureHelp: "Drag inside the display or pinch with two fingers",
  zoom: "Zoom", rotate: "Rotate 90°", reset: "Reset", deleteConfirm: "Do you really want to delete this image from your collection?",
  galleryLoadFailed: "The gallery could not be loaded", automaticDisabled: "Automatic rotation is paused", settingSaved: "Setting saved",
  intervalSaved: "Rotation interval saved", androidOnly: "This feature is available on Android", imagesAdded: "Images added to your collection",
  selectionCancelled: "Selection cancelled", imageSelectionAndroid: "Image selection is available on Android", imageDeleted: "Image deleted",
  imageDeleteFailed: "The image could not be deleted", cropSaved: "Image crop saved", cropSaveFailed: "The image crop could not be saved",
  wallpaperUpdated: "Lock screen updated",
} satisfies Record<string, string>;

export type TranslationKey = keyof typeof en;
type Copy = Record<TranslationKey, string>;

const copies: Record<Exclude<Language, "en">, Copy> = {
  de: {
    automaticActive: "Deine Motive wechseln automatisch", automaticPaused: "Automatischer Wechsel ist pausiert",
    settings: "Einstellungen", currentWallpaper: "Aktuelles Hintergrundbild", currentImage: "Aktuelles Motiv", nextImage: "Nächstes Motiv",
    changeInterval: "Bild wechseln", paused: "Pausiert", selectImages: "Bilder auswählen", pleaseWait: "Bitte warten …",
    collection: "Meine Sammlung", image: "Bild", images: "Bilder", motif: "Motiv", noImages: "Noch keine Bilder ausgewählt",
    collectionHint: "Tippe auf die Bildanzahl, um deine Galerie zu öffnen.", shuffle: "Zufällige Reihenfolge", lockScreenOnly: "Nur Sperrbildschirm",
    settingsIntro: "Lege fest, wie WallpaperFlow im Hintergrund arbeitet.", language: "Sprache", noImageLimit: "Ohne Bilderlimit",
    privacyInfo: "Deine Auswahl wird privat auf dem Gerät gespeichert. Die einzige Grenze ist der freie Speicherplatz.", home: "Start", back: "Zurück",
    addImages: "Bilder hinzufügen", backToGallery: "Zurück zur Galerie", editImage: "Bild anpassen", savedForImage: "Wird nur für dieses Bild gespeichert",
    saveCrop: "Bildausschnitt speichern", myImages: "Meine Bilder", current: "Aktuell", adjustImage: "Bild anpassen", deleteImage: "Bild löschen",
    emptyCollection: "Deine Sammlung ist leer", emptyCollectionText: "Füge Bilder hinzu, die automatisch als Sperrbildschirm wechseln sollen.",
    galleryLoading: "Galerie wird geladen …", loadMore: "Weitere Bilder laden", editCrop: "Bildausschnitt bearbeiten",
    gestureLabel: "Bild mit einem Finger verschieben und mit zwei Fingern zoomen", cropPreview: "Vorschau des Bildausschnitts", imageFit: "Bildanpassung",
    fill: "Ausfüllen", fit: "Einpassen", adjustOnScreen: "Direkt im Bildschirm anpassen", gestureHelp: "Im Display ziehen oder mit zwei Fingern zoomen",
    zoom: "Zoom", rotate: "Um 90° drehen", reset: "Zurücksetzen", deleteConfirm: "Möchtest du dieses Bild wirklich aus deiner Sammlung löschen?",
    galleryLoadFailed: "Galerie konnte nicht geladen werden", automaticDisabled: "Automatischer Wechsel pausiert", settingSaved: "Einstellung gespeichert",
    intervalSaved: "Wechselintervall gespeichert", androidOnly: "Diese Funktion ist auf Android verfügbar", imagesAdded: "Bilder wurden zur Sammlung hinzugefügt",
    selectionCancelled: "Auswahl abgebrochen", imageSelectionAndroid: "Bildauswahl ist auf Android verfügbar", imageDeleted: "Bild wurde gelöscht",
    imageDeleteFailed: "Bild konnte nicht gelöscht werden", cropSaved: "Bildausschnitt wurde gespeichert", cropSaveFailed: "Bildausschnitt konnte nicht gespeichert werden",
    wallpaperUpdated: "Sperrbildschirm wurde aktualisiert",
  },
  fr: {
    automaticActive: "Vos fonds d’écran changent automatiquement", automaticPaused: "La rotation automatique est en pause",
    settings: "Paramètres", currentWallpaper: "Fond d’écran actuel", currentImage: "Image actuelle", nextImage: "Image suivante",
    changeInterval: "Changer l’image", paused: "En pause", selectImages: "Sélectionner des images", pleaseWait: "Veuillez patienter…",
    collection: "Ma collection", image: "image", images: "images", motif: "Image", noImages: "Aucune image sélectionnée",
    collectionHint: "Touchez le nombre d’images pour ouvrir votre galerie.", shuffle: "Ordre aléatoire", lockScreenOnly: "Écran de verrouillage uniquement",
    settingsIntro: "Choisissez comment WallpaperFlow fonctionne en arrière-plan.", language: "Langue", noImageLimit: "Aucune limite d’images",
    privacyInfo: "Votre sélection reste privée sur cet appareil. Seul l’espace disponible la limite.", home: "Accueil", back: "Retour",
    addImages: "Ajouter des images", backToGallery: "Retour à la galerie", editImage: "Ajuster l’image", savedForImage: "Enregistré uniquement pour cette image",
    saveCrop: "Enregistrer le cadrage", myImages: "Mes images", current: "Actuelle", adjustImage: "Ajuster l’image", deleteImage: "Supprimer l’image",
    emptyCollection: "Votre collection est vide", emptyCollectionText: "Ajoutez des images à faire défiler automatiquement sur l’écran de verrouillage.",
    galleryLoading: "Chargement de la galerie…", loadMore: "Charger plus d’images", editCrop: "Modifier le cadrage",
    gestureLabel: "Déplacez l’image avec un doigt et zoomez avec deux doigts", cropPreview: "Aperçu du cadrage", imageFit: "Ajustement de l’image",
    fill: "Remplir", fit: "Adapter", adjustOnScreen: "Ajuster directement à l’écran", gestureHelp: "Faites glisser dans l’écran ou pincez avec deux doigts",
    zoom: "Zoom", rotate: "Tourner de 90°", reset: "Réinitialiser", deleteConfirm: "Voulez-vous vraiment supprimer cette image de votre collection ?",
    galleryLoadFailed: "Impossible de charger la galerie", automaticDisabled: "La rotation automatique est en pause", settingSaved: "Paramètre enregistré",
    intervalSaved: "Intervalle enregistré", androidOnly: "Cette fonction est disponible sur Android", imagesAdded: "Images ajoutées à votre collection",
    selectionCancelled: "Sélection annulée", imageSelectionAndroid: "La sélection d’images est disponible sur Android", imageDeleted: "Image supprimée",
    imageDeleteFailed: "Impossible de supprimer l’image", cropSaved: "Cadrage enregistré", cropSaveFailed: "Impossible d’enregistrer le cadrage",
    wallpaperUpdated: "Écran de verrouillage mis à jour",
  },
  es: {
    automaticActive: "Tus fondos cambian automáticamente", automaticPaused: "La rotación automática está en pausa",
    settings: "Ajustes", currentWallpaper: "Fondo actual", currentImage: "Imagen actual", nextImage: "Imagen siguiente",
    changeInterval: "Cambiar imagen", paused: "En pausa", selectImages: "Seleccionar imágenes", pleaseWait: "Espera…",
    collection: "Mi colección", image: "imagen", images: "imágenes", motif: "Imagen", noImages: "Aún no hay imágenes seleccionadas",
    collectionHint: "Toca el número de imágenes para abrir la galería.", shuffle: "Orden aleatorio", lockScreenOnly: "Solo pantalla de bloqueo",
    settingsIntro: "Elige cómo funciona WallpaperFlow en segundo plano.", language: "Idioma", noImageLimit: "Sin límite de imágenes",
    privacyInfo: "Tu selección permanece privada en este dispositivo. El único límite es el espacio disponible.", home: "Inicio", back: "Atrás",
    addImages: "Añadir imágenes", backToGallery: "Volver a la galería", editImage: "Ajustar imagen", savedForImage: "Se guarda solo para esta imagen",
    saveCrop: "Guardar recorte", myImages: "Mis imágenes", current: "Actual", adjustImage: "Ajustar imagen", deleteImage: "Eliminar imagen",
    emptyCollection: "Tu colección está vacía", emptyCollectionText: "Añade imágenes para que cambien automáticamente en la pantalla de bloqueo.",
    galleryLoading: "Cargando galería…", loadMore: "Cargar más imágenes", editCrop: "Editar recorte",
    gestureLabel: "Mueve la imagen con un dedo y amplía con dos", cropPreview: "Vista previa del recorte", imageFit: "Ajuste de imagen",
    fill: "Rellenar", fit: "Encajar", adjustOnScreen: "Ajustar directamente en pantalla", gestureHelp: "Arrastra dentro de la pantalla o pellizca con dos dedos",
    zoom: "Zoom", rotate: "Girar 90°", reset: "Restablecer", deleteConfirm: "¿Quieres eliminar esta imagen de tu colección?",
    galleryLoadFailed: "No se pudo cargar la galería", automaticDisabled: "La rotación automática está en pausa", settingSaved: "Ajuste guardado",
    intervalSaved: "Intervalo guardado", androidOnly: "Esta función está disponible en Android", imagesAdded: "Imágenes añadidas a tu colección",
    selectionCancelled: "Selección cancelada", imageSelectionAndroid: "La selección de imágenes está disponible en Android", imageDeleted: "Imagen eliminada",
    imageDeleteFailed: "No se pudo eliminar la imagen", cropSaved: "Recorte guardado", cropSaveFailed: "No se pudo guardar el recorte",
    wallpaperUpdated: "Pantalla de bloqueo actualizada",
  },
  it: {
    automaticActive: "Gli sfondi cambiano automaticamente", automaticPaused: "La rotazione automatica è in pausa",
    settings: "Impostazioni", currentWallpaper: "Sfondo attuale", currentImage: "Immagine attuale", nextImage: "Immagine successiva",
    changeInterval: "Cambia immagine", paused: "In pausa", selectImages: "Seleziona immagini", pleaseWait: "Attendi…",
    collection: "La mia raccolta", image: "immagine", images: "immagini", motif: "Immagine", noImages: "Nessuna immagine selezionata",
    collectionHint: "Tocca il numero di immagini per aprire la galleria.", shuffle: "Ordine casuale", lockScreenOnly: "Solo schermata di blocco",
    settingsIntro: "Scegli come funziona WallpaperFlow in background.", language: "Lingua", noImageLimit: "Nessun limite di immagini",
    privacyInfo: "La selezione resta privata su questo dispositivo. L’unico limite è lo spazio disponibile.", home: "Home", back: "Indietro",
    addImages: "Aggiungi immagini", backToGallery: "Torna alla galleria", editImage: "Regola immagine", savedForImage: "Salvato solo per questa immagine",
    saveCrop: "Salva ritaglio", myImages: "Le mie immagini", current: "Attuale", adjustImage: "Regola immagine", deleteImage: "Elimina immagine",
    emptyCollection: "La raccolta è vuota", emptyCollectionText: "Aggiungi immagini da alternare automaticamente nella schermata di blocco.",
    galleryLoading: "Caricamento galleria…", loadMore: "Carica altre immagini", editCrop: "Modifica ritaglio",
    gestureLabel: "Sposta l’immagine con un dito e ingrandisci con due", cropPreview: "Anteprima ritaglio", imageFit: "Adattamento immagine",
    fill: "Riempi", fit: "Adatta", adjustOnScreen: "Regola direttamente sullo schermo", gestureHelp: "Trascina nello schermo o pizzica con due dita",
    zoom: "Zoom", rotate: "Ruota di 90°", reset: "Ripristina", deleteConfirm: "Vuoi davvero eliminare questa immagine dalla raccolta?",
    galleryLoadFailed: "Impossibile caricare la galleria", automaticDisabled: "La rotazione automatica è in pausa", settingSaved: "Impostazione salvata",
    intervalSaved: "Intervallo salvato", androidOnly: "Questa funzione è disponibile su Android", imagesAdded: "Immagini aggiunte alla raccolta",
    selectionCancelled: "Selezione annullata", imageSelectionAndroid: "La selezione immagini è disponibile su Android", imageDeleted: "Immagine eliminata",
    imageDeleteFailed: "Impossibile eliminare l’immagine", cropSaved: "Ritaglio salvato", cropSaveFailed: "Impossibile salvare il ritaglio",
    wallpaperUpdated: "Schermata di blocco aggiornata",
  },
  nl: {
    automaticActive: "Je achtergronden wisselen automatisch", automaticPaused: "Automatisch wisselen is gepauzeerd",
    settings: "Instellingen", currentWallpaper: "Huidige achtergrond", currentImage: "Huidige afbeelding", nextImage: "Volgende afbeelding",
    changeInterval: "Afbeelding wisselen", paused: "Gepauzeerd", selectImages: "Afbeeldingen kiezen", pleaseWait: "Even geduld…",
    collection: "Mijn collectie", image: "afbeelding", images: "afbeeldingen", motif: "Afbeelding", noImages: "Nog geen afbeeldingen gekozen",
    collectionHint: "Tik op het aantal afbeeldingen om je galerij te openen.", shuffle: "Willekeurige volgorde", lockScreenOnly: "Alleen vergrendelscherm",
    settingsIntro: "Kies hoe WallpaperFlow op de achtergrond werkt.", language: "Taal", noImageLimit: "Geen afbeeldingslimiet",
    privacyInfo: "Je selectie blijft privé op dit apparaat. Alleen de beschikbare opslagruimte vormt een limiet.", home: "Start", back: "Terug",
    addImages: "Afbeeldingen toevoegen", backToGallery: "Terug naar galerij", editImage: "Afbeelding aanpassen", savedForImage: "Alleen voor deze afbeelding opgeslagen",
    saveCrop: "Uitsnede opslaan", myImages: "Mijn afbeeldingen", current: "Huidig", adjustImage: "Afbeelding aanpassen", deleteImage: "Afbeelding verwijderen",
    emptyCollection: "Je collectie is leeg", emptyCollectionText: "Voeg afbeeldingen toe die automatisch op je vergrendelscherm wisselen.",
    galleryLoading: "Galerij laden…", loadMore: "Meer afbeeldingen laden", editCrop: "Uitsnede bewerken",
    gestureLabel: "Verplaats met één vinger en zoom met twee vingers", cropPreview: "Voorbeeld van uitsnede", imageFit: "Afbeelding passend maken",
    fill: "Vullen", fit: "Passend", adjustOnScreen: "Direct op het scherm aanpassen", gestureHelp: "Sleep in het scherm of knijp met twee vingers",
    zoom: "Zoom", rotate: "90° draaien", reset: "Herstellen", deleteConfirm: "Wil je deze afbeelding echt uit je collectie verwijderen?",
    galleryLoadFailed: "De galerij kon niet worden geladen", automaticDisabled: "Automatisch wisselen is gepauzeerd", settingSaved: "Instelling opgeslagen",
    intervalSaved: "Wisselinterval opgeslagen", androidOnly: "Deze functie is beschikbaar op Android", imagesAdded: "Afbeeldingen aan je collectie toegevoegd",
    selectionCancelled: "Selectie geannuleerd", imageSelectionAndroid: "Afbeeldingen kiezen is beschikbaar op Android", imageDeleted: "Afbeelding verwijderd",
    imageDeleteFailed: "De afbeelding kon niet worden verwijderd", cropSaved: "Uitsnede opgeslagen", cropSaveFailed: "De uitsnede kon niet worden opgeslagen",
    wallpaperUpdated: "Vergrendelscherm bijgewerkt",
  },
  pl: {
    automaticActive: "Tapety zmieniają się automatycznie", automaticPaused: "Automatyczna zmiana jest wstrzymana",
    settings: "Ustawienia", currentWallpaper: "Bieżąca tapeta", currentImage: "Bieżący obraz", nextImage: "Następny obraz",
    changeInterval: "Zmieniaj obraz", paused: "Wstrzymano", selectImages: "Wybierz obrazy", pleaseWait: "Proszę czekać…",
    collection: "Moja kolekcja", image: "obraz", images: "obrazy", motif: "Obraz", noImages: "Nie wybrano jeszcze obrazów",
    collectionHint: "Dotknij liczby obrazów, aby otworzyć galerię.", shuffle: "Losowa kolejność", lockScreenOnly: "Tylko ekran blokady",
    settingsIntro: "Wybierz sposób działania WallpaperFlow w tle.", language: "Język", noImageLimit: "Bez limitu obrazów",
    privacyInfo: "Wybór pozostaje prywatny na tym urządzeniu. Ogranicza go tylko dostępne miejsce.", home: "Start", back: "Wstecz",
    addImages: "Dodaj obrazy", backToGallery: "Wróć do galerii", editImage: "Dopasuj obraz", savedForImage: "Zapisane tylko dla tego obrazu",
    saveCrop: "Zapisz kadr", myImages: "Moje obrazy", current: "Bieżący", adjustImage: "Dopasuj obraz", deleteImage: "Usuń obraz",
    emptyCollection: "Kolekcja jest pusta", emptyCollectionText: "Dodaj obrazy, które mają automatycznie zmieniać się na ekranie blokady.",
    galleryLoading: "Wczytywanie galerii…", loadMore: "Wczytaj więcej obrazów", editCrop: "Edytuj kadr",
    gestureLabel: "Przesuwaj jednym palcem i powiększaj dwoma", cropPreview: "Podgląd kadru", imageFit: "Dopasowanie obrazu",
    fill: "Wypełnij", fit: "Dopasuj", adjustOnScreen: "Dopasuj bezpośrednio na ekranie", gestureHelp: "Przeciągnij na ekranie lub uszczypnij dwoma palcami",
    zoom: "Powiększenie", rotate: "Obróć o 90°", reset: "Resetuj", deleteConfirm: "Czy na pewno usunąć ten obraz z kolekcji?",
    galleryLoadFailed: "Nie udało się wczytać galerii", automaticDisabled: "Automatyczna zmiana jest wstrzymana", settingSaved: "Ustawienie zapisane",
    intervalSaved: "Interwał zapisany", androidOnly: "Ta funkcja jest dostępna na Androidzie", imagesAdded: "Obrazy dodano do kolekcji",
    selectionCancelled: "Anulowano wybór", imageSelectionAndroid: "Wybór obrazów jest dostępny na Androidzie", imageDeleted: "Obraz usunięty",
    imageDeleteFailed: "Nie udało się usunąć obrazu", cropSaved: "Kadr zapisany", cropSaveFailed: "Nie udało się zapisać kadru",
    wallpaperUpdated: "Ekran blokady zaktualizowany",
  },
  pt: {
    automaticActive: "Os seus fundos mudam automaticamente", automaticPaused: "A rotação automática está em pausa",
    settings: "Definições", currentWallpaper: "Fundo atual", currentImage: "Imagem atual", nextImage: "Imagem seguinte",
    changeInterval: "Mudar imagem", paused: "Em pausa", selectImages: "Selecionar imagens", pleaseWait: "Aguarde…",
    collection: "A minha coleção", image: "imagem", images: "imagens", motif: "Imagem", noImages: "Ainda não há imagens selecionadas",
    collectionHint: "Toque no número de imagens para abrir a galeria.", shuffle: "Ordem aleatória", lockScreenOnly: "Apenas ecrã de bloqueio",
    settingsIntro: "Escolha como o WallpaperFlow funciona em segundo plano.", language: "Idioma", noImageLimit: "Sem limite de imagens",
    privacyInfo: "A sua seleção permanece privada neste dispositivo. O único limite é o espaço disponível.", home: "Início", back: "Voltar",
    addImages: "Adicionar imagens", backToGallery: "Voltar à galeria", editImage: "Ajustar imagem", savedForImage: "Guardado apenas para esta imagem",
    saveCrop: "Guardar recorte", myImages: "As minhas imagens", current: "Atual", adjustImage: "Ajustar imagem", deleteImage: "Eliminar imagem",
    emptyCollection: "A coleção está vazia", emptyCollectionText: "Adicione imagens para alternarem automaticamente no ecrã de bloqueio.",
    galleryLoading: "A carregar galeria…", loadMore: "Carregar mais imagens", editCrop: "Editar recorte",
    gestureLabel: "Mova a imagem com um dedo e amplie com dois", cropPreview: "Pré-visualização do recorte", imageFit: "Ajuste da imagem",
    fill: "Preencher", fit: "Ajustar", adjustOnScreen: "Ajustar diretamente no ecrã", gestureHelp: "Arraste no ecrã ou aproxime dois dedos",
    zoom: "Zoom", rotate: "Rodar 90°", reset: "Repor", deleteConfirm: "Pretende mesmo eliminar esta imagem da coleção?",
    galleryLoadFailed: "Não foi possível carregar a galeria", automaticDisabled: "A rotação automática está em pausa", settingSaved: "Definição guardada",
    intervalSaved: "Intervalo guardado", androidOnly: "Esta função está disponível no Android", imagesAdded: "Imagens adicionadas à coleção",
    selectionCancelled: "Seleção cancelada", imageSelectionAndroid: "A seleção de imagens está disponível no Android", imageDeleted: "Imagem eliminada",
    imageDeleteFailed: "Não foi possível eliminar a imagem", cropSaved: "Recorte guardado", cropSaveFailed: "Não foi possível guardar o recorte",
    wallpaperUpdated: "Ecrã de bloqueio atualizado",
  },
  ja: {
    automaticActive: "壁紙は自動的に切り替わります", automaticPaused: "自動切り替えは一時停止中です",
    settings: "設定", currentWallpaper: "現在の壁紙", currentImage: "現在の画像", nextImage: "次の画像",
    changeInterval: "画像を切り替え", paused: "一時停止", selectImages: "画像を選択", pleaseWait: "お待ちください…",
    collection: "マイコレクション", image: "枚", images: "枚", motif: "画像", noImages: "画像がまだ選択されていません",
    collectionHint: "画像数をタップしてギャラリーを開きます。", shuffle: "ランダムな順序", lockScreenOnly: "ロック画面のみ",
    settingsIntro: "WallpaperFlow のバックグラウンド動作を設定します。", language: "言語", noImageLimit: "画像数の制限なし",
    privacyInfo: "選択した画像はこの端末内にのみ保存されます。上限は空き容量だけです。", home: "ホーム", back: "戻る",
    addImages: "画像を追加", backToGallery: "ギャラリーに戻る", editImage: "画像を調整", savedForImage: "この画像にのみ保存されます",
    saveCrop: "切り抜きを保存", myImages: "マイ画像", current: "現在", adjustImage: "画像を調整", deleteImage: "画像を削除",
    emptyCollection: "コレクションは空です", emptyCollectionText: "ロック画面で自動的に切り替える画像を追加してください。",
    galleryLoading: "ギャラリーを読み込み中…", loadMore: "さらに読み込む", editCrop: "切り抜きを編集",
    gestureLabel: "1本指で移動し、2本指でズームします", cropPreview: "切り抜きプレビュー", imageFit: "画像の配置",
    fill: "画面を埋める", fit: "全体を表示", adjustOnScreen: "画面上で直接調整", gestureHelp: "画面内をドラッグするか、2本指でピンチします",
    zoom: "ズーム", rotate: "90°回転", reset: "リセット", deleteConfirm: "この画像をコレクションから削除しますか？",
    galleryLoadFailed: "ギャラリーを読み込めませんでした", automaticDisabled: "自動切り替えは一時停止中です", settingSaved: "設定を保存しました",
    intervalSaved: "切り替え間隔を保存しました", androidOnly: "この機能は Android で利用できます", imagesAdded: "画像をコレクションに追加しました",
    selectionCancelled: "選択をキャンセルしました", imageSelectionAndroid: "画像選択は Android で利用できます", imageDeleted: "画像を削除しました",
    imageDeleteFailed: "画像を削除できませんでした", cropSaved: "切り抜きを保存しました", cropSaveFailed: "切り抜きを保存できませんでした",
    wallpaperUpdated: "ロック画面を更新しました",
  },
  ko: {
    automaticActive: "배경화면이 자동으로 변경됩니다", automaticPaused: "자동 변경이 일시 중지되었습니다",
    settings: "설정", currentWallpaper: "현재 배경화면", currentImage: "현재 이미지", nextImage: "다음 이미지",
    changeInterval: "이미지 변경", paused: "일시 중지", selectImages: "이미지 선택", pleaseWait: "잠시 기다려 주세요…",
    collection: "내 컬렉션", image: "이미지", images: "이미지", motif: "이미지", noImages: "선택한 이미지가 없습니다",
    collectionHint: "이미지 수를 탭하여 갤러리를 여세요.", shuffle: "무작위 순서", lockScreenOnly: "잠금 화면만",
    settingsIntro: "WallpaperFlow의 백그라운드 작동 방식을 선택하세요.", language: "언어", noImageLimit: "이미지 수 제한 없음",
    privacyInfo: "선택한 이미지는 이 기기에만 비공개로 저장됩니다. 저장 공간만 사용 한도를 결정합니다.", home: "홈", back: "뒤로",
    addImages: "이미지 추가", backToGallery: "갤러리로 돌아가기", editImage: "이미지 조정", savedForImage: "이 이미지에만 저장됨",
    saveCrop: "자르기 저장", myImages: "내 이미지", current: "현재", adjustImage: "이미지 조정", deleteImage: "이미지 삭제",
    emptyCollection: "컬렉션이 비어 있습니다", emptyCollectionText: "잠금 화면에서 자동으로 변경할 이미지를 추가하세요.",
    galleryLoading: "갤러리 불러오는 중…", loadMore: "이미지 더 불러오기", editCrop: "자르기 편집",
    gestureLabel: "한 손가락으로 이동하고 두 손가락으로 확대하세요", cropPreview: "자르기 미리보기", imageFit: "이미지 맞춤",
    fill: "채우기", fit: "맞추기", adjustOnScreen: "화면에서 직접 조정", gestureHelp: "화면 안에서 드래그하거나 두 손가락으로 확대하세요",
    zoom: "확대", rotate: "90° 회전", reset: "초기화", deleteConfirm: "이 이미지를 컬렉션에서 삭제할까요?",
    galleryLoadFailed: "갤러리를 불러올 수 없습니다", automaticDisabled: "자동 변경이 일시 중지되었습니다", settingSaved: "설정을 저장했습니다",
    intervalSaved: "변경 간격을 저장했습니다", androidOnly: "이 기능은 Android에서 사용할 수 있습니다", imagesAdded: "컬렉션에 이미지를 추가했습니다",
    selectionCancelled: "선택을 취소했습니다", imageSelectionAndroid: "이미지 선택은 Android에서 사용할 수 있습니다", imageDeleted: "이미지를 삭제했습니다",
    imageDeleteFailed: "이미지를 삭제할 수 없습니다", cropSaved: "자르기를 저장했습니다", cropSaveFailed: "자르기를 저장할 수 없습니다",
    wallpaperUpdated: "잠금 화면을 업데이트했습니다",
  },
  "zh-CN": {
    automaticActive: "壁纸会自动更换", automaticPaused: "自动更换已暂停",
    settings: "设置", currentWallpaper: "当前壁纸", currentImage: "当前图片", nextImage: "下一张图片",
    changeInterval: "更换图片", paused: "已暂停", selectImages: "选择图片", pleaseWait: "请稍候…",
    collection: "我的收藏", image: "张图片", images: "张图片", motif: "图片", noImages: "尚未选择图片",
    collectionHint: "点击图片数量打开图库。", shuffle: "随机顺序", lockScreenOnly: "仅锁屏",
    settingsIntro: "选择 WallpaperFlow 在后台的工作方式。", language: "语言", noImageLimit: "不限图片数量",
    privacyInfo: "所选图片仅保存在此设备上。唯一限制是可用存储空间。", home: "首页", back: "返回",
    addImages: "添加图片", backToGallery: "返回图库", editImage: "调整图片", savedForImage: "仅为此图片保存",
    saveCrop: "保存裁剪", myImages: "我的图片", current: "当前", adjustImage: "调整图片", deleteImage: "删除图片",
    emptyCollection: "收藏为空", emptyCollectionText: "添加要在锁屏上自动轮换的图片。",
    galleryLoading: "正在加载图库…", loadMore: "加载更多图片", editCrop: "编辑裁剪",
    gestureLabel: "单指移动图片，双指缩放", cropPreview: "裁剪预览", imageFit: "图片适配",
    fill: "填充", fit: "适应", adjustOnScreen: "直接在屏幕中调整", gestureHelp: "在屏幕内拖动或双指缩放",
    zoom: "缩放", rotate: "旋转 90°", reset: "重置", deleteConfirm: "确定要从收藏中删除此图片吗？",
    galleryLoadFailed: "无法加载图库", automaticDisabled: "自动更换已暂停", settingSaved: "设置已保存",
    intervalSaved: "更换间隔已保存", androidOnly: "此功能可在 Android 上使用", imagesAdded: "图片已添加到收藏",
    selectionCancelled: "已取消选择", imageSelectionAndroid: "图片选择功能可在 Android 上使用", imageDeleted: "图片已删除",
    imageDeleteFailed: "无法删除图片", cropSaved: "裁剪已保存", cropSaveFailed: "无法保存裁剪",
    wallpaperUpdated: "锁屏已更新",
  },
};

function intervalLabel(language: Language, minutes: number) {
  if (language === "de") return minutes < 60 ? `Alle ${minutes} Min.` : minutes === 60 ? "Jede Stunde" : `Alle ${minutes / 60} Std.`;
  if (language === "fr") return minutes < 60 ? `Toutes les ${minutes} min` : minutes === 60 ? "Toutes les heures" : `Toutes les ${minutes / 60} h`;
  if (language === "es") return minutes < 60 ? `Cada ${minutes} min` : minutes === 60 ? "Cada hora" : `Cada ${minutes / 60} h`;
  if (language === "it") return minutes < 60 ? `Ogni ${minutes} min` : minutes === 60 ? "Ogni ora" : `Ogni ${minutes / 60} ore`;
  if (language === "nl") return minutes < 60 ? `Elke ${minutes} min.` : minutes === 60 ? "Elk uur" : `Elke ${minutes / 60} uur`;
  if (language === "pl") return minutes < 60 ? `Co ${minutes} min` : minutes === 60 ? "Co godzinę" : `Co ${minutes / 60} godz.`;
  if (language === "pt") return minutes < 60 ? `A cada ${minutes} min` : minutes === 60 ? "A cada hora" : `A cada ${minutes / 60} h`;
  if (language === "ja") return minutes < 60 ? `${minutes}分ごと` : minutes === 60 ? "1時間ごと" : `${minutes / 60}時間ごと`;
  if (language === "ko") return minutes < 60 ? `${minutes}분마다` : minutes === 60 ? "1시간마다" : `${minutes / 60}시간마다`;
  if (language === "zh-CN") return minutes < 60 ? `每 ${minutes} 分钟` : minutes === 60 ? "每小时" : `每 ${minutes / 60} 小时`;
  return minutes < 60 ? `Every ${minutes} min` : minutes === 60 ? "Every hour" : `Every ${minutes / 60} hours`;
}

const selectionCopies: Record<Language, {
  selected: string; deleteSelected: string; deleteSelectedConfirm: string; imagesDeleted: string; imagesDeleteFailed: string;
  selectImagesToDelete: string; clearSelection: string; selectAll: string; selectImage: string; deselectImage: string;
}> = {
  de: { selected: "ausgewählt", deleteSelected: "Auswahl löschen", deleteSelectedConfirm: "Möchtest du die ausgewählten Bilder wirklich löschen?", imagesDeleted: "Ausgewählte Bilder wurden gelöscht", imagesDeleteFailed: "Bilder konnten nicht gelöscht werden", selectImagesToDelete: "Bilder zum Löschen auswählen", clearSelection: "Auswahl aufheben", selectAll: "Alle auswählen", selectImage: "Bild auswählen", deselectImage: "Bild abwählen" },
  en: { selected: "selected", deleteSelected: "Delete selection", deleteSelectedConfirm: "Do you really want to delete the selected images?", imagesDeleted: "Selected images deleted", imagesDeleteFailed: "The images could not be deleted", selectImagesToDelete: "Select images to delete", clearSelection: "Clear selection", selectAll: "Select all", selectImage: "Select image", deselectImage: "Deselect image" },
  fr: { selected: "sélectionnées", deleteSelected: "Supprimer la sélection", deleteSelectedConfirm: "Voulez-vous vraiment supprimer les images sélectionnées ?", imagesDeleted: "Images sélectionnées supprimées", imagesDeleteFailed: "Impossible de supprimer les images", selectImagesToDelete: "Sélectionnez les images à supprimer", clearSelection: "Tout désélectionner", selectAll: "Tout sélectionner", selectImage: "Sélectionner l’image", deselectImage: "Désélectionner l’image" },
  es: { selected: "seleccionadas", deleteSelected: "Eliminar selección", deleteSelectedConfirm: "¿Quieres eliminar las imágenes seleccionadas?", imagesDeleted: "Imágenes seleccionadas eliminadas", imagesDeleteFailed: "No se pudieron eliminar las imágenes", selectImagesToDelete: "Selecciona imágenes para eliminar", clearSelection: "Quitar selección", selectAll: "Seleccionar todo", selectImage: "Seleccionar imagen", deselectImage: "Deseleccionar imagen" },
  it: { selected: "selezionate", deleteSelected: "Elimina selezione", deleteSelectedConfirm: "Vuoi davvero eliminare le immagini selezionate?", imagesDeleted: "Immagini selezionate eliminate", imagesDeleteFailed: "Impossibile eliminare le immagini", selectImagesToDelete: "Seleziona le immagini da eliminare", clearSelection: "Deseleziona tutto", selectAll: "Seleziona tutto", selectImage: "Seleziona immagine", deselectImage: "Deseleziona immagine" },
  nl: { selected: "geselecteerd", deleteSelected: "Selectie verwijderen", deleteSelectedConfirm: "Wil je de geselecteerde afbeeldingen echt verwijderen?", imagesDeleted: "Geselecteerde afbeeldingen verwijderd", imagesDeleteFailed: "De afbeeldingen konden niet worden verwijderd", selectImagesToDelete: "Selecteer afbeeldingen om te verwijderen", clearSelection: "Selectie wissen", selectAll: "Alles selecteren", selectImage: "Afbeelding selecteren", deselectImage: "Afbeelding deselecteren" },
  pl: { selected: "wybrano", deleteSelected: "Usuń wybrane", deleteSelectedConfirm: "Czy na pewno usunąć wybrane obrazy?", imagesDeleted: "Wybrane obrazy usunięto", imagesDeleteFailed: "Nie udało się usunąć obrazów", selectImagesToDelete: "Wybierz obrazy do usunięcia", clearSelection: "Wyczyść wybór", selectAll: "Wybierz wszystkie", selectImage: "Wybierz obraz", deselectImage: "Odznacz obraz" },
  pt: { selected: "selecionadas", deleteSelected: "Eliminar seleção", deleteSelectedConfirm: "Pretende mesmo eliminar as imagens selecionadas?", imagesDeleted: "Imagens selecionadas eliminadas", imagesDeleteFailed: "Não foi possível eliminar as imagens", selectImagesToDelete: "Selecione imagens para eliminar", clearSelection: "Limpar seleção", selectAll: "Selecionar tudo", selectImage: "Selecionar imagem", deselectImage: "Desmarcar imagem" },
  ja: { selected: "件選択中", deleteSelected: "選択項目を削除", deleteSelectedConfirm: "選択した画像を削除しますか？", imagesDeleted: "選択した画像を削除しました", imagesDeleteFailed: "画像を削除できませんでした", selectImagesToDelete: "削除する画像を選択", clearSelection: "選択を解除", selectAll: "すべて選択", selectImage: "画像を選択", deselectImage: "画像の選択を解除" },
  ko: { selected: "개 선택됨", deleteSelected: "선택 항목 삭제", deleteSelectedConfirm: "선택한 이미지를 삭제할까요?", imagesDeleted: "선택한 이미지를 삭제했습니다", imagesDeleteFailed: "이미지를 삭제할 수 없습니다", selectImagesToDelete: "삭제할 이미지 선택", clearSelection: "선택 해제", selectAll: "모두 선택", selectImage: "이미지 선택", deselectImage: "이미지 선택 해제" },
  "zh-CN": { selected: "张已选择", deleteSelected: "删除所选", deleteSelectedConfirm: "确定要删除所选图片吗？", imagesDeleted: "已删除所选图片", imagesDeleteFailed: "无法删除图片", selectImagesToDelete: "选择要删除的图片", clearSelection: "清除选择", selectAll: "全选", selectImage: "选择图片", deselectImage: "取消选择图片" },
};

export const translations = Object.fromEntries(languages.map(language => {
  const copy = language === "en" ? en : copies[language];
  return [language, { ...copy, ...selectionCopies[language], everyMinutes: (minutes: number) => intervalLabel(language, minutes) }];
})) as Record<Language, Copy & typeof selectionCopies[Language] & { everyMinutes: (minutes: number) => string }>;

function normalizeLanguage(value: string): Language | undefined {
  const locale = value.toLowerCase();
  if (locale.startsWith("zh")) return "zh-CN";
  return languages.find(language => language.toLowerCase() === locale || locale.startsWith(`${language.toLowerCase()}-`));
}

export function initialLanguage(): Language {
  const stored = window.localStorage.getItem("wallpaperflow-language");
  if (stored) {
    const saved = normalizeLanguage(stored);
    if (saved) return saved;
  }
  const systemLocales = window.navigator.languages?.length ? window.navigator.languages : [window.navigator.language];
  for (const locale of systemLocales) {
    const match = normalizeLanguage(locale);
    if (match) return match;
  }
  return "en";
}
