import Foundation
import Observation

/// Manages in-app language selection independently of the system locale.
@Observable
final class LanguageManager {

    static let shared = LanguageManager()

    enum Language: String, CaseIterable, Identifiable {
        case english = "en"
        case german  = "de"
        case spanish = "es"

        var id: String { rawValue }

        var displayName: String {
            switch self {
            case .english: return "English"
            case .german:  return "Deutsch"
            case .spanish: return "Español"
            }
        }

        var flag: String {
            switch self {
            case .english: return "🇬🇧"
            case .german:  return "🇩🇪"
            case .spanish: return "🇪🇸"
            }
        }
    }

    private(set) var current: Language

    private init() {
        let saved = UserDefaults.standard.string(forKey: "appLanguage") ?? ""
        current = Language(rawValue: saved) ?? .english
    }

    func set(_ language: Language) {
        current = language
        UserDefaults.standard.set(language.rawValue, forKey: "appLanguage")
    }

    /// Returns the localised string for key in the currently selected language.
    func string(_ key: String) -> String {
        guard let path = Bundle.main.path(forResource: current.rawValue, ofType: "lproj"),
              let bundle = Bundle(path: path) else {
            return NSLocalizedString(key, comment: "")
        }
        return bundle.localizedString(forKey: key, value: key, table: nil)
    }
}

/// Convenience shorthand
func L(_ key: String) -> String {
    LanguageManager.shared.string(key)
}
