//
//  MainMenuBar.swift
//  punchnet
//
//  Created by 安礼成 on 2026/3/24.
//

import SwiftUI

struct MainMenuBar: View {
    @State private var vpnManager = VPNManager.shared
    @Environment(AppContext.self) private var appContext: AppContext
    @Environment(\.openWindow) private var openWindow

    var body: some View {
        VStack {
            switch self.vpnManager.vpnStatus {
            case .connected:
                Button(action: {
                    Task { @MainActor in
                        try await appContext.stopTun()
                    }
                }, label: {
                    Text("停止")
                })
            case .connecting:
                Button(action: {
                }, label: {
                    Text("连接中...")
                })
                .disabled(true)
            case .disconnecting:
                Button(action: {
                }, label: {
                    Text("断开中...")
                })
                .disabled(true)
            case .disconnected:
                Button(action: {
                    Task { @MainActor in
                        await self.startVPN()
                    }
                }, label: {
                    Text("启动")
                })
            }
            
            Divider()
            
            Button("打开控制面板") {
                openWindow(id: "main")
                NSApp.activate(ignoringOtherApps: true)
            }
            
            SettingsLink {
                Text("设置")
            }
            .buttonStyle(.plain)
            
            Divider()
            
            Button("退出应用") {
                NSApplication.shared.terminate(nil)
            }
            
        }
    }
    
    private func startVPN() async {
        do {
            if appContext.networkContext == nil {
                try await appContext.connectNetwork()
            }
            try await appContext.startTun()
        } catch {
            NSLog("menu start vpn failed: \(error)")
        }
    }
    
}
