import type { AppPageProps } from '@/types/index';
import { usePage } from '@inertiajs/vue3';

export function useTranslations() {
  const page = usePage<AppPageProps & { translations?: any }>();

  const $t = (key: string, fallback?: string): string => {
    const translations = page.props.translations || {};

    // Handle translation keys like 'permissions.users.view', 'validate.users.manager', etc.
    const keyParts = key.split('.');
    if (keyParts.length >= 2) {
      const translationGroup = keyParts[0]; // 'permissions', 'validate', etc.
      const translationKey = keyParts.slice(1).join('.'); // 'users.view', 'users.manager', etc.

      // Look in translations[group][key]
      if (translations[translationGroup] && translations[translationGroup][translationKey]) {
        return translations[translationGroup][translationKey];
      }
    }

    // Fallback: try normal nested key lookup for other patterns
    const keys = key.split('.');
    let value = translations;

    for (const k of keys) {
      if (value && typeof value === 'object' && k in value) {
        value = value[k];
      } else {
        return fallback || key;
      }
    }

    return value || fallback || key;
  };

  return {
    $t,
  };
}
