<?php

namespace App\Support;

class LocalizedSettings
{
    /** @var list<string> */
    private const array FIELDS = [
        'title', 'description', 'heading', 'name', 'quote', 'bio', 'role',
        'company', 'location', 'suffix', 'button_text', 'category', 'message',
    ];

    public static function apply(array $data, string $locale): array
    {
        if (! in_array($locale, ['en', 'fr'], true)) {
            $locale = 'en';
        }

        if ($locale === 'en') {
            return $data;
        }

        $out = [];
        foreach ($data as $key => $value) {
            $localizedKey = "{$key}_{$locale}";
            if (isset($data[$localizedKey]) && $data[$localizedKey] !== '') {
                $out[$key] = $data[$localizedKey];
            } else {
                $out[$key] = self::localizeValue($value, $locale);
            }
        }

        return $out;
    }

    private static function localizeValue(mixed $value, string $locale): mixed
    {
        if (! is_string($value) || ! self::looksLikeJsonArray($value)) {
            return $value;
        }

        $decoded = json_decode($value, true);
        if (! is_array($decoded)) {
            return $value;
        }

        $localized = array_map(
            fn ($item) => is_array($item) ? self::localizeItem($item, $locale) : $item,
            $decoded
        );

        return json_encode($localized, JSON_UNESCAPED_UNICODE);
    }

    private static function localizeItem(array $item, string $locale): array
    {
        $out = $item;
        foreach (self::FIELDS as $field) {
            $lk = "{$field}_{$locale}";
            if (isset($item[$lk]) && $item[$lk] !== '') {
                $out[$field] = $item[$lk];
            }
        }

        return $out;
    }

    private static function looksLikeJsonArray(string $value): bool
    {
        $trim = ltrim($value);

        return $trim !== '' && ($trim[0] === '[' || $trim[0] === '{');
    }
}
