import SwiftUI

struct LoginTopBar: View {
    let openLanguageSettings: () -> Void
    let onShowModePrompt: (() -> Void)?
    @EnvironmentObject private var themeManager: ThemeManager
    @Environment(\.colorScheme) private var colorScheme
    private let themeOptions = ThemeOption.ordered

    var body: some View {
        HStack {
            Button(action: openLanguageSettings) {
                Text("🌍")
                    .padding(8)
            }
            Spacer()
            if let onShowModePrompt {
                Button(action: onShowModePrompt) {
                    Text(NSLocalizedString("Режим", comment: ""))
                        .font(.footnote.bold())
                }
                Spacer()
            }
            Menu {
                ForEach(themeOptions) { option in
                    Button(action: { selectTheme(option) }) {
                        themeMenuContent(for: option)
                            .opacity(option.isEnabled ? 1.0 : 0.5)
                    }
                    .disabled(!option.isEnabled)
                }
            } label: {
                Image(systemName: themeIconName)
                    .padding(8)
            }
        }
    }

    private var selectedThemeOption: ThemeOption {
        ThemeOption.option(for: themeManager.theme)
    }

    private var themeIconName: String {
        switch themeManager.theme {
        case .system:
            return colorScheme == .dark ? "moon.fill" : "sun.max.fill"
        case .light:
            return "sun.max.fill"
        case .oledDark:
            return "moon.fill"
        }
    }

    private func themeMenuContent(for option: ThemeOption) -> some View {
        let isSelected = option == selectedThemeOption

        return HStack(spacing: 8) {
            Image(systemName: isSelected ? "checkmark.circle.fill" : "circle")
                .foregroundColor(isSelected ? .accentColor : .secondary)
            VStack(alignment: .leading, spacing: 2) {
                Text(option.title)
                if let note = option.note {
                    Text(note)
                        .font(.caption)
                        .foregroundColor(.secondary)
                }
            }
        }
    }

    private func selectTheme(_ option: ThemeOption) {
        guard let mappedTheme = option.mappedTheme else { return }
        themeManager.setTheme(mappedTheme)
    }
}
