<?php
declare(strict_types=1);

namespace App\Services\Translate;

class LocalDictionaryProvider implements TranslationProviderInterface
{
    private array $dictionary = [
        'en' => [
            'mod' => 'mod', 'muzik' => 'music', 'müzik' => 'music', 'yukleme' => 'upload', 'yükleme' => 'upload',
            'rehberi' => 'guide', 'gizlilik' => 'privacy', 'kullanim' => 'terms', 'sartlari' => 'terms',
            'topluluk' => 'community', 'kurallari' => 'rules', 'icerik' => 'content', 'politikasi' => 'policy',
            'hakkimizda' => 'about us', 'iletisim' => 'contact', 'baslamadan' => 'before starting',
        ],
        'de' => [
            'mod' => 'mod', 'muzik' => 'musik', 'müzik' => 'musik', 'rehberi' => 'leitfaden',
            'gizlilik' => 'datenschutz', 'topluluk' => 'community', 'kurallari' => 'regeln',
        ],
        'fr' => [
            'mod' => 'mod', 'muzik' => 'musique', 'müzik' => 'musique', 'rehberi' => 'guide',
            'gizlilik' => 'confidentialite', 'topluluk' => 'communaute', 'kurallari' => 'regles',
        ],
    ];

    public function translate(string $text, string $targetLanguage, string $sourceLanguage = 'tr'): string
    {
        $targetLanguage = substr(strtolower($targetLanguage), 0, 2);
        if ($targetLanguage === $sourceLanguage || $text === '') {
            return $text;
        }

        $map = $this->dictionary[$targetLanguage] ?? [];
        $translated = preg_replace_callback('/[\p{L}\p{N}]+/u', function (array $match) use ($map): string {
            $word = (string) $match[0];
            $key = function_exists('mb_strtolower') ? mb_strtolower($word, 'UTF-8') : strtolower($word);
            $key = strtr($key, ['İ' => 'i', 'ı' => 'i']);

            return $map[$key] ?? $word;
        }, $text) ?: $text;

        return '[draft ' . $targetLanguage . '] ' . $translated;
    }
}
