<?php
declare(strict_types=1);

const SUPPORTED_LOCALES = ['pt', 'en', 'es'];
const DEFAULT_LOCALE = 'pt';

/**
 * Resolves and persists the visitor's language. ?lang= wins (and is what the
 * header switcher sends), falling back to the cookie from a previous visit,
 * then the default. Must run before any output — it can set a cookie.
 */
function resolve_locale(): string
{
    // GET (switcher link) or POST (hidden field on the lead form, in case cookies are blocked) — either sets the cookie for next time.
    $fromQuery = $_GET['lang'] ?? $_POST['lang'] ?? null;
    if (is_string($fromQuery) && in_array($fromQuery, SUPPORTED_LOCALES, true)) {
        setcookie('lang', $fromQuery, time() + 60 * 60 * 24 * 365, '/', '', !empty($_SERVER['HTTPS']), true);
        return $fromQuery;
    }
    $fromCookie = $_COOKIE['lang'] ?? null;
    if (is_string($fromCookie) && in_array($fromCookie, SUPPORTED_LOCALES, true)) {
        return $fromCookie;
    }
    return DEFAULT_LOCALE;
}

function load_translations(string $locale): array
{
    static $cache = [];
    if (!isset($cache[$locale])) {
        $file = __DIR__ . '/lang/' . $locale . '.php';
        $cache[$locale] = is_file($file) ? require $file : [];
    }
    return $cache[$locale];
}

/** t('key', ['brand' => BRAND_NAME]) — falls back to the default locale, then the raw key. */
function t(string $key, array $replace = []): string
{
    static $locale = null;
    if ($locale === null) {
        $locale = resolve_locale();
    }
    $value = load_translations($locale)[$key] ?? load_translations(DEFAULT_LOCALE)[$key] ?? $key;
    foreach ($replace as $token => $v) {
        $value = str_replace('{' . $token . '}', (string) $v, $value);
    }
    return $value;
}

function current_locale(): string
{
    static $locale = null;
    if ($locale === null) {
        $locale = resolve_locale();
    }
    return $locale;
}
