//
//  UnitSystem.swift
//  Cable
//
//  Created by Stefan Lange-Hegermann on 11.09.25.
//

import Foundation

enum UnitSystem: String, CaseIterable {
    case metric = "metric"
    case imperial = "imperial"
    
    var displayName: String {
        switch self {
        case .metric:
            return String(localized: "units.metric.display", comment: "Display name for the metric unit system")
        case .imperial:
            return String(localized: "units.imperial.display", comment: "Display name for the imperial unit system")
        }
    }
    
    var wireAreaUnit: String {
        switch self {
        case .metric:
            return "mm²"
        case .imperial:
            return "AWG"
        }
    }
    
    var lengthUnit: String {
        switch self {
        case .metric:
            return "m"
        case .imperial:
            return "ft"
        }
    }
}

enum LocaleDefaults {
    private static let lowVoltageRegions: Set<String> = [
        "US", "CA", "MX", "JP", "TW", "CO", "VE", "BR"
    ]

    static var mainsVoltage: Double {
        let region = Locale.current.region?.identifier.uppercased() ?? ""
        return lowVoltageRegions.contains(region) ? 120.0 : 230.0
    }
}

@MainActor
class UnitSystemSettings: ObservableObject {
    @Published var unitSystem: UnitSystem {
        didSet {
            UserDefaults.standard.set(unitSystem.rawValue, forKey: "unitSystem")
            AnalyticsTracker.log("Unit System Changed", properties: ["system": unitSystem.rawValue])
        }
    }

    init() {
        if let saved = UserDefaults.standard.string(forKey: "unitSystem"),
           let system = UnitSystem(rawValue: saved) {
            self.unitSystem = system
        } else {
            self.unitSystem = Locale.current.measurementSystem == .us ? .imperial : .metric
        }
    }
}
