import { createI18n } from 'vue-i18n';

export type SupportedLocale = 'en' | 'it' | 'fr' | 'de' | 'es';

export const localeOptions: { label: string; value: SupportedLocale }[] = [
  { label: 'English', value: 'en' },
  { label: 'Italiano', value: 'it' },
  { label: 'Français', value: 'fr' },
  { label: 'Deutsch', value: 'de' },
  { label: 'Español', value: 'es' },
];

const fallbackLocale: SupportedLocale = 'en';
const storageKey = 'app.locale';

const messages = {
  en: {
    app: { title: 'Encore Profiles' },
    nav: {
      menu: 'Menu',
      profiles: 'Profiles',
      myProfile: 'My profile',
      login: 'Log in',
      register: 'Register',
      logout: 'Log out ({name})',
      logoutAction: 'Log out',
      language: 'Language',
    },
    actions: {
      cancel: 'Cancel',
      save: 'Save',
      create: 'Create',
      remove: 'Remove',
      chooseFile: 'Choose file',
      camera: 'Camera',
      takePhoto: 'Take photo',
      crop: 'Crop',
      newProfile: 'New profile',
      register: 'Register',
      editProfile: 'Edit profile',
      updateRole: 'Update role',
      updateStatus: 'Update status',
      updatePassword: 'Update password',
    },
    fields: {
      email: 'Email',
      password: 'Password',
      displayName: 'Display name',
      firstName: 'First name',
      lastName: 'Last name',
      address: 'Address',
      cap: 'Postcode',
      city: 'City',
      country: 'Country',
      role: 'Role',
      status: 'Status',
    },
    avatar: {
      cropAvatar: 'Crop avatar',
      cameraUnavailable: 'Camera not available in this browser.',
    },
    admin: {
      dashboard: 'Dashboard',
      profiles: 'Profiles',
      personalData: 'Personal data',
      profile: 'Profile',
      notArtist: 'Not an artist',
      artist: 'Artist',
      columns: {
        name: 'Name',
        email: 'Email',
        role: 'Role',
        status: 'Status',
        artist: 'Artist',
        created: 'Created',
        updated: 'Updated',
      },
    },
    profile: {
      title: 'My profile',
      avatar: 'Avatar',
      password: 'Password',
      currentPassword: 'Current password',
      newPassword: 'New password',
      confirmNewPassword: 'Confirm new password',
      passwordMismatch: 'Passwords do not match.',
      loginRequired: 'You must be logged in to view your profile.',
    },
    login: {
      title: 'Log in',
      needAccount: 'Create an account',
      forgotPassword: 'Forgot password',
    },
    passwordReset: {
      title: 'Password reset',
      newPasswordTitle: 'Choose a new password',
      sendLink: 'Send reset link',
      updatePassword: 'Update password',
      backToLogin: 'Back to log in',
      requestSent: 'If the email exists, we sent a password reset link.',
      resetDone: 'Password updated. You can now log in.',
    },
    register: {
      title: 'Create account',
      welcomeTitle: 'Welcome',
      haveAccount: 'I already have an account',
      success: 'Registration completed. You can now log in.',
      confirmationSent: 'We sent you a confirmation request. Please check your mailbox.',
      emailUnavailable: 'This email is already registered.',
      emailDomainInvalid: 'This email domain cannot receive email.',
    },
    welcome: {
      title: 'Email confirmation',
      success: 'Email confirmed for {email}.',
      missingToken: 'Missing confirmation token.',
    },
    pages: {
      home: 'Home',
      goHome: 'Go Home',
      goToIndex: 'Go to Index Page',
      goToSecond: 'Go to Second Page',
      cropperExample: 'Cropper example',
      notFound: 'Oops. Nothing here...',
      unauthorized: 'Unauthorized',
      unauthorizedHint: 'You need to log in to access this page.',
    },
    status: {
      0: 'Active',
      1: 'Inactive',
      2: 'Suspended',
      3: 'Deleted',
      4: 'Pending',
      5: 'Waiting deletion',
      6: 'Banned',
      unknown: 'Unknown ({status})',
    },
  },
  it: {
    app: { title: 'Profili Encore' },
    nav: {
      menu: 'Menu',
      profiles: 'Profili',
      myProfile: 'Il mio profilo',
      login: 'Accedi',
      register: 'Registrati',
      logout: 'Esci ({name})',
      logoutAction: 'Esci',
      language: 'Lingua',
    },
    actions: {
      cancel: 'Annulla',
      save: 'Salva',
      create: 'Crea',
      remove: 'Rimuovi',
      chooseFile: 'Scegli file',
      camera: 'Fotocamera',
      takePhoto: 'Scatta foto',
      crop: 'Ritaglia',
      newProfile: 'Nuovo profilo',
      register: 'Registrati',
      editProfile: 'Modifica profilo',
      updateRole: 'Aggiorna ruolo',
      updateStatus: 'Aggiorna stato',
      updatePassword: 'Aggiorna password',
    },
    fields: {
      email: 'Email',
      password: 'Password',
      displayName: 'Nome visualizzato',
      firstName: 'Nome',
      lastName: 'Cognome',
      address: 'Indirizzo',
      cap: 'CAP',
      city: 'Città',
      country: 'Paese',
      role: 'Ruolo',
      status: 'Stato',
    },
    avatar: {
      cropAvatar: 'Ritaglia avatar',
      cameraUnavailable: 'Fotocamera non disponibile in questo browser.',
    },
    admin: {
      dashboard: 'Dashboard',
      profiles: 'Profili',
      personalData: 'Dati personali',
      profile: 'Profilo',
      notArtist: 'Non artista',
      artist: 'Artista',
      columns: {
        name: 'Nome',
        email: 'Email',
        role: 'Ruolo',
        status: 'Stato',
        artist: 'Artista',
        created: 'Creato',
        updated: 'Aggiornato',
      },
    },
    profile: {
      title: 'Il mio profilo',
      avatar: 'Avatar',
      password: 'Password',
      currentPassword: 'Password corrente',
      newPassword: 'Nuova password',
      confirmNewPassword: 'Conferma nuova password',
      passwordMismatch: 'Le password non coincidono.',
      loginRequired: 'Devi effettuare l’accesso per visualizzare il profilo.',
    },
    login: {
      title: 'Accedi',
      needAccount: 'Crea un account',
      forgotPassword: 'Password dimenticata',
    },
    passwordReset: {
      title: 'Recupero password',
      newPasswordTitle: 'Scegli una nuova password',
      sendLink: 'Invia link di recupero',
      updatePassword: 'Aggiorna password',
      backToLogin: 'Torna al login',
      requestSent: 'Se l’email esiste, abbiamo inviato un link per reimpostare la password.',
      resetDone: 'Password aggiornata. Ora puoi accedere.',
    },
    register: {
      title: 'Crea account',
      welcomeTitle: 'Benvenuto',
      haveAccount: 'Ho già un account',
      success: 'Registrazione completata. Ora puoi accedere.',
      confirmationSent: 'Ti abbiamo inviato una richieta di conferma, consulta la tua casella di posta.',
      emailUnavailable: 'Questa email è già registrata.',
      emailDomainInvalid: 'Il dominio di questa email non può ricevere posta.',
    },
    welcome: {
      title: 'Conferma email',
      success: 'Email confermata per {email}.',
      missingToken: 'Token di conferma mancante.',
    },
    pages: {
      home: 'Home',
      goHome: 'Vai alla home',
      goToIndex: 'Vai alla pagina iniziale',
      goToSecond: 'Vai alla seconda pagina',
      cropperExample: 'Esempio cropper',
      notFound: 'Ops. Qui non c’è niente...',
      unauthorized: 'Non autorizzato',
      unauthorizedHint: 'Devi effettuare l’accesso per visualizzare questa pagina.',
    },
    status: {
      0: 'Attivo',
      1: 'Inattivo',
      2: 'Sospeso',
      3: 'Eliminato',
      4: 'In attesa',
      5: 'In attesa di eliminazione',
      6: 'Bannato',
      unknown: 'Sconosciuto ({status})',
    },
  },
  fr: {
    app: { title: 'Profils Encore' },
    nav: {
      menu: 'Menu',
      profiles: 'Profils',
      myProfile: 'Mon profil',
      login: 'Connexion',
      register: 'Inscription',
      logout: 'Déconnexion ({name})',
      logoutAction: 'Déconnexion',
      language: 'Langue',
    },
    actions: {
      cancel: 'Annuler',
      save: 'Enregistrer',
      create: 'Créer',
      remove: 'Supprimer',
      chooseFile: 'Choisir un fichier',
      camera: 'Caméra',
      takePhoto: 'Prendre une photo',
      crop: 'Recadrer',
      newProfile: 'Nouveau profil',
      register: 'S’inscrire',
      editProfile: 'Modifier le profil',
      updateRole: 'Modifier le rôle',
      updateStatus: 'Modifier le statut',
      updatePassword: 'Modifier le mot de passe',
    },
    fields: {
      email: 'Email',
      password: 'Mot de passe',
      displayName: 'Nom affiché',
      firstName: 'Prénom',
      lastName: 'Nom',
      address: 'Adresse',
      cap: 'Code postal',
      city: 'Ville',
      country: 'Pays',
      role: 'Rôle',
      status: 'Statut',
    },
    avatar: {
      cropAvatar: 'Recadrer l’avatar',
      cameraUnavailable: 'Caméra non disponible dans ce navigateur.',
    },
    admin: {
      dashboard: 'Tableau de bord',
      profiles: 'Profils',
      personalData: 'Données personnelles',
      profile: 'Profil',
      notArtist: 'Pas artiste',
      artist: 'Artiste',
      columns: {
        name: 'Nom',
        email: 'Email',
        role: 'Rôle',
        status: 'Statut',
        artist: 'Artiste',
        created: 'Créé',
        updated: 'Mis à jour',
      },
    },
    profile: {
      title: 'Mon profil',
      avatar: 'Avatar',
      password: 'Mot de passe',
      currentPassword: 'Mot de passe actuel',
      newPassword: 'Nouveau mot de passe',
      confirmNewPassword: 'Confirmer le nouveau mot de passe',
      passwordMismatch: 'Les mots de passe ne correspondent pas.',
      loginRequired: 'Vous devez être connecté pour voir votre profil.',
    },
    login: {
      title: 'Connexion',
      needAccount: 'Créer un compte',
      forgotPassword: 'Mot de passe oublié',
    },
    passwordReset: {
      title: 'Réinitialisation du mot de passe',
      newPasswordTitle: 'Choisir un nouveau mot de passe',
      sendLink: 'Envoyer le lien',
      updatePassword: 'Mettre à jour le mot de passe',
      backToLogin: 'Retour à la connexion',
      requestSent: 'Si l’email existe, nous avons envoyé un lien de réinitialisation.',
      resetDone: 'Mot de passe mis à jour. Vous pouvez maintenant vous connecter.',
    },
    register: {
      title: 'Créer un compte',
      welcomeTitle: 'Bienvenue',
      haveAccount: 'J’ai déjà un compte',
      success: 'Inscription terminée. Vous pouvez maintenant vous connecter.',
      confirmationSent: 'Nous vous avons envoyé une demande de confirmation. Veuillez consulter votre boîte mail.',
      emailUnavailable: 'Cet email est déjà enregistré.',
      emailDomainInvalid: 'Ce domaine email ne peut pas recevoir d’e-mails.',
    },
    welcome: {
      title: 'Confirmation email',
      success: 'Email confirmée pour {email}.',
      missingToken: 'Jeton de confirmation manquant.',
    },
    pages: {
      home: 'Accueil',
      goHome: 'Accueil',
      goToIndex: 'Aller à la page d’accueil',
      goToSecond: 'Aller à la deuxième page',
      cropperExample: 'Exemple de recadrage',
      notFound: 'Oups. Rien ici...',
      unauthorized: 'Non autorisé',
      unauthorizedHint: 'Vous devez vous connecter pour accéder à cette page.',
    },
    status: {
      0: 'Actif',
      1: 'Inactif',
      2: 'Suspendu',
      3: 'Supprimé',
      4: 'En attente',
      5: 'Suppression en attente',
      6: 'Banni',
      unknown: 'Inconnu ({status})',
    },
  },
  de: {
    app: { title: 'Encore Profile' },
    nav: {
      menu: 'Menü',
      profiles: 'Profile',
      myProfile: 'Mein Profil',
      login: 'Anmelden',
      register: 'Registrieren',
      logout: 'Abmelden ({name})',
      logoutAction: 'Abmelden',
      language: 'Sprache',
    },
    actions: {
      cancel: 'Abbrechen',
      save: 'Speichern',
      create: 'Erstellen',
      remove: 'Entfernen',
      chooseFile: 'Datei wählen',
      camera: 'Kamera',
      takePhoto: 'Foto aufnehmen',
      crop: 'Zuschneiden',
      newProfile: 'Neues Profil',
      register: 'Registrieren',
      editProfile: 'Profil bearbeiten',
      updateRole: 'Rolle ändern',
      updateStatus: 'Status ändern',
      updatePassword: 'Passwort ändern',
    },
    fields: {
      email: 'E-Mail',
      password: 'Passwort',
      displayName: 'Anzeigename',
      firstName: 'Vorname',
      lastName: 'Nachname',
      address: 'Adresse',
      cap: 'Postleitzahl',
      city: 'Stadt',
      country: 'Land',
      role: 'Rolle',
      status: 'Status',
    },
    avatar: {
      cropAvatar: 'Avatar zuschneiden',
      cameraUnavailable: 'Kamera ist in diesem Browser nicht verfügbar.',
    },
    admin: {
      dashboard: 'Dashboard',
      profiles: 'Profile',
      personalData: 'Persönliche Daten',
      profile: 'Profil',
      notArtist: 'Kein Künstler',
      artist: 'Künstler',
      columns: {
        name: 'Name',
        email: 'E-Mail',
        role: 'Rolle',
        status: 'Status',
        artist: 'Künstler',
        created: 'Erstellt',
        updated: 'Aktualisiert',
      },
    },
    profile: {
      title: 'Mein Profil',
      avatar: 'Avatar',
      password: 'Passwort',
      currentPassword: 'Aktuelles Passwort',
      newPassword: 'Neues Passwort',
      confirmNewPassword: 'Neues Passwort bestätigen',
      passwordMismatch: 'Die Passwörter stimmen nicht überein.',
      loginRequired: 'Sie müssen angemeldet sein, um Ihr Profil zu sehen.',
    },
    login: {
      title: 'Anmelden',
      needAccount: 'Konto erstellen',
      forgotPassword: 'Passwort vergessen',
    },
    passwordReset: {
      title: 'Passwort zurücksetzen',
      newPasswordTitle: 'Neues Passwort wählen',
      sendLink: 'Link senden',
      updatePassword: 'Passwort aktualisieren',
      backToLogin: 'Zur Anmeldung',
      requestSent: 'Wenn die E-Mail existiert, haben wir einen Link zum Zurücksetzen gesendet.',
      resetDone: 'Passwort aktualisiert. Sie können sich jetzt anmelden.',
    },
    register: {
      title: 'Konto erstellen',
      welcomeTitle: 'Willkommen',
      haveAccount: 'Ich habe bereits ein Konto',
      success: 'Registrierung abgeschlossen. Sie können sich jetzt anmelden.',
      confirmationSent: 'Wir haben Ihnen eine Bestätigungsanfrage gesendet. Bitte prüfen Sie Ihr Postfach.',
      emailUnavailable: 'Diese E-Mail ist bereits registriert.',
      emailDomainInvalid: 'Diese E-Mail-Domain kann keine E-Mails empfangen.',
    },
    welcome: {
      title: 'E-Mail-Bestätigung',
      success: 'E-Mail für {email} bestätigt.',
      missingToken: 'Bestätigungstoken fehlt.',
    },
    pages: {
      home: 'Startseite',
      goHome: 'Zur Startseite',
      goToIndex: 'Zur Startseite',
      goToSecond: 'Zur zweiten Seite',
      cropperExample: 'Cropper-Beispiel',
      notFound: 'Hoppla. Hier ist nichts...',
      unauthorized: 'Nicht autorisiert',
      unauthorizedHint: 'Sie müssen angemeldet sein, um diese Seite aufzurufen.',
    },
    status: {
      0: 'Aktiv',
      1: 'Inaktiv',
      2: 'Gesperrt',
      3: 'Gelöscht',
      4: 'Ausstehend',
      5: 'Löschung ausstehend',
      6: 'Gebannt',
      unknown: 'Unbekannt ({status})',
    },
  },
  es: {
    app: { title: 'Perfiles Encore' },
    nav: {
      menu: 'Menú',
      profiles: 'Perfiles',
      myProfile: 'Mi perfil',
      login: 'Iniciar sesión',
      register: 'Registrarse',
      logout: 'Cerrar sesión ({name})',
      logoutAction: 'Cerrar sesión',
      language: 'Idioma',
    },
    actions: {
      cancel: 'Cancelar',
      save: 'Guardar',
      create: 'Crear',
      remove: 'Eliminar',
      chooseFile: 'Elegir archivo',
      camera: 'Cámara',
      takePhoto: 'Tomar foto',
      crop: 'Recortar',
      newProfile: 'Nuevo perfil',
      register: 'Registrarse',
      editProfile: 'Editar perfil',
      updateRole: 'Actualizar rol',
      updateStatus: 'Actualizar estado',
      updatePassword: 'Actualizar contraseña',
    },
    fields: {
      email: 'Email',
      password: 'Contraseña',
      displayName: 'Nombre visible',
      firstName: 'Nombre',
      lastName: 'Apellido',
      address: 'Dirección',
      cap: 'Código postal',
      city: 'Ciudad',
      country: 'País',
      role: 'Rol',
      status: 'Estado',
    },
    avatar: {
      cropAvatar: 'Recortar avatar',
      cameraUnavailable: 'La cámara no está disponible en este navegador.',
    },
    admin: {
      dashboard: 'Panel',
      profiles: 'Perfiles',
      personalData: 'Datos personales',
      profile: 'Perfil',
      notArtist: 'No artista',
      artist: 'Artista',
      columns: {
        name: 'Nombre',
        email: 'Email',
        role: 'Rol',
        status: 'Estado',
        artist: 'Artista',
        created: 'Creado',
        updated: 'Actualizado',
      },
    },
    profile: {
      title: 'Mi perfil',
      avatar: 'Avatar',
      password: 'Contraseña',
      currentPassword: 'Contraseña actual',
      newPassword: 'Nueva contraseña',
      confirmNewPassword: 'Confirmar nueva contraseña',
      passwordMismatch: 'Las contraseñas no coinciden.',
      loginRequired: 'Debes iniciar sesión para ver tu perfil.',
    },
    login: {
      title: 'Iniciar sesión',
      needAccount: 'Crear una cuenta',
      forgotPassword: 'Contraseña olvidada',
    },
    passwordReset: {
      title: 'Recuperar contraseña',
      newPasswordTitle: 'Elige una nueva contraseña',
      sendLink: 'Enviar enlace',
      updatePassword: 'Actualizar contraseña',
      backToLogin: 'Volver al inicio de sesión',
      requestSent: 'Si el email existe, enviamos un enlace para restablecer la contraseña.',
      resetDone: 'Contraseña actualizada. Ahora puedes iniciar sesión.',
    },
    register: {
      title: 'Crear cuenta',
      welcomeTitle: 'Bienvenido',
      haveAccount: 'Ya tengo una cuenta',
      success: 'Registro completado. Ahora puedes iniciar sesión.',
      confirmationSent: 'Te hemos enviado una solicitud de confirmación. Revisa tu buzón de correo.',
      emailUnavailable: 'Este email ya está registrado.',
      emailDomainInvalid: 'Este dominio de email no puede recibir correo.',
    },
    welcome: {
      title: 'Confirmación de email',
      success: 'Email confirmado para {email}.',
      missingToken: 'Falta el token de confirmación.',
    },
    pages: {
      home: 'Inicio',
      goHome: 'Ir al inicio',
      goToIndex: 'Ir a la página inicial',
      goToSecond: 'Ir a la segunda página',
      cropperExample: 'Ejemplo de recorte',
      notFound: 'Vaya. Aquí no hay nada...',
      unauthorized: 'No autorizado',
      unauthorizedHint: 'Debes iniciar sesión para acceder a esta página.',
    },
    status: {
      0: 'Activo',
      1: 'Inactivo',
      2: 'Suspendido',
      3: 'Eliminado',
      4: 'Pendiente',
      5: 'Esperando eliminación',
      6: 'Bloqueado',
      unknown: 'Desconocido ({status})',
    },
  },
};

function detectLocale(): SupportedLocale {
  const stored = window.localStorage.getItem(storageKey);
  if (isSupportedLocale(stored)) return stored;

  const browserLocale = navigator.language.split('-')[0] ?? null;
  if (isSupportedLocale(browserLocale)) return browserLocale;

  return fallbackLocale;
}

function isSupportedLocale(locale: string | null): locale is SupportedLocale {
  return localeOptions.some((option) => option.value === locale);
}

export const i18n = createI18n({
  legacy: false,
  locale: detectLocale(),
  fallbackLocale,
  messages,
});

export function setLocale(locale: SupportedLocale) {
  i18n.global.locale.value = locale;
  window.localStorage.setItem(storageKey, locale);
}
