import AppKit
import AppKit
import SwiftUI

@main
struct FchatiApp: App {
    var body: some Scene {
        WindowGroup("Fchati") {
            RootView()
        }
        .defaultSize(width: 420, height: 560)

        MenuBarExtra("Fchati", systemImage: "message") {
            RootView()
                .background(WindowConfigurator())
        }
        .menuBarExtraStyle(.window)
    }
}

// Prevents the popover from closing when clicking outside.
private struct WindowConfigurator: NSViewRepresentable {
    func makeNSView(context: Context) -> NSView {
        let view = NSView()
        DispatchQueue.main.async {
            guard let window = view.window else { return }
            window.level = .floating
            window.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary]
            window.isMovableByWindowBackground = false
        }
        return view
    }

    func updateNSView(_ nsView: NSView, context: Context) {}
}

enum AppTab: String, CaseIterable, Identifiable {
    case chat = "Chat"
    case pairing = "Pairing"
    case settings = "Settings"

    var id: Self { self }

    var title: String {
        rawValue
    }

    var icon: String {
        switch self {
        case .chat:
            "message"
        case .pairing:
            "link"
        case .settings:
            "gearshape"
        }
    }
}

private struct RootView: View {
    @State private var selectedTab: AppTab = .pairing

    var body: some View {
        VStack(spacing: 0) {
            HStack(spacing: 8) {
                Picker("Section", selection: $selectedTab) {
                    ForEach(AppTab.allCases) { tab in
                        Label(tab.title, systemImage: tab.icon)
                            .tag(tab)
                    }
                }
                .pickerStyle(.segmented)
                .labelsHidden()

                Button {
                    NSApplication.shared.terminate(nil)
                } label: {
                    Image(systemName: "power")
                }
                .accessibilityLabel("Quit Fchati")
                .help("Quit Fchati")
            }
            .padding()

            Divider()

            Group {
                switch selectedTab {
                case .chat:
                    ChatView()
                case .pairing:
                    PairingView {
                        selectedTab = .chat
                    }
                case .settings:
                    SettingsView()
                }
            }
            .frame(maxWidth: .infinity, maxHeight: .infinity)
        }
        .frame(minWidth: 360, idealWidth: 420, maxWidth: 640)
        .frame(minHeight: 480)
    }
}
