import SwiftUI

// MARK: - Dark Mode System
// DarkModeWrapper: applies overrideUserInterfaceStyle via @AppStorage.
// DarkModeButton: toggles theme (no animation — all snapshot approaches cause white/black flash).

// MARK: - DarkModeWrapper

struct DarkModeWrapper<Content: View>: View {
    @ViewBuilder var content: Content
    @AppStorage("rosetta_theme_mode") private var themeModeRaw: String = "system"

    var body: some View {
        content
            .onAppear {
                let defaults = UserDefaults.standard
                if defaults.object(forKey: "rosetta_theme_mode") == nil,
                   let legacy = defaults.object(forKey: "rosetta_dark_mode") as? Bool {
                    themeModeRaw = legacy ? "dark" : "light"
                    defaults.removeObject(forKey: "rosetta_dark_mode")
                }
            }
            .onChange(of: themeModeRaw, initial: true) { _, newValue in
                applyTheme(newValue)
            }
    }

    private func applyTheme(_ mode: String) {
        guard let windowScene = activeWindowScene else { return }
        let style: UIUserInterfaceStyle
        switch mode {
        case "light": style = .light
        case "system": style = .unspecified
        default: style = .dark
        }
        // CRITICAL: use dynamic UIColor — auto-resolves on trait change.
        // Static colors (.white / .black) cause white/black screen flash because
        // rootViewController.view.backgroundColor stays stale during SwiftUI re-render.
        let bgColor = UIColor { $0.userInterfaceStyle == .dark ? .black : .white }
        for window in windowScene.windows {
            window.overrideUserInterfaceStyle = style
            window.backgroundColor = bgColor
            window.rootViewController?.view.backgroundColor = bgColor
        }
    }

    private var activeWindowScene: UIWindowScene? {
        let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }
        return scenes.first(where: { $0.activationState == .foregroundActive }) ?? scenes.first
    }
}

// MARK: - DarkModeButton

struct DarkModeButton: View {
    @AppStorage("rosetta_theme_mode") private var themeModeRaw: String = "system"

    private var isMoon: Bool {
        switch themeModeRaw {
        case "light": return false
        case "dark": return true
        default: return UIScreen.main.traitCollection.userInterfaceStyle == .dark
        }
    }

    var body: some View {
        Button {
            // Theme switching temporarily disabled
        } label: {
            Image(systemName: isMoon ? "moon.fill" : "sun.max.fill")
                .font(.system(size: 16, weight: .medium))
                .foregroundStyle(RosettaColors.Adaptive.text)
                .symbolEffect(.bounce, value: isMoon)
                .frame(width: 44, height: 44)
        }
        .buttonStyle(.plain)
    }
}
