<?php

declare(strict_types=1);

use SeoScope\i18n\Translator;

/**
 * Global translator instance (set by bootstrap request lifecycle).
 */
$GLOBALS['seoscope_translator'] = null;

function seoscope_translator(): ?Translator
{
    return $GLOBALS['seoscope_translator'] ?? null;
}

function seoscope_set_translator(?Translator $t): void
{
    $GLOBALS['seoscope_translator'] = $t;
}

/**
 * Translate string by key. Optional placeholder params: [ 'name' => 'World' ] for ":name" in message.
 *
 * @param array<string, string|int|float> $params
 */
function __(string $key, array $params = []): string
{
    $tr = seoscope_translator();
    if ($tr === null) {
        return $key;
    }
    return $tr->get($key, $params);
}

/**
 * Format a calendar day (Y-m-d) for tooltips and copy, using the current UI locale when possible.
 */
function seoscope_format_ui_long_date(string $ymd): string
{
    try {
        $d = new \DateTimeImmutable($ymd);
    } catch (\Exception) {
        return $ymd;
    }
    $code = seoscope_translator()?->getLocale() ?? 'en';
    if (class_exists(\IntlDateFormatter::class)) {
        $bcp = match ($code) {
            'it' => 'it_IT',
            'de' => 'de_DE',
            'es' => 'es_ES',
            'fr' => 'fr_FR',
            default => 'en_US',
        };
        $fmt = new \IntlDateFormatter(
            $bcp,
            \IntlDateFormatter::LONG,
            \IntlDateFormatter::NONE,
            null,
            \IntlDateFormatter::GREGORIAN
        );
        if ($fmt !== null) {
            $out = $fmt->format($d);
            if (is_string($out) && $out !== '') {
                return $out;
            }
        }
    }
    return $d->format('F j, Y');
}
