namespace ClaudeDo.Localization;

public sealed class Localizer : ILocalizer
{
    private readonly LocaleStore _store;
    private readonly string _fallbackCode;
    private LocaleFile? _active;
    private LocaleFile? _fallback;

    public Localizer(LocaleStore store, string code, string fallbackCode = "en")
    {
        _store = store;
        _fallbackCode = fallbackCode;
        _store.TryGet(fallbackCode, out _fallback);
        SetLanguage(code);
    }

    public string CurrentCode { get; private set; } = "";

    public IReadOnlyList<LanguageOption> AvailableLanguages =>
        _store.Available.Select(f => new LanguageOption(f.Code, f.Name)).ToList();

    public event EventHandler? LanguageChanged;

    public string this[string key]
    {
        get
        {
            if (_active is not null && _active.Strings.TryGetValue(key, out var v)) return v;
            if (_fallback is not null && _fallback.Strings.TryGetValue(key, out var fv)) return fv;
            return key;
        }
    }

    public string Get(string key, params object[] args)
    {
        var fmt = this[key];
        return args.Length == 0 ? fmt : string.Format(fmt, args);
    }

    public void SetLanguage(string code)
    {
        if (_store.TryGet(code, out var f) && f is not null)
        {
            _active = f;
            CurrentCode = f.Code;
        }
        else
        {
            _active = _fallback;
            CurrentCode = _fallback?.Code ?? code;
        }
        LanguageChanged?.Invoke(this, EventArgs.Empty);
    }
}
