import SwiftUI

struct AuthView: View {
    @EnvironmentObject private var router: AppRouter
    @ObservedObject var viewModel: AuthViewModel

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

            Text("Bookibra")
                .font(Theme.headerSerif(size: 48))
                .foregroundStyle(.black)

            Picker("Mode", selection: $viewModel.mode) {
                Text(String(localized: "auth.login")).tag(AuthViewModel.Mode.login)
                Text(String(localized: "auth.register")).tag(AuthViewModel.Mode.register)
            }
            .pickerStyle(.segmented)
            .padding(.horizontal, 24)

            VStack(spacing: 14) {
                TextField(String(localized: "auth.email"), text: $viewModel.email)
                    .textInputAutocapitalization(.never)
                    .keyboardType(.emailAddress)
                    .padding()
                    .background(Color.white, in: RoundedRectangle(cornerRadius: 12))

                SecureField(String(localized: "auth.password"), text: $viewModel.password)
                    .padding()
                    .background(Color.white, in: RoundedRectangle(cornerRadius: 12))
            }
            .padding(.horizontal, 24)

            if let error = viewModel.errorMessage {
                Text(error)
                    .font(.footnote)
                    .foregroundStyle(.red)
                    .padding(.horizontal, 24)
                    .multilineTextAlignment(.center)
            }

            Button {
                Task {
                    await viewModel.submit {
                        router.isAuthenticated = true
                    }
                }
            } label: {
                if viewModel.isLoading {
                    ProgressView()
                        .tint(.white)
                        .frame(maxWidth: .infinity)
                        .padding(.vertical, 16)
                } else {
                    Text(String(localized: "auth.continue"))
                        .font(.headline)
                        .foregroundStyle(.white)
                        .frame(maxWidth: .infinity)
                        .padding(.vertical, 16)
                }
            }
            .background(Color.black)
            .clipShape(Capsule())
            .padding(.horizontal, 24)

            Spacer()
        }
        .background(Theme.background.ignoresSafeArea())
    }
}
