<?php

declare(strict_types=1);

final class I18n
{
    public const LOCALES = ['fr' => 'Français', 'en' => 'English'];
    private static string $locale = 'fr';
    private static array $catalogues = [];
    public static function setLocale(string $locale): void
    {
        self::$locale = isset(self::LOCALES[$locale]) ? $locale : 'fr';
    }
    public static function locale(): string
    {
        return self::$locale;
    }
    public static function translate(string $key, array $replace = []): string
    {
        $value = self::catalogue(self::$locale)[$key] ?? (self::catalogue('fr')[$key] ?? $key);
        foreach ($replace as $name => $replacement) {
            $value = str_replace(':' . $name, (string) $replacement, $value);
        }
        return $value;
    }
    public static function choice(string $singular, string $plural, int|float $count, array $replace = []): string
    {
        return self::translate($count == 1 ? $singular : $plural, ['count' => $count] + $replace);
    }
    private static function catalogue(string $locale): array
    {
        if (isset(self::$catalogues[$locale])) {
            return self::$catalogues[$locale];
        }
        $path = __DIR__ . '/../../resources/lang/' . $locale . '.php';
        $catalogue = is_file($path) ? require $path : [];
        return self::$catalogues[$locale] = is_array($catalogue) ? $catalogue : [];
    }
}
if (!function_exists('t')) {
    function t(string $key, array $replace = []): string
    {
        return I18n::translate($key, $replace);
    }
}
if (!function_exists('tn')) {
    function tn(string $singular, string $plural, int|float $count, array $replace = []): string
    {
        return I18n::choice($singular, $plural, $count, $replace);
    }
}
