//
//  MenuContentView.swift
//  SwanDesk — the MenuBarExtra dropdown.
//

import SwiftUI

struct MenuContentView: View {
    @Bindable var connection: ConnectionManager
    @Bindable var store: ProfileStore
    @Environment(\.openWindow) private var openWindow

    var body: some View {
        // Status line
        Text(connection.stateText)

        Divider()

        if store.profiles.isEmpty {
            Text("No profiles configured")
            Button("Add a Profile…") { openConfig(.connections) }
        } else {
            ForEach(store.profiles) { profile in
                profileButton(profile)
            }
        }

        if connection.isConnected || connection.status.state == .connecting || connection.status.state == .reconnecting {
            Divider()
            Button("Disconnect") { connection.disconnect() }
                .disabled(connection.busy)
        }

        Divider()

        Button("Configuration…") { openConfig(.connections) }
            .keyboardShortcut(",", modifiers: .command)
        Button("Show Log…") { openConfig(.log) }
        Button("About SwanDesk") { AboutPanel.present() }
        Divider()
        Button("Quit SwanDesk") { NSApp.terminate(nil) }
            .keyboardShortcut("q", modifiers: .command)
    }

    @ViewBuilder
    private func profileButton(_ profile: VPNProfile) -> some View {
        let isActive = connection.status.profileID == profile.id.uuidString && connection.isConnected
        Button {
            if isActive {
                connection.disconnect()
            } else {
                connection.connect(profile: profile, secrets: store.secrets(for: profile.id))
            }
        } label: {
            Text(isActive ? "✓ \(profile.name)" : profile.name)
        }
        .disabled(connection.busy)
    }

    private func openConfig(_ tab: ConfigTab) {
        ConfigWindowModel.shared.selectedTab = tab
        NSApp.activate(ignoringOtherApps: true)
        openWindow(id: "config")
    }
}
