<?php

class FbLang
{
    private static bool  $loaded  = false;
    private static array $strings = [];

    public static function load(): void
    {
        if (self::$loaded) return;
        try { $lang = \Core\System\Language::code() ?? 'ar'; } catch (\Throwable $e) { $lang = 'ar'; }
        $file = __DIR__ . '/lang/' . $lang . '.json';
        if (!is_file($file)) $file = __DIR__ . '/lang/ar.json';
        if (is_file($file)) self::$strings = json_decode(file_get_contents($file), true) ?? [];
        self::$loaded = true;
    }

    public static function t(string $key, string $fallback = '', array $replace = []): string
    {
        $text = self::$strings[$key] ?? $fallback ?: $key;
        foreach ($replace as $k => $v) $text = str_replace(':' . $k, (string)$v, $text);
        return $text;
    }
}

if (!function_exists('fbt')) {
    function fbt(string $key, string $fallback = '', array $replace = []): string {
        return FbLang::t($key, $fallback, $replace);
    }
}
