//
//  CameraSettings.swift
//  CameraTester
//
//  Created by Matt Bruce on 1/3/26.
//

import SwiftUI

/// Persistent camera settings stored in UserDefaults
struct CameraSettings: Codable {
    var photoQuality: PhotoQuality
    var isRingLightEnabled: Bool
    var ringLightColor: Color
    var ringLightSize: CGFloat
    var ringLightOpacity: Double
    var flashMode: CameraFlashMode
    var isFlashSyncedWithRingLight: Bool

    // Default settings
    static let `default` = CameraSettings(
        photoQuality: .high,
        isRingLightEnabled: true,
        ringLightColor: .white,
        ringLightSize: 25,
        ringLightOpacity: 1.0,
        flashMode: .off,
        isFlashSyncedWithRingLight: false
    )

    // UserDefaults keys
    private enum Keys {
        static let cameraSettings = "cameraSettings"
    }

    // MARK: - Persistence

    /// Save settings to UserDefaults
    func save() {
        let encoder = JSONEncoder()
        do {
            let data = try encoder.encode(self)
            UserDefaults.standard.set(data, forKey: Keys.cameraSettings)
            UserDefaults.standard.synchronize()
        } catch {
            print("Failed to save camera settings: \(error)")
        }
    }

    /// Load settings from UserDefaults, or return defaults if none exist
    static func load() -> CameraSettings {
        guard let data = UserDefaults.standard.data(forKey: Keys.cameraSettings) else {
            return .default
        }

        let decoder = JSONDecoder()
        do {
            return try decoder.decode(CameraSettings.self, from: data)
        } catch {
            print("Failed to load camera settings, using defaults: \(error)")
            return .default
        }
    }

    /// Reset settings to defaults and save
    static func reset() {
        let settings = CameraSettings.default
        settings.save()
    }
}
