<?php
declare(strict_types=1);

namespace App;

final class I18n
{
    private array $current = [];
    private array $fallback = [];

    public function __construct(private Config $config, private string $lang = 'en')
    {
        // Minimal example translations (normally load JSON/PHP arrays from disk)
        $this->fallback = [
            'common' => [
                'title' => 'Papa-Kind-Treff',
                'intro' => 'Väter vernetzen sich für Treffen mit und ohne Kinder.',
            ],
            'cta' => [
                'primary' => 'Weiter',
            ],
        ];

        $this->current = $this->fallback;
    }

    private function traverse(array $data, string $key): mixed
    {
        $node = $data;
        foreach (explode('.', $key) as $seg) {
            if (!is_array($node) || !array_key_exists($seg, $node)) {
                return null;
            }
            $node = $node[$seg];
        }
        return $node;
    }

    public function get(string $key, $default = '', array $vars = []): string
    {
        $val = $this->traverse($this->current, $key);
        if ($val === null) {
            $val = $this->traverse($this->fallback, $key);
        }
        if (!is_string($val)) {
            $val = (string)($default ?? '');
        }

        // Built-ins
        $val = str_replace('{year}', date('Y'), $val);
        $val = str_replace('{{primary_url}}', $this->config->primaryUrl, $val);

        foreach ($vars as $k => $v) {
            $val = str_replace('{' . $k . '}', (string)$v, $val);
            $val = str_replace('{{' . $k . '}}', (string)$v, $val);
        }
        return $val;
    }
}
