import SwiftUI

/// 登录界面：输入用户名/密码，调用 ViewModel.login 保存令牌后进入主界面。
struct LoginView: View {
    @ObservedObject var viewModel: ControllerViewModel

    @State private var username: String = ""
    @State private var password: String = ""

    var body: some View {
        NavigationView {
            Form {
                Section("账号登录") {
                    TextField("用户名", text: $username)
                        .textInputAutocapitalization(.never)
                        .autocorrectionDisabled()
                    SecureField("密码", text: $password)
                }

                if let err = viewModel.loginError, !err.isEmpty {
                    Section {
                        Text(err).foregroundColor(.red)
                    }
                }

                Section {
                    Button {
                        Task {
                            await viewModel.login(username: username, password: password)
                        }
                    } label: {
                        HStack {
                            Spacer()
                            if viewModel.isLoggingIn {
                                ProgressView().padding(.trailing, 8)
                            }
                            Text(viewModel.isLoggingIn ? "登录中..." : "登录")
                                .font(.system(size: 15, weight: .semibold))
                            Spacer()
                        }
                    }
                    .disabled(viewModel.isLoggingIn || username.isEmpty || password.isEmpty)
                } footer: {
                    Text("登录后才能连接信令服务器并发起远程控制。账号由服务端统一创建与管控。")
                }
            }
            .navigationTitle("WebRTC 控制端")
        }
        .navigationViewStyle(.stack)
    }
}
