<?php
declare(strict_types=1);

class Lang
{
    /** All supported language codes. Each must have a matching file in /lang/. */
    public const SUPPORTED = ['de', 'en', 'es', 'fr', 'hu', 'it', 'nl', 'pl', 'ru', 'tr', 'zh'];

    /** Human-readable native names for the picker UIs. */
    public const NAMES = [
        'de' => 'Deutsch',
        'en' => 'English',
        'es' => 'Español',
        'fr' => 'Français',
        'hu' => 'Magyar',
        'it' => 'Italiano',
        'nl' => 'Nederlands',
        'pl' => 'Polski',
        'ru' => 'Русский',
        'tr' => 'Türkçe',
        'zh' => '中文',
    ];

    /** Fallback when nothing else applies (browser, user, default-setting). */
    public const FALLBACK = 'en';

    private static array $strings = [];
    private static string $current = self::FALLBACK;

    public static function isSupported(string $lang): bool
    {
        return in_array($lang, self::SUPPORTED, true);
    }

    public static function load(string $lang): void
    {
        if (!self::isSupported($lang)) $lang = self::FALLBACK;
        self::$current = $lang;
        $file = BASE_PATH . '/lang/' . $lang . '.php';
        if (file_exists($file)) {
            self::$strings = require $file;
        }
    }

    /**
     * Pick the best language for an incoming Accept-Language header.
     * Falls back to self::FALLBACK when no supported language is found.
     */
    public static function fromAcceptHeader(?string $header): string
    {
        if (!$header) return self::FALLBACK;
        // Each entry: "en-US,en;q=0.9,de;q=0.7"
        $entries = [];
        foreach (explode(',', $header) as $part) {
            $part = trim($part);
            if ($part === '') continue;
            [$tag, $q] = array_pad(explode(';q=', $part, 2), 2, '1');
            $entries[] = ['tag' => strtolower(trim($tag)), 'q' => (float)$q];
        }
        usort($entries, fn($a, $b) => $b['q'] <=> $a['q']);
        foreach ($entries as $e) {
            $primary = explode('-', $e['tag'])[0] ?? '';
            if ($primary !== '' && self::isSupported($primary)) return $primary;
        }
        return self::FALLBACK;
    }

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

    public static function current(): string
    {
        return self::$current;
    }
}

// Shorthand global function
function t(string $key, array $replace = []): string
{
    return htmlspecialchars(Lang::get($key, $replace), ENT_QUOTES, 'UTF-8');
}

function tr(string $key, array $replace = []): string
{
    return Lang::get($key, $replace);
}
