// LoopFollow
// AppLanguage.swift

import Foundation

/// User-selectable app interface language.
///
/// `.system` follows the device language (the default). The other cases override
/// it by writing the `AppleLanguages` user default, which iOS reads at launch to
/// pick the bundle localization — so a change takes full effect after the app is
/// restarted.
enum AppLanguage: String, CaseIterable, Codable {
    case system
    case english
    case chineseSimplified

    var displayName: String {
        switch self {
        case .system: return String(localized: "System")
        case .english: return "English"
        case .chineseSimplified: return "简体中文"
        }
    }

    /// The `AppleLanguages` code this option maps to, or `nil` to follow the system.
    var languageCode: String? {
        switch self {
        case .system: return nil
        case .english: return "en"
        case .chineseSimplified: return "zh-Hans"
        }
    }

    /// Writes (or clears) the `AppleLanguages` preference so iOS localizes the app
    /// bundle accordingly on the next launch.
    func applyToAppleLanguages() {
        let defaults = UserDefaults.standard
        if let code = languageCode {
            defaults.set([code], forKey: "AppleLanguages")
        } else {
            defaults.removeObject(forKey: "AppleLanguages")
        }
    }

    /// Re-asserts the stored preference at launch to keep `AppleLanguages` in sync
    /// with the value shown in Settings.
    static func applyStored() {
        Storage.shared.appLanguage.value.applyToAppleLanguages()
    }
}
