import SwiftUI

struct PasswordResetFlow: View {
    @StateObject private var viewModel: PasswordResetViewModel
    @Environment(\.dismiss) var dismiss
    var onLoginSuccess: ((Bool) -> Void)?

    init(resetToken: String? = nil, onLoginSuccess: ((Bool) -> Void)? = nil) {
        _viewModel = StateObject(wrappedValue: PasswordResetViewModel(resetToken: resetToken))
        self.onLoginSuccess = onLoginSuccess
    }

    var body: some View {
        NavigationStack {
            Group {
                switch viewModel.currentStep {
                case .requestCode:
                    ForgotPasswordView(viewModel: viewModel)
                case .verifyCode:
                    VerifyResetCodeView(viewModel: viewModel)
                case .resetPassword, .loggingIn, .success:
                    ResetPasswordView(viewModel: viewModel, onSuccess: {
                        dismiss()
                    })
                }
            }
            .animation(.easeInOut, value: viewModel.currentStep)
        }
        .onAppear {
            // Set up callback for auto-login success
            // Capture dismiss and onLoginSuccess directly to avoid holding the entire view struct
            let dismissAction = dismiss
            let loginHandler = onLoginSuccess
            viewModel.onLoginSuccess = { isVerified in
                dismissAction()
                loginHandler?(isVerified)
            }
        }
    }
}

#Preview("Normal Flow") {
    PasswordResetFlow()
}

#Preview("Deep Link Flow") {
    PasswordResetFlow(resetToken: "sample-token-from-deep-link")
}
