import SwiftUI

struct LoginView: View {
    @Environment(AuthManager.self) private var auth
    @State private var username = ""
    @State private var password = ""
    @State private var isLoading = false

    var body: some View {
        VStack(spacing: 32) {
            Spacer()

            VStack(spacing: 8) {
                Image(systemName: "square.grid.2x2.fill")
                    .font(.system(size: 48))
                    .foregroundStyle(Color.accentWarm)
                Text("Platform")
                    .font(.largeTitle.weight(.bold))
                    .foregroundStyle(Color.textPrimary)
                Text("Sign in to your account")
                    .font(.subheadline)
                    .foregroundStyle(Color.textSecondary)
            }

            VStack(spacing: 16) {
                TextField("Username", text: $username)
                    .textFieldStyle(.roundedBorder)
                    .textContentType(.username)
                    .autocorrectionDisabled()
                    .textInputAutocapitalization(.never)

                SecureField("Password", text: $password)
                    .textFieldStyle(.roundedBorder)
                    .textContentType(.password)

                if let error = auth.error {
                    Text(error)
                        .font(.caption)
                        .foregroundStyle(.red)
                        .frame(maxWidth: .infinity, alignment: .leading)
                }

                Button {
                    isLoading = true
                    Task {
                        await auth.login(username: username, password: password)
                        isLoading = false
                    }
                } label: {
                    if isLoading {
                        ProgressView()
                            .tint(.white)
                    } else {
                        Text("Sign In")
                            .font(.headline)
                    }
                }
                .frame(maxWidth: .infinity)
                .frame(height: 48)
                .background(Color.accentWarm)
                .foregroundStyle(.white)
                .clipShape(RoundedRectangle(cornerRadius: 12))
                .disabled(username.isEmpty || password.isEmpty || isLoading)
                .opacity(username.isEmpty || password.isEmpty ? 0.6 : 1)
            }
            .padding(.horizontal, 32)

            Spacer()
            Spacer()
        }
        .background(Color.canvas)
    }
}
