package com.example.myapplication6;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;

import java.util.Locale;

/**
 * Persists a simple language preference ("en" / "tr") and applies it to the app context.
 */
public final class LocaleHelper {

    private static final String PREFS_NAME = "app_prefs";
    private static final String KEY_LANGUAGE = "language";

    private LocaleHelper() {}

    public static String getPreferredLanguage(Context context) {
        SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        String lang = prefs.getString(KEY_LANGUAGE, null);
        if (lang == null || lang.trim().isEmpty()) {
            String sysLang = Locale.getDefault().getLanguage();
            if ("tr".equalsIgnoreCase(sysLang)) return "tr";
            return "en";
        }
        if ("tr".equalsIgnoreCase(lang)) return "tr";
        return "en";
    }

    public static void setPreferredLanguage(Context context, String lang) {
        String normalized = "tr".equalsIgnoreCase(lang) ? "tr" : "en";
        SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        prefs.edit().putString(KEY_LANGUAGE, normalized).apply();
    }

    public static Context wrap(Context context) {
        String lang = getPreferredLanguage(context);
        Locale locale = new Locale(lang);
        Locale.setDefault(locale);

        Configuration config = new Configuration(context.getResources().getConfiguration());
        config.setLocale(locale);
        config.setLayoutDirection(locale);
        return context.createConfigurationContext(config);
    }
}

